Wifi Connection after a failed attempt

Giovanni
Posts: 1
Joined: Thu Aug 22, 2024 12:24 pm

Wifi Connection after a failed attempt

Postby Giovanni » Thu Aug 22, 2024 12:32 pm

Hi, I am developing a wifi connection code, my esp32 WROOM 32E module connects via Bluetooth and receives a message from an application containing the SSID and PASSWORD credentials of the wifi network. If I enter the correct credentials directly the module connects and works. If I enter the wrong credentials and then enter the correct ones the connection does not take place. How can I solve this ?
Attached is a screen of the output when I enter the correct credentials after the incorrect ones.
Thanks for the support.

Code: Select all

#include <string.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <inttypes.h>
#include "esp_bt.h"
#include "esp_bt_main.h"
#include "esp_gap_bt_api.h"
#include "esp_bt_device.h"
#include "esp_spp_api.h"
#include "spp_task.h"
#include "time.h"
#include "sys/time.h"
#include "esp_vfs.h"
#include "sys/unistd.h"
#include "esp_partition.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_system.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_log.h"
#include "nvs_flash.h"

#include "lwip/err.h"
#include "lwip/sys.h"

//----------------------------------------------- BLOCCO DICHIARAZINI WIFI ---------------------------------------------------------------------------------------
#define EXAMPLE_ESP_MAXIMUM_RETRY  3
#if CONFIG_ESP_WPA3_SAE_PWE_HUNT_AND_PECK
#define ESP_WIFI_SAE_MODE WPA3_SAE_PWE_HUNT_AND_PECK
#define EXAMPLE_H2E_IDENTIFIER ""
#elif CONFIG_ESP_WPA3_SAE_PWE_HASH_TO_ELEMENT
#define ESP_WIFI_SAE_MODE WPA3_SAE_PWE_HASH_TO_ELEMENT
#define EXAMPLE_H2E_IDENTIFIER CONFIG_ESP_WIFI_PW_ID
#elif CONFIG_ESP_WPA3_SAE_PWE_BOTH
#define ESP_WIFI_SAE_MODE WPA3_SAE_PWE_BOTH
#define EXAMPLE_H2E_IDENTIFIER CONFIG_ESP_WIFI_PW_ID
#endif
#if CONFIG_ESP_WIFI_AUTH_OPEN
#define ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD WIFI_AUTH_OPEN
#elif CONFIG_ESP_WIFI_AUTH_WEP
#define ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD WIFI_AUTH_WEP
#elif CONFIG_ESP_WIFI_AUTH_WPA_PSK
#define ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD WIFI_AUTH_WPA_PSK
#elif CONFIG_ESP_WIFI_AUTH_WPA2_PSK
#define ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD WIFI_AUTH_WPA2_PSK
#elif CONFIG_ESP_WIFI_AUTH_WPA_WPA2_PSK
#define ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD WIFI_AUTH_WPA_WPA2_PSK
#elif CONFIG_ESP_WIFI_AUTH_WPA3_PSK
#define ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD WIFI_AUTH_WPA3_PSK
#elif CONFIG_ESP_WIFI_AUTH_WPA2_WPA3_PSK
#define ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD WIFI_AUTH_WPA2_WPA3_PSK
#elif CONFIG_ESP_WIFI_AUTH_WAPI_PSK
#define ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD WIFI_AUTH_WAPI_PSK
#endif
static EventGroupHandle_t s_wifi_event_group;
#define WIFI_CONNECTED_BIT BIT0
#define WIFI_FAIL_BIT      BIT1
static const char *TAG = "wifi station";
static int s_retry_num = 0;
void wifi_init_sta(void);
//----------------------------------------------- BLOCCO DICHIARAZIONI BLUETOOTH ---------------------------------------------------------------------------------------
#define SPP_TAG "SPP_ACCEPTOR_DEMO"
#define SPP_SERVER_NAME "SPP_SERVER"
#define EXAMPLE_DEVICE_NAME "AMI_ESP"
static const esp_spp_sec_t sec_mask = ESP_SPP_SEC_NONE;
static const esp_spp_role_t role_slave = ESP_SPP_ROLE_SLAVE;
void Write_Partition(char* Part,int SzPart, char* addr, int SzAddr);
#define SPP_DATA_LEN 100
int SzPartSSID;
int SzPartPSWD;
char prefix_pass[6] = "PSWD:";
char start[6] = "START";
char prefix_ssid[6] = "SSID:";
char PartitionPASS[5] = "PSWD";
char PartitionSSID[5] = "SSID";
char SSID[25];
char PSWD[25];
char *wifi_ssid;
char *wifi_pass;
bool ssidrecived = false;
bool passrecived = false;
int SsidSize = 0, PassSize = 0;
//----------------------------------------------- BLOCCO BLUETOOTH ---------------------------------------------------------------------------------------
const unsigned char *find_byte(const unsigned char *data, size_t size, unsigned char byte) {
    for (size_t i = 0; i < size; i++) {
        if (data[i] == byte) {
            return &data[i];
        }
    }
    return NULL;
}
void Disconnect_BT()
{
    esp_spp_deinit();
    esp_bluedroid_disable();
    esp_bt_controller_disable();
    esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT);
}
static char *bda2str(uint8_t * bda, char *str, size_t size)
{
    if (bda == NULL || str == NULL || size < 18)  return NULL;
    uint8_t *p = bda;
    sprintf(str, "%02x:%02x:%02x:%02x:%02x:%02x", p[0], p[1], p[2], p[3], p[4], p[5]);
    return str;
}
static void spp_read_handle(void * param)
{
    int size = 0;
    int fd = (int)param;
    uint8_t *spp_data = NULL;
    spp_data = malloc(SPP_DATA_LEN);
    const unsigned char end_marker[] = {0x0D, 0x0A}; // Line terminator CR LF
    if (!spp_data) 
    {
        ESP_LOGE(SPP_TAG, "malloc spp_data failed, fd:%d", fd);
        goto done;
    }
    do 
    {
        /* The frequency of calling this function also limits the speed at which the peer device can send data. */
        size = read(fd, spp_data, SPP_DATA_LEN);      
        if (size < 0) break;
        else if (size == 0) vTaskDelay(500 / portTICK_PERIOD_MS); /* There is no data, retry after 500 ms */ 
        else 
        {                 
            if (memcmp(spp_data, prefix_ssid, 5) == 0) // Save the ssid
            {
                const unsigned char *end_pos = find_byte(spp_data + sizeof(prefix_ssid), size - sizeof(prefix_ssid), end_marker[0]);          
                SsidSize = (end_pos - spp_data) - sizeof(prefix_ssid) + 3; // deve contenere anche 00 0D 0A               
                wifi_ssid = (char *)malloc(SsidSize + 1);
                memcpy(wifi_ssid, &spp_data[5], SsidSize); 
                wifi_ssid[SsidSize - 2] = '\0';  // Aggiungere il terminatore di stringa
                wifi_ssid[SsidSize - 1] = '\r';  // Aggiungere CR
                wifi_ssid[SsidSize] = '\n';  // Aggiungere LF                       
                ssidrecived = true;               
                //Write_Partition(PartitionSSID,SzPartSSID,wifi_ssid,SizeSSID+1);
                int StartPass = 5 + SsidSize;   
                if(spp_data[StartPass] == 0x50 && spp_data[StartPass+1] == 0x53 && spp_data[StartPass+2] == 0x57 &&
                   spp_data[StartPass+3] == 0x44 && spp_data[StartPass+4] == 0x3A ) 
                   {                       
                        StartPass=StartPass+5;
                        PassSize = size - StartPass - 7;                       
                        wifi_pass = (char *)malloc(PassSize + 1);
                        memcpy(wifi_pass, &spp_data[StartPass], PassSize);
                        wifi_pass[PassSize - 2] = '\0';  // Aggiungere il terminatore di stringa
                        wifi_pass[PassSize - 1] = '\r';  // Aggiungere CR
                        wifi_pass[PassSize] = '\n';  // Aggiungere LF                        
                        passrecived = true;
                        int StartInit = size -7;                          
                        if(spp_data[StartInit] == 0x53 && spp_data[StartInit+1] == 0x54 && spp_data[StartInit+2] == 0x41 && 
                        spp_data[StartInit+3] == 0x52 && spp_data[StartInit+4] == 0x54)
                        {                          
                            SsidSize = SsidSize + 1; // MODIFICO LE DIMENSIONI PER IL SALVATAGGIO IN NVS
                            PassSize = PassSize + 1;                                                
                            if(passrecived && ssidrecived)  wifi_init_sta();  
                        }
                   }
            }             
            vTaskDelay(10/portTICK_PERIOD_MS);             /* To avoid task watchdog */
        }
    } while (1);
done:
    if (spp_data) free(spp_data);
    spp_wr_task_shut_down();
}
static void esp_spp_cb(uint16_t e, void *p)
{
    esp_spp_cb_event_t event = e;
    esp_spp_cb_param_t *param = p;
    char bda_str[18] = {0};
    switch (event) 
    {
        case ESP_SPP_INIT_EVT:
            if (param->init.status == ESP_SPP_SUCCESS) 
            {
                ESP_LOGI(SPP_TAG, "ESP_SPP_INIT_EVT");            
                esp_spp_vfs_register();     /* Enable SPP VFS mode */
            } 
            else  ESP_LOGE(SPP_TAG, "ESP_SPP_INIT_EVT status:%d", param->init.status);
            break;
        case ESP_SPP_DISCOVERY_COMP_EVT:
            ESP_LOGI(SPP_TAG, "ESP_SPP_DISCOVERY_COMP_EVT");
            break;

        case ESP_SPP_OPEN_EVT:
            ESP_LOGI(SPP_TAG, "ESP_SPP_OPEN_EVT");
            break;

        case ESP_SPP_CLOSE_EVT:
            ESP_LOGI(SPP_TAG, "ESP_SPP_CLOSE_EVT status:%d handle:%"PRIu32" close_by_remote:%d", param->close.status, param->close.handle, param->close.async);
            break;

        case ESP_SPP_START_EVT:
            if (param->start.status == ESP_SPP_SUCCESS) 
            {
                ESP_LOGI(SPP_TAG, "ESP_SPP_START_EVT handle:%"PRIu32" sec_id:%d scn:%d", param->start.handle, param->start.sec_id, param->start.scn);
                esp_bt_dev_set_device_name(EXAMPLE_DEVICE_NAME);
                esp_bt_gap_set_scan_mode(ESP_BT_CONNECTABLE, ESP_BT_GENERAL_DISCOVERABLE);
            } 
            else  ESP_LOGE(SPP_TAG, "ESP_SPP_START_EVT status:%d", param->start.status);
            break;

        case ESP_SPP_CL_INIT_EVT:
            ESP_LOGI(SPP_TAG, "ESP_SPP_CL_INIT_EVT");
            break;

        case ESP_SPP_SRV_OPEN_EVT:
            ESP_LOGI(SPP_TAG, "ESP_SPP_SRV_OPEN_EVT status:%d handle:%"PRIu32", rem_bda:[%s]", param->srv_open.status, param->srv_open.handle, bda2str(param->srv_open.rem_bda, bda_str, sizeof(bda_str)));
            if (param->srv_open.status == ESP_SPP_SUCCESS)  spp_wr_task_start_up(spp_read_handle, param->srv_open.fd);
            break;

        case ESP_SPP_VFS_REGISTER_EVT:
            if (param->vfs_register.status == ESP_SPP_SUCCESS) 
            {
                ESP_LOGI(SPP_TAG, "ESP_SPP_VFS_REGISTER_EVT");
                esp_spp_start_srv(sec_mask, role_slave, 0, SPP_SERVER_NAME);
            } 
            else  ESP_LOGE(SPP_TAG, "ESP_SPP_VFS_REGISTER_EVT status:%d", param->vfs_register.status);
            break;

        default:
            break;
    }
}
static void esp_spp_stack_cb(esp_spp_cb_event_t event, esp_spp_cb_param_t *param)
{
    spp_task_work_dispatch(esp_spp_cb, event, param, sizeof(esp_spp_cb_param_t), NULL);
}
void esp_bt_gap_cb(esp_bt_gap_cb_event_t event, esp_bt_gap_cb_param_t *param)
{
    switch (event) 
    {
        case ESP_BT_GAP_AUTH_CMPL_EVT:
        {
            if (param->auth_cmpl.stat == ESP_BT_STATUS_SUCCESS) 
            {
                ESP_LOGI(SPP_TAG, "authentication success: %s", param->auth_cmpl.device_name);
                esp_log_buffer_hex(SPP_TAG, param->auth_cmpl.bda, ESP_BD_ADDR_LEN);
            } 
            else  ESP_LOGE(SPP_TAG, "authentication failed, status:%d", param->auth_cmpl.stat);
            break;
        }

        case ESP_BT_GAP_PIN_REQ_EVT:
        {
            ESP_LOGI(SPP_TAG, "ESP_BT_GAP_PIN_REQ_EVT min_16_digit:%d", param->pin_req.min_16_digit);
            if (param->pin_req.min_16_digit) 
            {
                ESP_LOGI(SPP_TAG, "Input pin code: 0000 0000 0000 0000");
                esp_bt_pin_code_t pin_code = {0};
                esp_bt_gap_pin_reply(param->pin_req.bda, true, 16, pin_code);
            } 
            else 
            {                
                esp_bt_pin_code_t pin_code;
                pin_code[0] = '5';
                pin_code[1] = '2';
                pin_code[2] = '8';
                pin_code[3] = '1';
                esp_bt_gap_pin_reply(param->pin_req.bda, true, 4, pin_code);
            }
            break;            
        }

    #if (CONFIG_BT_SSP_ENABLED == true)
        case ESP_BT_GAP_CFM_REQ_EVT:
            ESP_LOGI(SPP_TAG, "ESP_BT_GAP_CFM_REQ_EVT Please compare the numeric value: %"PRIu32, param->cfm_req.num_val);
            esp_bt_gap_ssp_confirm_reply(param->cfm_req.bda, true);
            break;

        case ESP_BT_GAP_KEY_NOTIF_EVT:
            ESP_LOGI(SPP_TAG, "ESP_BT_GAP_KEY_NOTIF_EVT passkey:%"PRIu32, param->key_notif.passkey);
            break;

        case ESP_BT_GAP_KEY_REQ_EVT:
            ESP_LOGI(SPP_TAG, "ESP_BT_GAP_KEY_REQ_EVT Please enter passkey!");
            break;
    #endif
        case ESP_BT_GAP_MODE_CHG_EVT:
            ESP_LOGI(SPP_TAG, "ESP_BT_GAP_MODE_CHG_EVT mode:%d", param->mode_chg.mode);
            break;

        default: 
        {
            ESP_LOGI(SPP_TAG, "event: %d", event);
            break;
        }
    }
    return;
}
//----------------------------------------------- BLOCCO NVS ---------------------------------------------------------------------------------------
char* find_sequence(const char *data, size_t data_size, const char *sequence, size_t sequence_size) 
{
    for (size_t i = 0; i <= data_size - sequence_size; i++) 
    {
        if (memcmp(&data[i], sequence, sequence_size) == 0) return (char*)&data[i];
    }
    return NULL; // Sequenza non trovata
}
bool Read_Partition(char* Part,int Sz)
{
    bool end = false;
    char PartitionAddr[Sz];
    strcpy(PartitionAddr,Part);       
    const esp_partition_t *partition = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_ANY, PartitionAddr);
    assert(partition != NULL);    
    const void *map_ptr;
    esp_partition_mmap_handle_t map_handle;   
    esp_partition_mmap(partition, 0, partition->size, ESP_PARTITION_MMAP_DATA, &map_ptr, &map_handle);
    char read_data[30];   
    size_t read_data_size = sizeof(read_data);
    memcpy(read_data, map_ptr, sizeof(read_data)); 
    if(read_data[0] == (char) 0xFF && read_data[1] == (char) 0xFF && read_data[2] == (char) 0xFF)
    {      
        end = true;
        if(strncmp(PartitionAddr, PartitionSSID, 5) == 0) printf("SSID true\n");
        if(strncmp(PartitionAddr, PartitionPASS, 5) == 0) printf("PSWD true\n");
    }
    else
    {        
        if(strncmp(PartitionAddr, PartitionSSID, 5) == 0)
        {           
            char sequence[] = {0x00, 0x0D, 0x0A};   // Sequenza da cercare: 00 0D 0A
            size_t sequence_size = sizeof(sequence);
            char *end = (char*)find_sequence(read_data, read_data_size, sequence, sequence_size);
            if (end != NULL) 
            {      
                size_t length = end - read_data;
                wifi_ssid = (char *)malloc(length);
                if (wifi_ssid == NULL) 
                {
                    perror("Impossibile allocare memoria");
                    return 1;
                }           
                strncpy(wifi_ssid, read_data, length);
                wifi_ssid[length] = 0x00;
                printf("SSID read = ");          
                for(int i =0; i<= length;i++)
                {
                    printf("%02X ", wifi_ssid[i]);
                }
                printf("\n");      
            }
            else printf("\n Sequenza non trovata \n");
        }
        if (strncmp(PartitionAddr, PartitionPASS, 5) == 0)
        {
            char sequence[] = {0x00, 0x0D, 0x0A};   // Sequenza da cercare: 00 0D 0A
            size_t sequence_size = sizeof(sequence);
            char *end = (char*)find_sequence(read_data, read_data_size, sequence, sequence_size);           
            if (end != NULL) 
            {      
                size_t length = end - read_data ;
                wifi_pass = (char *)malloc(length);
                if (wifi_pass == NULL) 
                {
                    perror("Impossibile allocare memoria");
                    return 1;
                }   
                strncpy(wifi_pass, read_data, length);
                wifi_pass[length] = 0x00; 
                printf("PASS read = ");
                for(int i =0; i<= length;i++)
                {
                    printf("%02X ", wifi_pass[i]);
                }
                printf("\n");
            }        
        }
        end = false;
    }   
    esp_partition_munmap(map_handle);   
    return end;
}
void Write_Partition(char* Part,int SzPart, char* addr, int SzAddr)
{
    char PartitionAddr[SzPart];
    memcpy(PartitionAddr,Part,SzPart);  
    char store_data[SzAddr];
    memcpy(store_data,addr,SzAddr);        
    const esp_partition_t *partition = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_ANY, PartitionAddr);
    assert(partition != NULL);        
    esp_partition_erase_range(partition, 0, partition->size); // Pulisco prima di scrivere
    esp_partition_write(partition, 0, store_data, sizeof(store_data));
}
void Init_Flash()
{    
    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 );
}
//----------------------------------------------- BLOCCO WIFI ---------------------------------------------------------------------------------------


static void event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data)
{
    if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START)  esp_wifi_connect();    
    else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) 
    {
        if (s_retry_num < EXAMPLE_ESP_MAXIMUM_RETRY) 
        {
            esp_wifi_connect();
            s_retry_num++;
            ESP_LOGI(TAG, "retry to connect to the AP");
        } 
        else xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT);
        ESP_LOGI(TAG,"connect to the AP fail");
    } 
    else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) 
    {
        ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
        ESP_LOGI(TAG, "got ip:" IPSTR, IP2STR(&event->ip_info.ip));
        s_retry_num = 0;
        xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
    }
}
void wifi_init_sta(void)
{    
    // Pulizia delle risorse
    esp_event_loop_delete_default();    // Elimina il loop degli eventi esistente
    esp_netif_t *netif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF");
    if (netif != NULL)  esp_netif_destroy(netif);
    
    // Inizializzazione del gruppo di eventi
    if (s_wifi_event_group == NULL)  s_wifi_event_group = xEventGroupCreate();

    ESP_ERROR_CHECK(esp_netif_init());
    ESP_ERROR_CHECK(esp_event_loop_create_default());        
    esp_netif_create_default_wifi_sta();  

    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&cfg));   

    esp_event_handler_instance_t instance_any_id; 
    esp_event_handler_instance_t instance_got_ip;
    ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &event_handler, NULL, &instance_any_id));
    ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &event_handler, NULL, &instance_got_ip));

    wifi_config_t wifi_config = {     
        .sta = {
            .ssid = "",
            .password = "",
            .threshold.authmode = ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD,
            .sae_pwe_h2e = ESP_WIFI_SAE_MODE,
            .sae_h2e_identifier = EXAMPLE_H2E_IDENTIFIER,
        },
    };

    strncpy((char*)wifi_config.sta.ssid, wifi_ssid, sizeof(wifi_config.sta.ssid) - 1);
    strncpy((char*)wifi_config.sta.password, wifi_pass, sizeof(wifi_config.sta.password) - 1);
    wifi_config.sta.ssid[sizeof(wifi_config.sta.ssid) - 1] = '\0';
    wifi_config.sta.password[sizeof(wifi_config.sta.password) - 1] = '\0';

    ESP_LOGI(TAG, "Configured SSID: %s", wifi_config.sta.ssid);
    ESP_LOGI(TAG, "Configured PASS: %s", wifi_config.sta.password);

    // Ferma e deinizializza il Wi-Fi se necessario
    ESP_ERROR_CHECK(esp_wifi_stop()); 
    ESP_ERROR_CHECK(esp_wifi_deinit()); 

    // Ripristina la configurazione Wi-Fi
    ESP_ERROR_CHECK(esp_wifi_init(&cfg)); 
    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
    ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config));
    ESP_ERROR_CHECK(esp_wifi_start());

    ESP_LOGI(TAG, "wifi_init_sta finished."); 
    EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group, WIFI_CONNECTED_BIT | WIFI_FAIL_BIT, pdFALSE, pdFALSE, 10000 / portTICK_PERIOD_MS); 

    if (bits & WIFI_CONNECTED_BIT) 
    {
        if (ssidrecived && passrecived) 
        {
            Write_Partition(PartitionSSID, SzPartSSID, wifi_ssid, SsidSize);
            Write_Partition(PartitionPASS, SzPartPSWD, wifi_pass, PassSize);
            Disconnect_BT();
        }
        ESP_LOGI(TAG, "connected to ap SSID:%s password:%s", wifi_ssid, wifi_pass);
    }
    else if (bits & WIFI_FAIL_BIT) 
    {
        ESP_LOGI(TAG, "Failed to connect to SSID:%s, password:%s", wifi_ssid, wifi_pass);
        esp_event_loop_delete_default();
        free(wifi_pass); 
        free(wifi_ssid);
        memset(wifi_config.sta.ssid, 0, sizeof(wifi_config.sta.ssid));
        memset(wifi_config.sta.password, 0, sizeof(wifi_config.sta.password));
    }
    else 
    {
        ESP_LOGE(TAG, "UNEXPECTED EVENT");
    }
}
//----------------------------------------------- BLOCCO MAIN ---------------------------------------------------------------------------------------
void app_main(void)
{     
    Init_Flash();
    SzPartSSID= sizeof(PartitionSSID);     
    SzPartPSWD = sizeof(PartitionPASS);
    bool RetSSID = Read_Partition(PartitionSSID,SzPartSSID);    
    bool RetPSWD = Read_Partition(PartitionPASS,SzPartPSWD);
    if(RetSSID == false && RetPSWD == false)  // STARTO LA COMUNICAZIONE WIFI 
    {
        printf("Init Wifi \n");
        wifi_init_sta();
    }
    else   // NON HO SALVATO LE CREDENZALI WIFI, MI PREDISPONGO AD ABILITARE IL BLUETOOTH
    {       
        printf("Init Bluetooth\n");
        esp_bt_controller_mem_release(ESP_BT_MODE_BLE);
        esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
        esp_bt_controller_init(&bt_cfg);   
        esp_bt_controller_enable(ESP_BT_MODE_CLASSIC_BT);   
        esp_bluedroid_init();    
        esp_bluedroid_enable();    
        esp_bt_gap_register_callback(esp_bt_gap_cb);
        esp_spp_register_callback(esp_spp_stack_cb);  
        spp_task_task_start_up();
        esp_spp_cfg_t bt_spp_cfg = BT_SPP_DEFAULT_CONFIG();
        esp_spp_enhanced_init(&bt_spp_cfg);
    
    #if (CONFIG_BT_SSP_ENABLED == true)
        /* Set default parameters for Secure Simple Pairing */
        esp_bt_sp_param_t param_type = ESP_BT_SP_IOCAP_MODE;
        esp_bt_io_cap_t iocap = ESP_BT_IO_CAP_IO;
        esp_bt_gap_set_security_param(param_type, &iocap, sizeof(uint8_t));
    #endif
        esp_bt_pin_type_t pin_type = ESP_BT_PIN_TYPE_VARIABLE;
        esp_bt_pin_code_t pin_code;
        esp_bt_gap_set_pin(pin_type, 0, pin_code);
    }    
}
Attachments
Immagine 2024-08-22 143120.png
Immagine 2024-08-22 143120.png (35.19 KiB) Viewed 340 times

MicroController
Posts: 1541
Joined: Mon Oct 17, 2022 7:38 pm
Location: Europe, Germany

Re: Wifi Connection after a failed attempt

Postby MicroController » Fri Aug 23, 2024 6:40 am

You may be able to do what you want by using the WiFi provisioning the IDF provides.

Who is online

Users browsing this forum: blim_acs and 115 guests