Wifi won't restart correctly after shutdown [SOLVED]

greg-dickson
Posts: 39
Joined: Sun Nov 01, 2020 1:51 am

Wifi won't restart correctly after shutdown [SOLVED]

Postby greg-dickson » Wed Jan 29, 2025 12:33 pm

HI
In esp-idf I have the following shutdown code.

Code: Select all

esp_err_t wifi_stop(void)
{
  CHECK(esp_wifi_stop());
  CHECK(esp_wifi_deinit());
  CHECK(esp_wifi_clear_default_wifi_driver_and_handlers(STA_netif));
  esp_netif_destroy(STA_netif);
  CHECK( esp_event_loop_delete_default());
  STA_netif = NULL;
  return ESP_OK;
}
CHECK simply reports the error and returns That error.

when I try and reconnect the system hangs at getting an IP.
ie
I (23014) wifi_sta: Waiting for IP(s)
I (25424) wifi_sta: Wi-Fi disconnected 201, trying to reconnect...
I (27844) wifi_sta: Wi-Fi disconnected 201, trying to reconnect...
I (30254) wifi_sta: Wi-Fi disconnected 201, trying to reconnect...
I (32664) wifi_sta: Wi-Fi disconnected 201, trying to reconnect...
I (35084) wifi_sta: Wi-Fi disconnected 201, trying to reconnect...

The first connect works fine after a complete power down and restart.
However a wake from deep sleep has the same problem and even when I hit the reset buton.
Could it be that the router is simply presuming it already knows it's IP?
What am I doing wrong here.
Last edited by greg-dickson on Fri Jan 31, 2025 2:27 am, edited 1 time in total.

chegewara
Posts: 2505
Joined: Wed Jun 14, 2017 9:00 pm

Re: Wifi won't restart correctly after shutdown

Postby chegewara » Wed Jan 29, 2025 1:48 pm

Hi,
You posted code the way you stop wifi, but not how you init and start wifi.

Also, if your code and logs are more or less standard then disconnect reason 201 means the AP cant be discovered.

greg-dickson
Posts: 39
Joined: Sun Nov 01, 2020 1:51 am

Re: Wifi won't restart correctly after shutdown

Postby greg-dickson » Thu Jan 30, 2025 11:05 am

Hi,
You posted code the way you stop wifi, but not how you init and start wifi.

Also, if your code and logs are more or less standard then disconnect reason 201 means the AP cant be discovered.
Thanks for your interest but if it is working fine on a cold boot but not after my code why do you need the connect code. It is basically the same as the SNTP wifi example with only the wifi stuff in it.
Here is the code but I can't see how that will help as it does actually work.

Code: Select all

static esp_netif_t *STA_netif = NULL;
static SemaphoreHandle_t Semaphore_get_ip_addrs = NULL;
static int s_retry_num = 0;
#define WIFI_CONNECT_MAX_RETRY 10
esp_err_t wifi_sta_do_disconnect(void);
#define NETIF_DESCRIPTION_STA "netif_sta"
#define ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD WIFI_AUTH_WPA2_PSK
#define ESP_WIFI_SAE_MODE WPA3_SAE_PWE_BOTH
#define SAE_H2E_IDENTIFIER ""

Code: Select all

//! WiFi functions

/**
 * @brief Checks the netif description if it contains specified prefix.
 * All netifs created withing common connect component are prefixed with the module TAG,
 * so it returns true if the specified netif is owned by this module
 */
bool is_our_netif(const char *prefix, esp_netif_t *netif)
{
    return strncmp(prefix, esp_netif_get_desc(netif), strlen(prefix) - 1) == 0;
}

static bool netif_desc_matches_with(esp_netif_t *netif, void *ctx)
{
    return strcmp(ctx, esp_netif_get_desc(netif)) == 0;
}

esp_netif_t *netif_from_desc(const char *desc)
{
    return esp_netif_find_if(netif_desc_matches_with, (void*)desc);
}

static void handler_on_wifi_disconnect(void *arg, esp_event_base_t event_base,
                               int32_t event_id, void *event_data)
{
  s_retry_num++;
  if (s_retry_num > WIFI_CONNECT_MAX_RETRY) {
    ESP_LOGI(TAG, "WiFi Connect failed %d times, stop reconnect.", s_retry_num);
    /* let wifi_sta_do_connect() return */
    if (Semaphore_get_ip_addrs) {
        xSemaphoreGive(Semaphore_get_ip_addrs);
    }
    wifi_sta_do_disconnect();
    return;
  }
  wifi_event_sta_disconnected_t *disconn = event_data;
  if (disconn->reason == WIFI_REASON_ROAMING) {
    ESP_LOGD(TAG, "station roaming, do nothing");
    return;
  }
  ESP_LOGI(TAG, "Wi-Fi disconnected %d, trying to reconnect...", disconn->reason);
  esp_err_t err = esp_wifi_connect();
  if (err == ESP_ERR_WIFI_NOT_STARTED) {
    return;
  }
  REPORT(err);
}


static void handler_on_sta_got_ip(void *arg, esp_event_base_t event_base,
                      int32_t event_id, void *event_data)
{
  s_retry_num = 0;
  ip_event_got_ip_t *event = (ip_event_got_ip_t *)event_data;
  if (!is_our_netif(NETIF_DESCRIPTION_STA, event->esp_netif)) {
      return;
  }
  ESP_LOGI(TAG, "Got IPv4 event: Interface \"%s\" address: " IPSTR, esp_netif_get_desc(event->esp_netif), IP2STR(&event->ip_info.ip));
  if (Semaphore_get_ip_addrs) {
      xSemaphoreGive(Semaphore_get_ip_addrs);
  } else {
      ESP_LOGI(TAG, "- IPv4 address: " IPSTR ",", IP2STR(&event->ip_info.ip));
  }
}


esp_err_t wifi_start(void)
{
  wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
  CHECK(esp_wifi_init(&cfg));

  esp_netif_inherent_config_t esp_netif_config = ESP_NETIF_INHERENT_DEFAULT_WIFI_STA();
  // Warning: the interface desc is used in tests to capture actual connection details (IP, gw, mask)
  esp_netif_config.if_desc = NETIF_DESCRIPTION_STA;
  esp_netif_config.route_prio = 128;
  STA_netif = esp_netif_create_wifi(WIFI_IF_STA, &esp_netif_config);
  esp_wifi_set_default_wifi_sta_handlers();

  CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
  CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
  CHECK(esp_wifi_start());
  return ESP_OK;
}


esp_err_t wifi_stop(void)
{
  //~ esp_err_t err = esp_wifi_stop();
  //~ if (err == ESP_ERR_WIFI_NOT_INIT) {
      //~ return;
  //~ }
  CHECK(esp_wifi_stop());
  CHECK(esp_wifi_deinit());
  CHECK(esp_wifi_clear_default_wifi_driver_and_handlers(STA_netif));
  esp_netif_destroy(STA_netif);
  CHECK( esp_event_loop_delete_default());
  STA_netif = NULL;
  
  return ESP_OK;
}


esp_err_t wifi_sta_do_connect(wifi_config_t wifi_config, bool wait)
{
  if (wait) {
      Semaphore_get_ip_addrs = xSemaphoreCreateBinary();
      if (Semaphore_get_ip_addrs == NULL) {
          return ESP_ERR_NO_MEM;
      }
  }
  s_retry_num = 0;
  CHECK(esp_event_handler_register(WIFI_EVENT, WIFI_EVENT_STA_DISCONNECTED, &handler_on_wifi_disconnect, NULL));
  CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &handler_on_sta_got_ip, NULL));
  //~ CHECK(esp_event_handler_register(WIFI_EVENT, WIFI_EVENT_STA_CONNECTED, &handler_on_wifi_connect, STA_netif));
  ESP_LOGI(TAG, "Connecting to %s...", wifi_config.sta.ssid);
  CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config));
  esp_err_t ret = esp_wifi_connect();
  if (ret != ESP_OK) {
      ESP_LOGE(TAG, "WiFi connect failed! ret:%x", ret);
      return ret;
  }
  if (wait) {
      ESP_LOGI(TAG, "Waiting for IP(s)");
      xSemaphoreTake(Semaphore_get_ip_addrs, portMAX_DELAY);
      if (s_retry_num > WIFI_CONNECT_MAX_RETRY) {
          return ESP_FAIL;
      }
  }
  return ESP_OK;
}

esp_err_t wifi_sta_do_disconnect(void)
{
  CHECK(esp_event_handler_unregister(WIFI_EVENT, WIFI_EVENT_STA_DISCONNECTED, &handler_on_wifi_disconnect));
  CHECK(esp_event_handler_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP, &handler_on_sta_got_ip));
  if (Semaphore_get_ip_addrs) {
      vSemaphoreDelete(Semaphore_get_ip_addrs);
  }
  return esp_wifi_disconnect();
}

void wifi_shutdown(void)
{
    REPORT(wifi_sta_do_disconnect());
    REPORT(wifi_stop());
    ESP_LOGI(TAG, "Disconnected from WiFi.");
}

esp_err_t wifi_connect(void)
{
  esp_log_level_set("wifi",ESP_LOG_ERROR);
  esp_log_level_set("wifi_init",ESP_LOG_ERROR);
  ESP_LOGI(TAG, "Start wifi connect.");
  wifi_start();
  wifi_config_t wifi_config = {
      .sta = {
          //.ssid = Wifi_SSID,
          //.password = Wifi_password,
          /* Authmode threshold resets to WPA2 as default if password matches WPA2 standards (pasword len => 8).
           * If you want to connect the device to deprecated WEP/WPA networks, Please set the threshold value
           * to WIFI_AUTH_WEP/WIFI_AUTH_WPA_PSK and set the password with length and format matching to
           * WIFI_AUTH_WEP/WIFI_AUTH_WPA_PSK standards.
           */
          .scan_method = WIFI_ALL_CHANNEL_SCAN,
          .sort_method = WIFI_CONNECT_AP_BY_SIGNAL,
          //~ .threshold.rssi = CONFIG_WIFI_SCAN_RSSI_THRESHOLD,
          .threshold.authmode = ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD,
          .sae_pwe_h2e = ESP_WIFI_SAE_MODE,
          .sae_h2e_identifier = SAE_H2E_IDENTIFIER,
      },
  };
  
  //~ memcpy(wifi_config.sta.ssid, Wifi_SSID, sizeof(Wifi_SSIDwifi_config.sta.ssid));
  memcpy(wifi_config.sta.ssid, Wifi_SSID, sizeof(wifi_config.sta.ssid));
  memcpy(wifi_config.sta.password, Wifi_password, sizeof(wifi_config.sta.password));
  return wifi_sta_do_connect(wifi_config, true);
}

static void print_servers(void)
{
  ESP_LOGI(TAG, "List of configured NTP servers:");

  for (uint8_t i = 0; i < SNTP_MAX_SERVERS; ++i){
      if (esp_sntp_getservername(i)){
          ESP_LOGI(TAG, "server %d: %s", i, esp_sntp_getservername(i));
      } else {
          // we have either IPv4 or IPv6 address, let's print it
#ifndef INET6_ADDRSTRLEN
#define INET6_ADDRSTRLEN 48
#endif
          char buff[INET6_ADDRSTRLEN];
          ip_addr_t const *ip = esp_sntp_getserver(i);
          if (ipaddr_ntoa_r(ip, buff, INET6_ADDRSTRLEN) != NULL)
              ESP_LOGI(TAG, "server %d: %s", i, buff);
      }
  }
}

esp_err_t sync_time_to_sntp(void)
{
  
#ifdef CONFIG_NVS_PAGE_NAME
  truc_nvs_init(true);
#else
  CHECK( nvs_flash_init() );
#endif
  CHECK( esp_netif_init() );
  esp_event_loop_create_default(); // this is throwing iESP_ERR_INVALID_STATE when run after proir update
  setenv("TZ", "UTC0", 0); // set enviroment to UTC and overwrite
  tzset();

#if LWIP_DHCP_GET_NTP_SRV
  /**
   * NTP server address could be acquired via DHCP,
   * see following menuconfig options:
   * 'LWIP_DHCP_GET_NTP_SRV' - enable STNP over DHCP
   * 'LWIP_SNTP_DEBUG' - enable debugging messages
   *
   * NOTE: This call should be made BEFORE esp acquires IP address from DHCP,
   * otherwise NTP option would be rejected by default.
   */
  ESP_LOGI(TAG, "Initializing SNTP");
  esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG(CONFIG_SNTP_TIME_SERVER);
  config.start = false;                       // start SNTP service explicitly (after connecting)
  config.server_from_dhcp = true;             // accept NTP offers from DHCP server, if any (need to enable *before* connecting)
  config.renew_servers_after_new_IP = true;   // let esp-netif update configured SNTP server(s) after receiving DHCP lease
  config.index_of_first_server = 1;           // updates from server num 1, leaving server 0 (from DHCP) intact
  // configure the event on which we renew servers
  config.ip_event_to_renew = IP_EVENT_STA_GOT_IP;
  //~ config.sync_cb = time_sync_notification_cb; // only if we need the notification function
  esp_netif_sntp_init(&config);

#endif /* LWIP_DHCP_GET_NTP_SRV */

  CHECK(wifi_connect());

#if LWIP_DHCP_GET_NTP_SRV
  ESP_LOGI(TAG, "Starting SNTP");
  esp_netif_sntp_start();
#if LWIP_IPV6 && SNTP_MAX_SERVERS > 2
  /* This demonstrates using IPv6 address as an additional SNTP server
   * (statically assigned IPv6 address is also possible)
   */
  ip_addr_t ip6;
  if (ipaddr_aton("2a01:3f7::1", &ip6)) {    // ipv6 ntp source "ntp.netnod.se"
      esp_sntp_setserver(2, &ip6);
  }
#endif  /* LWIP_IPV6 */
/* end LWIP_DHCP_GET_NTP_SRV */
#else
  ESP_LOGI(TAG, "Initializing and starting SNTP");
#if CONFIG_LWIP_SNTP_MAX_SERVERS > 1
  /* This demonstrates configuring more than one server
   */
  esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG_MULTIPLE(2,
                             ESP_SNTP_SERVER_LIST(CONFIG_SNTP_TIME_SERVER, "pool.ntp.org" ) );
#else
  /*
   * This is the basic default config with one server and starting the service
   */
  esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG("pool.ntp.org");
#endif
  //~ config.sync_cb = time_sync_notification_cb;     // Note: This is only needed if we want
//~ #ifdef CONFIG_SNTP_TIME_SYNC_METHOD_SMOOTH
  //~ config.smooth_sync = true;
//~ #endif
  config.smooth_sync = false;
  esp_netif_sntp_init(&config);
#endif

  //~ print_servers();

  // wait for time to be set
  int retry = 0;
  const int retry_count = 15;
  while (esp_netif_sntp_sync_wait(2000 / portTICK_PERIOD_MS) == ESP_ERR_TIMEOUT && ++retry < retry_count) {
      ESP_LOGI(TAG, "Waiting for system time to be set... (%d/%d)", retry, retry_count);
  }
  time(&SNTP_check_timestamp);  
  wifi_shutdown();
  esp_netif_sntp_deinit();
#ifdef CONFIG_DS3231_I2C
  time_t now = 0;
  struct tm timeinfo = { 0 };

  ESP_LOGW(__FUNCTION__,"Setting RTC");  
  if(rtc_available())
  {
    time(&now);
    ds3231_time_get(&timeinfo);
    time_t rtc_time_diff = mktime(&timeinfo) - now; // seconds is in UTC
    // report the time difference
    if(rtc_time_diff != 0)
    {
      ESP_LOGW(__FUNCTION__,"RTC was %s it will be adjusted by %d seconds",rtc_time_diff<0?"slower":"faster",abs((int)rtc_time_diff));
      time(&now);       
      localtime_r(&now, &timeinfo);
      if(ds3231_time_set(&timeinfo)==ESP_OK)
      {
        ds3231_time_get(&timeinfo);
        char strftime_buf[64];
        strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo);
        time(&now);
        struct tm localtimeinfo;
        //time(&now);
        localtime_r(&now, &localtimeinfo);
        char local[100];
        strftime(local, sizeof(local), "%c", &localtimeinfo);
        ESP_LOGI(__FUNCTION__, "System time synced to SNTP Server as UTC\nRTC  : date/time is: %s \nLocal: date/time is: %s ", strftime_buf, local);          
        return true;
      }
      else
      {
        ESP_LOGW(__FUNCTION__, "Failed to set RTC");      
      }
    }
  } 
#endif
  return ESP_OK;
}

chegewara
Posts: 2505
Joined: Wed Jun 14, 2017 9:00 pm

Re: Wifi won't restart correctly after shutdown

Postby chegewara » Thu Jan 30, 2025 11:37 am

Hi,
i have reasons asking you to show wifi init code, which i will explain later.
There is last one question:
- when you stop wifi with this function, which one is next to restart wifi and it fails?

Code: Select all

esp_err_t wifi_stop(void)

greg-dickson
Posts: 39
Joined: Sun Nov 01, 2020 1:51 am

Re: Wifi won't restart correctly after shutdown

Postby greg-dickson » Thu Jan 30, 2025 3:13 pm

Hi,
i have reasons asking you to show wifi init code, which i will explain later.
There is last one question:
- when you stop wifi with this function, which one is next to restart wifi and it fails?

Code: Select all

esp_err_t wifi_stop(void)
that would be either of these

Code: Select all

//! SNTP functions

esp_err_t sync_time_to_sntp(void)
{
  
#ifdef CONFIG_NVS_PAGE_NAME
  truc_nvs_init(true);
#else
  CHECK( nvs_flash_init() );
#endif
  CHECK( esp_netif_init() );
  esp_event_loop_create_default(); // this is throwing iESP_ERR_INVALID_STATE when run after proir update
  setenv("TZ", "UTC0", 0); // set enviroment to UTC and overwrite
  tzset();

#if LWIP_DHCP_GET_NTP_SRV
  /**
   * NTP server address could be acquired via DHCP,
   * see following menuconfig options:
   * 'LWIP_DHCP_GET_NTP_SRV' - enable STNP over DHCP
   * 'LWIP_SNTP_DEBUG' - enable debugging messages
   *
   * NOTE: This call should be made BEFORE esp acquires IP address from DHCP,
   * otherwise NTP option would be rejected by default.
   */
  ESP_LOGI(TAG, "Initializing SNTP");
  esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG(CONFIG_SNTP_TIME_SERVER);
  config.start = false;                       // start SNTP service explicitly (after connecting)
  config.server_from_dhcp = true;             // accept NTP offers from DHCP server, if any (need to enable *before* connecting)
  config.renew_servers_after_new_IP = true;   // let esp-netif update configured SNTP server(s) after receiving DHCP lease
  config.index_of_first_server = 1;           // updates from server num 1, leaving server 0 (from DHCP) intact
  // configure the event on which we renew servers
  config.ip_event_to_renew = IP_EVENT_STA_GOT_IP;
  //~ config.sync_cb = time_sync_notification_cb; // only if we need the notification function
  esp_netif_sntp_init(&config);

#endif /* LWIP_DHCP_GET_NTP_SRV */

  CHECK(wifi_connect());

#if LWIP_DHCP_GET_NTP_SRV
  ESP_LOGI(TAG, "Starting SNTP");
  esp_netif_sntp_start();
#if LWIP_IPV6 && SNTP_MAX_SERVERS > 2
  /* This demonstrates using IPv6 address as an additional SNTP server
   * (statically assigned IPv6 address is also possible)
   */
  ip_addr_t ip6;
  if (ipaddr_aton("2a01:3f7::1", &ip6)) {    // ipv6 ntp source "ntp.netnod.se"
      esp_sntp_setserver(2, &ip6);
  }
#endif  /* LWIP_IPV6 */
/* end LWIP_DHCP_GET_NTP_SRV */
#else
  ESP_LOGI(TAG, "Initializing and starting SNTP");
#if CONFIG_LWIP_SNTP_MAX_SERVERS > 1
  /* This demonstrates configuring more than one server
   */
  esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG_MULTIPLE(2,
                             ESP_SNTP_SERVER_LIST(CONFIG_SNTP_TIME_SERVER, "pool.ntp.org" ) );
#else
  /*
   * This is the basic default config with one server and starting the service
   */
  esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG("pool.ntp.org");
#endif
  //~ config.sync_cb = time_sync_notification_cb;     // Note: This is only needed if we want
//~ #ifdef CONFIG_SNTP_TIME_SYNC_METHOD_SMOOTH
  //~ config.smooth_sync = true;
//~ #endif
  config.smooth_sync = false;
  esp_netif_sntp_init(&config);
#endif

  //~ print_servers();

  // wait for time to be set
  int retry = 0;
  const int retry_count = 15;
  while (esp_netif_sntp_sync_wait(2000 / portTICK_PERIOD_MS) == ESP_ERR_TIMEOUT && ++retry < retry_count) {
      ESP_LOGI(TAG, "Waiting for system time to be set... (%d/%d)", retry, retry_count);
  }
  time(&SNTP_check_timestamp);  
  wifi_shutdown();
  esp_netif_sntp_deinit();
#ifdef CONFIG_DS3231_I2C
  time_t now = 0;
  struct tm timeinfo = { 0 };

  ESP_LOGW(__FUNCTION__,"Setting RTC");  
  if(rtc_available())
  {
    time(&now);
    ds3231_time_get(&timeinfo);
    time_t rtc_time_diff = mktime(&timeinfo) - now; // seconds is in UTC
    // report the time difference
    if(rtc_time_diff != 0)
    {
      ESP_LOGW(__FUNCTION__,"RTC was %s it will be adjusted by %d seconds",rtc_time_diff<0?"slower":"faster",abs((int)rtc_time_diff));
      time(&now);       
      localtime_r(&now, &timeinfo);
      if(ds3231_time_set(&timeinfo)==ESP_OK)
      {
        ds3231_time_get(&timeinfo);
        char strftime_buf[64];
        strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo);
        time(&now);
        struct tm localtimeinfo;
        //time(&now);
        localtime_r(&now, &localtimeinfo);
        char local[100];
        strftime(local, sizeof(local), "%c", &localtimeinfo);
        ESP_LOGI(__FUNCTION__, "System time synced to SNTP Server as UTC\nRTC  : date/time is: %s \nLocal: date/time is: %s ", strftime_buf, local);          
        return true;
      }
      else
      {
        ESP_LOGW(__FUNCTION__, "Failed to set RTC");      
      }
    }
  } 
#endif
  return ESP_OK;
}

/*!
 * returns true if updated to sntp
 */
  
bool time_check()
{
  setenv("TZ", "UTC0", 0); // set environment to UTC and overwrite
  tzset();
  //~ esp_err_t error = ESP_FAIL;
  if(!sync_time_to_rtc())
  {
    ESP_LOGI(__FUNCTION__, "Calling sync_time_to_sntp");
    if(sync_time_to_sntp() != ESP_OK)
      sync_time_to_build_time();
    else
      return true;
  }
  return false;
}
  

greg-dickson
Posts: 39
Joined: Sun Nov 01, 2020 1:51 am

Re: Wifi won't restart correctly after shutdown

Postby greg-dickson » Thu Jan 30, 2025 3:15 pm

To be complete here I will add this

Code: Select all

time_t compile_time() 
{
  char source[40];
  time_t t = 1736287200; // Error case
#ifdef BUILD_TIME_UNIX
  sprintf(source, "BUILD_TIME_UNIX");
  t = (time_t)BUILD_TIME_UNIX;
#else
  struct tm tm_info;    // A struct to hold the time information
  char datetime_str[30]; // A string to store the combined date and time
  // Combine the date and time strings
  sprintf(source, "__DATE__ and __TIME__");
  snprintf(datetime_str, sizeof(datetime_str), "%s %s", __DATE__, __TIME__);
  // Parse the combined string into a tm structure
  if (strptime(datetime_str, "%b %d %Y %H:%M:%S", &tm_info) != NULL) 
  {
    // Convert the tm structure to a time_t value
    t = mktime(&tm_info); 
  } 
#endif
  char strftime_buf[64];
  struct tm timeinfo;
  localtime_r(&t, &timeinfo);
  strftime(strftime_buf, sizeof(strftime_buf), "%a, %d %b %Y %T %z", &timeinfo);
  ESP_LOGI(__FUNCTION__,"Complied on %s from %s",strftime_buf,source);
  return t;
}
and in the CMakeLists.txt I have this

Code: Select all

# CREATE BUILD_TIME_UNIX from UTC, if it's not already defined
if(NOT DEFINED BUILD_TIME_UNIX)
  execute_process(
      COMMAND date -u +%s
      OUTPUT_VARIABLE BUILD_TIMESTAMP
      OUTPUT_STRIP_TRAILING_WHITESPACE
  )
  set(BUILD_TIME_UNIX ${BUILD_TIMESTAMP})
endif()

# Propagate the variable to the compiler as a macro
add_compile_definitions(BUILD_TIME_UNIX=${BUILD_TIME_UNIX})

greg-dickson
Posts: 39
Joined: Sun Nov 01, 2020 1:51 am

Re: Wifi won't restart correctly after shutdown

Postby greg-dickson » Fri Jan 31, 2025 2:05 am

Hi,
You posted code the way you stop wifi, but not how you init and start wifi.

Also, if your code and logs are more or less standard then disconnect reason 201 means the AP cant be discovered.
Thank you I did find the error elsewhere in the code where the AP details were stored incorrectly once the system was up and running.
I haven't been able to find a list of error codes and what they mean. I will go through the source and check again.
Thank you so much for your help.

chegewara
Posts: 2505
Joined: Wed Jun 14, 2017 9:00 pm

Re: Wifi won't restart correctly after shutdown

Postby chegewara » Fri Jan 31, 2025 2:09 am

Hi,
You posted code the way you stop wifi, but not how you init and start wifi.

Also, if your code and logs are more or less standard then disconnect reason 201 means the AP cant be discovered.
Thank you I did find the error elsewhere in the code where the AP details were stored incorrectly once the system was up and running.
I haven't been able to find a list of error codes and what they mean. I will go through the source and check again.
Thank you so much for your help.
Im glad you find it.

greg-dickson
Posts: 39
Joined: Sun Nov 01, 2020 1:51 am

Re: Wifi won't restart correctly after shutdown [SOLVED]

Postby greg-dickson » Fri Jan 31, 2025 2:43 am

I have now added this to my generic code to make the errors a little more clear.

Code: Select all

  
const char *wifi_reason_to_name(wifi_err_reason_t reason) 
{
  switch (reason) 
  {
    case WIFI_REASON_UNSPECIFIED :return "1, Unspecified reason"; 
    case WIFI_REASON_AUTH_EXPIRE :return "2, Authentication expired"; 
    case WIFI_REASON_AUTH_LEAVE :return "3, Deauthentication due to leaving"; 
    case WIFI_REASON_DISASSOC_DUE_TO_INACTIVITY :return "4, Disassociated due to inactivity"; 
    case WIFI_REASON_ASSOC_TOOMANY :return "5, Too many associated stations"; 
    case WIFI_REASON_CLASS2_FRAME_FROM_NONAUTH_STA :return "6, Class 2 frame received from nonauthenticated STA"; 
    case WIFI_REASON_CLASS3_FRAME_FROM_NONASSOC_STA :return "7, Class 3 frame received from nonassociated STA"; 
    case WIFI_REASON_ASSOC_LEAVE :return "8, Deassociated due to leaving"; 
    case WIFI_REASON_ASSOC_NOT_AUTHED :return "9, Association but not authenticated"; 
    case WIFI_REASON_DISASSOC_PWRCAP_BAD :return "10, Disassociated due to poor power capability"; 
    case WIFI_REASON_DISASSOC_SUPCHAN_BAD :return "11, Disassociated due to unsupported channel"; 
    case WIFI_REASON_BSS_TRANSITION_DISASSOC :return "12, Disassociated due to BSS transition"; 
    case WIFI_REASON_IE_INVALID :return "13, Invalid Information Element (IE"; 
    case WIFI_REASON_MIC_FAILURE :return "14, MIC failure"; 
    case WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT :return "15, 4-way handshake timeout"; 
    case WIFI_REASON_GROUP_KEY_UPDATE_TIMEOUT :return "16, Group key update timeout"; 
    case WIFI_REASON_IE_IN_4WAY_DIFFERS :return "17, IE differs in 4-way handshake"; 
    case WIFI_REASON_GROUP_CIPHER_INVALID :return "18, Invalid group cipher"; 
    case WIFI_REASON_PAIRWISE_CIPHER_INVALID :return "19, Invalid pairwise cipher"; 
    case WIFI_REASON_AKMP_INVALID :return "20, Invalid AKMP"; 
    case WIFI_REASON_UNSUPP_RSN_IE_VERSION :return "21, Unsupported RSN IE version"; 
    case WIFI_REASON_INVALID_RSN_IE_CAP :return "22, Invalid RSN IE capabilities"; 
    case WIFI_REASON_802_1X_AUTH_FAILED :return "23, 802.1X authentication failed"; 
    case WIFI_REASON_CIPHER_SUITE_REJECTED :return "24, Cipher suite rejected"; 
    case WIFI_REASON_TDLS_PEER_UNREACHABLE :return "25, TDLS peer unreachable"; 
    case WIFI_REASON_TDLS_UNSPECIFIED :return "26, TDLS unspecified"; 
    case WIFI_REASON_SSP_REQUESTED_DISASSOC :return "27, SSP requested disassociation"; 
    case WIFI_REASON_NO_SSP_ROAMING_AGREEMENT :return "28, No SSP roaming agreement"; 
    case WIFI_REASON_BAD_CIPHER_OR_AKM :return "29, Bad cipher or AKM"; 
    case WIFI_REASON_NOT_AUTHORIZED_THIS_LOCATION :return "30, Not authorized in this location"; 
    case WIFI_REASON_SERVICE_CHANGE_PERCLUDES_TS :return "31, Service change precludes TS"; 
    case WIFI_REASON_UNSPECIFIED_QOS :return "32, Unspecified QoS reason"; 
    case WIFI_REASON_NOT_ENOUGH_BANDWIDTH :return "33, Not enough bandwidth"; 
    case WIFI_REASON_MISSING_ACKS :return "34, Missing ACKs"; 
    case WIFI_REASON_EXCEEDED_TXOP :return "35, Exceeded TXOP"; 
    case WIFI_REASON_STA_LEAVING :return "36, Station leaving"; 
    case WIFI_REASON_END_BA :return "37, End of Block Ack (BA"; 
    case WIFI_REASON_UNKNOWN_BA :return "38, Unknown Block Ack (BA"; 
    case WIFI_REASON_TIMEOUT :return "39, Timeout"; 
    case WIFI_REASON_PEER_INITIATED :return "46, Peer initiated disassociation"; 
    case WIFI_REASON_AP_INITIATED :return "47, AP initiated disassociation"; 
    case WIFI_REASON_INVALID_FT_ACTION_FRAME_COUNT :return "48, Invalid FT action frame count"; 
    case WIFI_REASON_INVALID_PMKID :return "49, Invalid PMKID"; 
    case WIFI_REASON_INVALID_MDE :return "50, Invalid MDE"; 
    case WIFI_REASON_INVALID_FTE :return "51, Invalid FTE"; 
    case WIFI_REASON_TRANSMISSION_LINK_ESTABLISH_FAILED :return "67, Transmission link establishment failed"; 
    case WIFI_REASON_ALTERATIVE_CHANNEL_OCCUPIED :return "68, Alternative channel occupied"; 
    case WIFI_REASON_BEACON_TIMEOUT :return "200, Beacon timeout"; 
    case WIFI_REASON_NO_AP_FOUND :return "201, No AP found"; 
    case WIFI_REASON_AUTH_FAIL :return "202, Authentication failed"; 
    case WIFI_REASON_ASSOC_FAIL :return "203, Association failed"; 
    case WIFI_REASON_HANDSHAKE_TIMEOUT :return "204, Handshake timeout"; 
    case WIFI_REASON_CONNECTION_FAIL :return "205, Connection failed"; 
    case WIFI_REASON_AP_TSF_RESET :return "206, AP TSF reset"; 
    case WIFI_REASON_ROAMING :return "207, Roaming"; 
    case WIFI_REASON_ASSOC_COMEBACK_TIME_TOO_LONG :return "208, Association comeback time too long"; 
    case WIFI_REASON_SA_QUERY_TIMEOUT :return "209, SA query timeout"; 
    case WIFI_REASON_NO_AP_FOUND_W_COMPATIBLE_SECURITY :return "210, No AP found with compatible security"; 
    case WIFI_REASON_NO_AP_FOUND_IN_AUTHMODE_THRESHOLD :return "211, No AP found in auth mode threshold"; 
    case WIFI_REASON_NO_AP_FOUND_IN_RSSI_THRESHOLD :return "212, No AP found in RSSI threshold"; 
    default: return "Unknown reason";
  }
}

Who is online

Users browsing this forum: Bing [Bot] and 3 guests