ESPNOW - After WIFI gets disconnected

sreedhar
Posts: 6
Joined: Fri Mar 20, 2020 8:50 pm

ESPNOW - After WIFI gets disconnected

Postby sreedhar » Sun Apr 12, 2020 8:29 am

Hi Guys,

I am trying to implement espnow if the wifi is disconnected. When wifi gets disconnected i get below error,
assertion "netif already added" failed: file "C:/esp-idf/components/lwip/lwip/src/core/netif.c", line 395, function: netif_add
abort() was called at PC 0x40126927 on core 1
I had already called esp_wifi_disconnect(), esp_wifi_stop(), esp_wifi_deinit(). Any help would be highly appreciated.

My code is as below.

Code: Select all

#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <assert.h>
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "freertos/timers.h"
#include "freertos/event_groups.h"
#include "nvs_flash.h"
#include "esp_event.h"
#include "tcpip_adapter.h"
#include "esp_wifi.h"
#include "esp_log.h"
#include "esp_system.h"
#include "esp_now.h"
#include "esp32/rom/ets_sys.h"
#include "esp32/rom/crc.h"
#include "espnow_example.h"
#include "lwip/netdb.h"
#include "lwip/sockets.h"

static EventGroupHandle_t wifi_event_group;
const int CONNECTED_BIT = BIT0;
const int DISCONNECTED_BIT = BIT1;
static const char *TAG = "espnow_example";
static xQueueHandle s_example_espnow_queue;
//static uint8_t s_example_broadcast_mac[ESP_NOW_ETH_ALEN] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
static uint8_t s_example_broadcast_mac[ESP_NOW_ETH_ALEN] = { 0x24, 0x6f, 0x28, 0x10, 0x68, 0x88 };
static uint16_t s_example_espnow_seq[EXAMPLE_ESPNOW_DATA_MAX] = { 0, 0 };
#define WIFI_SSID "Roguenation_2.4G"
#define WIFI_PASS "XXXXXXX"
static const char *REQUEST = "GET "CONFIG_RESOURCE" HTTP/1.1\n"
	"Host: "CONFIG_WEBSITE"\n"
	"User-Agent: ESP32\n"
	"\n";


static void example_espnow_deinit(example_espnow_send_param_t *send_param);

static void example_espnow_send_cb(const uint8_t *mac_addr, esp_now_send_status_t status)
{
	NULL;
}

static void example_espnow_recv_cb(const uint8_t *mac_addr, const uint8_t *data, int len)
{
	NULL;
}

void example_espnow_data_prepare(example_espnow_send_param_t *send_param)
{
    example_espnow_data_t *buf = (example_espnow_data_t *)send_param->buffer;

    assert(send_param->len >= sizeof(example_espnow_data_t));

//    buf->type = IS_BROADCAST_ADDR(send_param->dest_mac) ? EXAMPLE_ESPNOW_DATA_BROADCAST : EXAMPLE_ESPNOW_DATA_UNICAST;
    buf->type = EXAMPLE_ESPNOW_DATA_UNICAST;
    buf->state = send_param->state;
    buf->seq_num = s_example_espnow_seq[buf->type]++;
    buf->crc = 0;
    buf->magic = send_param->magic;
    strcpy(buf->message, "1234");
    /* Fill all remaining bytes after the data with random values */
    esp_fill_random(buf->payload, send_param->len - sizeof(example_espnow_data_t));
    buf->crc = crc16_le(UINT16_MAX, (uint8_t const *)buf, send_param->len);
}

static void example_espnow_task(void *pvParameter)
{
	example_espnow_event_t evt;
	    uint8_t recv_state = 0;
	    uint16_t recv_seq = 0;
	    int recv_magic = 0;
	    bool is_broadcast = false;
	    int ret;

	    vTaskDelay(5000 / portTICK_RATE_MS);
	    ESP_LOGI(TAG, "Start sending broadcast data");

	    /* Start sending broadcast ESPNOW data. */
	while(1){
	    example_espnow_send_param_t *send_param = (example_espnow_send_param_t *)pvParameter;
	    if (esp_now_send(send_param->dest_mac, send_param->buffer, send_param->len) != ESP_OK) {
	        ESP_LOGE(TAG, "Send error");
	        example_espnow_deinit(send_param);
//	        vTaskDelete(NULL);
	    }

	    vTaskDelay(5000/ portTICK_RATE_MS);
}
}


static void event_handler(void* arg, esp_event_base_t event_base,
                          int event_id, void* event_data)
{
    static int s_retry_num = 0;

    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) {
    	xEventGroupClearBits(wifi_event_group, CONNECTED_BIT);
    	xEventGroupSetBits(wifi_event_group, DISCONNECTED_BIT);
        ESP_LOGI(TAG,"connect to the AP fail \n");
    }
    else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
    	xEventGroupSetBits(wifi_event_group, CONNECTED_BIT);
        ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
        ESP_LOGI(TAG, "got ip:%s",
                 ip4addr_ntoa(&event->ip_info.ip));
        s_retry_num = 0;
    }
}


static void example_wifi_init(void)
{
    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_wifi_set_storage(WIFI_STORAGE_RAM) );
    ESP_ERROR_CHECK( esp_wifi_set_mode(WIFI_MODE_STA) );
    ESP_ERROR_CHECK( esp_wifi_start());

#if CONFIG_ESPNOW_ENABLE_LONG_RANGE
    ESP_ERROR_CHECK( esp_wifi_set_protocol(ESPNOW_WIFI_IF, WIFI_PROTOCOL_11B|WIFI_PROTOCOL_11G|WIFI_PROTOCOL_11N|WIFI_PROTOCOL_LR) );
#endif
}

static esp_err_t example_espnow_init(void)
{
	 example_espnow_send_param_t *send_param;
	 s_example_espnow_queue = xQueueCreate(ESPNOW_QUEUE_SIZE, sizeof(example_espnow_event_t));
	 if (s_example_espnow_queue == NULL) {
	        ESP_LOGE(TAG, "Create mutex fail");
	        return ESP_FAIL;
	    }
	    /* Initialize ESPNOW and register sending and receiving callback function. */
	    ESP_ERROR_CHECK( esp_now_init() );
	    ESP_ERROR_CHECK( esp_now_register_send_cb(example_espnow_send_cb) );
	    ESP_ERROR_CHECK( esp_now_register_recv_cb(example_espnow_recv_cb) );
	    /* Set primary master key. */
	    ESP_ERROR_CHECK( esp_now_set_pmk((uint8_t *)CONFIG_ESPNOW_PMK) );
	    /* Add broadcast peer information to peer list. */
	        esp_now_peer_info_t *peer = malloc(sizeof(esp_now_peer_info_t));
	        if (peer == NULL) {
	            ESP_LOGE(TAG, "Malloc peer information fail");
	            vSemaphoreDelete(s_example_espnow_queue);
	            esp_now_deinit();
	            return ESP_FAIL;
	        }
		memset(peer, 0, sizeof(esp_now_peer_info_t));
		peer->channel = CONFIG_ESPNOW_CHANNEL;
		peer->ifidx = ESPNOW_WIFI_IF;
		peer->encrypt = false;
		memcpy(peer->peer_addr, s_example_broadcast_mac, ESP_NOW_ETH_ALEN);
		ESP_ERROR_CHECK( esp_now_add_peer(peer) );
		free(peer);

	    /* Initialize sending parameters. */
	    send_param = malloc(sizeof(example_espnow_send_param_t));
	    memset(send_param, 0, sizeof(example_espnow_send_param_t));
	    if (send_param == NULL) {
	        ESP_LOGE(TAG, "Malloc send parameter fail");
	        vSemaphoreDelete(s_example_espnow_queue);
	        esp_now_deinit();
	        return ESP_FAIL;
	    }
	    send_param->unicast = true;
	    send_param->broadcast = false;
	    send_param->state = 0;
	    send_param->magic = esp_random();
	    send_param->count = CONFIG_ESPNOW_SEND_COUNT;
	    send_param->delay = CONFIG_ESPNOW_SEND_DELAY;
	    send_param->len = CONFIG_ESPNOW_SEND_LEN;
	    send_param->buffer = malloc(CONFIG_ESPNOW_SEND_LEN);
	    if (send_param->buffer == NULL) {
	        ESP_LOGE(TAG, "Malloc send buffer fail");
	        free(send_param);
	        vSemaphoreDelete(s_example_espnow_queue);
	        esp_now_deinit();
	        return ESP_FAIL;
	    }
	    memcpy(send_param->dest_mac, s_example_broadcast_mac, ESP_NOW_ETH_ALEN);
	    example_espnow_data_prepare(send_param);
	    xTaskCreate(example_espnow_task, "example_espnow_task", 2048, send_param, 4, NULL);
	    return ESP_OK;

}

static void example_espnow_deinit(example_espnow_send_param_t *send_param)
{
    free(send_param->buffer);
    free(send_param);
    vSemaphoreDelete(s_example_espnow_queue);
    esp_now_deinit();
}

static void wifi_connect(){
	tcpip_adapter_init();
	ESP_ERROR_CHECK(esp_event_loop_create_default());
	// initialize the wifi event handler;
    ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, event_handler, NULL));
    ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, event_handler, NULL));
	// initialize the wifi stack in STAtion mode with config in RAM
	wifi_init_config_t wifi_init_config = WIFI_INIT_CONFIG_DEFAULT();
	ESP_ERROR_CHECK(esp_wifi_init(&wifi_init_config));
	ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
	ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));

	wifi_config_t wifi_config = {
			        .sta = {
			            .ssid = WIFI_SSID,
			            .password = WIFI_PASS,
			        },
			    };
		ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config));
		ESP_ERROR_CHECK(esp_wifi_start());
		printf("Connecting to %s\n", WIFI_SSID);
		vTaskDelay(1000/portTICK_PERIOD_MS);

			printf("Wifi connected");
//			printf("\n Main task: waiting for connection to the wifi network... ");
			xEventGroupWaitBits(wifi_event_group, CONNECTED_BIT, false, true, portMAX_DELAY);
			printf("connected!\n");

			// print the local IP address
			tcpip_adapter_ip_info_t ip_info;
			ESP_ERROR_CHECK(tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_STA, &ip_info));
			printf("IP Address:  %s\n", ip4addr_ntoa(&ip_info.ip));
			printf("Subnet mask: %s\n", ip4addr_ntoa(&ip_info.netmask));
			printf("Gateway:     %s\n", ip4addr_ntoa(&ip_info.gw));

			xEventGroupWaitBits(wifi_event_group, DISCONNECTED_BIT, false, true, portMAX_DELAY);
			printf("Wifi Disconnected \n");
			ESP_ERROR_CHECK(esp_event_loop_delete_default());
			vTaskDelay(5000/portTICK_RATE_MS);

}


void app_main()
{
	// 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();
	    }
		wifi_event_group = xEventGroupCreate();
	    ESP_ERROR_CHECK( ret );
	    printf("Router Connection Begin \n");
	    wifi_connect();
	    esp_wifi_disconnect();
		esp_wifi_stop();
		esp_wifi_deinit();

	    printf("ESPNOW WIFI Init Begin \n");
	    example_wifi_init();
	    printf("ESPNOW Init Begin \n");
	    example_espnow_init();

}
Log:
I (471) cpu_start: Starting scheduler on PRO CPU.
I (0) cpu_start: Starting scheduler on APP CPU.
Router Connection Begin
I (576) wifi: wifi driver task: 3ffc0cb4, prio:23, stack:3584, core=0
I (576) system_api: Base MAC address is not set, read default base MAC address from BLK0 of EFUSE
I (576) system_api: Base MAC address is not set, read default base MAC address from BLK0 of EFUSE
I (606) wifi: wifi firmware version: 581f422
I (606) wifi: config NVS flash: enabled
I (606) wifi: config nano formating: disabled
I (606) wifi: Init dynamic tx buffer num: 32
I (606) wifi: Init data frame dynamic rx buffer num: 32
I (616) wifi: Init management frame dynamic rx buffer num: 32
I (616) wifi: Init management short buffer num: 32
I (626) wifi: Init static rx buffer size: 1600
I (626) wifi: Init static rx buffer num: 10
I (636) wifi: Init dynamic rx buffer num: 32
I (736) phy: phy_version: 4180, cb3948e, Sep 12 2019, 16:39:13, 0, 0
I (736) wifi: mode : sta (24:6f:28:0b:bc:54)
Connecting to Roguenation_2.4G
I (856) wifi: new:<11,2>, old:<1,0>, ap:<255,255>, sta:<11,2>, prof:11
I (856) wifi: state: init -> auth (b0)
I (866) wifi: state: auth -> assoc (0)
I (866) wifi: state: assoc -> run (10)
I (986) wifi: connected with Roguenation_2.4G, aid = 3, channel 11, 40D, bssid = c4:71:54:32:34:9d
I (986) wifi: security type: 3, phy: bgn, rssi: -32
I (996) wifi: pm start, type: 1

I (1046) wifi: AP's beacon interval = 102400 us, DTIM period = 1
Wifi connectedI (2556) espnow_example: got ip:192.168.0.101
I (2556) tcpip_adapter: sta ip: 192.168.0.101, mask: 255.255.255.0, gw: 192.168.0.1
connected!
IP Address: 192.168.0.101
Subnet mask: 255.255.255.0
Gateway: 192.168.0.1
I (15756) wifi: bcn_timout,ap_probe_send_start
I (18256) wifi: ap_probe_send over, resett wifi status to disassoc
I (18256) wifi: state: run -> init (c800)
I (18256) wifi: pm stop, total sleep time: 7563283 us / 17263178 us

I (18266) wifi: new:<11,0>, old:<11,2>, ap:<255,255>, sta:<11,2>, prof:11
I (18266) espnow_example: connect to the AP fail

Wifi Disconnected
I (23276) wifi: flush txq
I (23276) wifi: stop sw txq
I (23276) wifi: lmac stop hw txq
I (23276) wifi: Deinit lldesc rx mblock:10
ESPNOW WIFI Init Begin
I (23296) wifi: wifi driver task: 3ffbfa94, prio:23, stack:3584, core=0
I (23296) system_api: Base MAC address is not set, read default base MAC address from BLK0 of EFUSE
I (23296) system_api: Base MAC address is not set, read default base MAC address from BLK0 of EFUSE
I (23326) wifi: wifi firmware version: 581f422
I (23326) wifi: config NVS flash: enabled
I (23326) wifi: config nano formating: disabled
I (23326) wifi: Init dynamic tx buffer num: 32
I (23326) wifi: Init data frame dynamic rx buffer num: 32
I (23336) wifi: Init management frame dynamic rx buffer num: 32
I (23336) wifi: Init management short buffer num: 32
I (23346) wifi: Init static rx buffer size: 1600
I (23346) wifi: Init static rx buffer num: 10
I (23356) wifi: Init dynamic rx buffer num: 32
I (23366) wifi: mode : sta (24:6f:28:0b:bc:54)
ESPNOW Init Begin
I (23376) ESPNOW: espnow [version: 1.0] init
assertion "netif already added" failed: file "C:/esp-idf/components/lwip/lwip/src/core/netif.c", line 395, function: netif_add
abort() was called at PC 0x40126927 on core 1

ELF file SHA256: 779090e58f2eac0c2befd22f2dc2905ed86170dd489fbdb63c77dc5ee7f42ddf

Backtrace: 0x4008f8bd:0x3ffbe230 0x4008fc35:0x3ffbe250 0x40126927:0x3ffbe270 0x40113a6f:0x3ffbe2a0 0x400dca6f:0x3ffbe2d0 0x400dcb12:0x3ffbe320 0x400dc926:0x3ffbe340 0x40112ab5:0x3ffbe360 0x40112b5c:0x3ffbe380 0x400920f9:0x3ffbe3b0

Rebooting...

marinacabezon
Posts: 6
Joined: Tue Jun 09, 2020 8:10 am

Re: ESPNOW - After WIFI gets disconnected

Postby marinacabezon » Tue Jun 28, 2022 8:07 am

Did you solve the error? I have the same trouble

Who is online

Users browsing this forum: ESPBoards and 129 guests