Establish WiFi connection to AP with strongest radio signal

axellin
Posts: 200
Joined: Mon Sep 17, 2018 9:09 am

Re: Establish WiFi connection to AP with strongest radio signal

Postby axellin » Wed Sep 21, 2022 3:13 am

FYI, you probable want to wait for this bug fix:
https://github.com/espressif/esp-idf/issues/8269

khoih-prog
Posts: 53
Joined: Sat Feb 22, 2020 8:16 pm

Re: Establish WiFi connection to AP with strongest radio signal

Postby khoih-prog » Wed Sep 21, 2022 7:46 pm

You can adapt ESP32 built-in WiFiMulti example to see if OK for you.

You can also try my WiFiMulti_Generic Library, which is designed to help many boards, including ESP32, to connect to one of your pre-selected SSIDs with the best RSSI.

freetz
Posts: 1
Joined: Fri May 12, 2023 7:56 am

Re: Establish WiFi connection to AP with strongest radio signal

Postby freetz » Fri May 12, 2023 9:08 am

Thanks to @Thomas Peter for his solution which I modified slightly in order to not rely on the ESP's sorting order and therefore possibly also solving @kristian32's issue. Here's the function I'm using now. It requires wifi_ssid and wifi_pass to be global variables and returns the connected BSSID as string:

Code: Select all

String scanAndConnectToStrongestNetwork() {
  int i_strongest = -1;
  int32_t rssi_strongest = -100;
  Serial.printf("Start scanning for SSID %s\r\n", wifi_ssid);

  int n = WiFi.scanNetworks(); // WiFi.scanNetworks will return the number of networks found
  Serial.println("Scan done.");

  if (n == 0) {
    Serial.println("No networks found!");
    return ("");
  } else {
    Serial.printf("%d networks found:", n);
    for (int i = 0; i < n; ++i) {
      // Print SSID and RSSI for each network found
      Serial.printf("%d: BSSID: %s  %2ddBm, %3d%%  %9s  %s\r\n", i, WiFi.BSSIDstr(i).c_str(), WiFi.RSSI(i), constrain(2 * (WiFi.RSSI(i) + 100), 0, 100), (WiFi.encryptionType(i) == WIFI_AUTH_OPEN) ? "open" : "encrypted", WiFi.SSID(i).c_str());
      if ((String(wifi_ssid) == String(WiFi.SSID(i)) && (WiFi.RSSI(i)) > rssi_strongest)) {
        rssi_strongest = WiFi.RSSI(i);
        i_strongest = i;
      }
    }
  }

  if (i_strongest < 0) {
    Serial.printf("No network with SSID %s found!\r\n", wifi_ssid);
    return ("");
  }
  Serial.printf("SSID match found at %d. Connecting...\r\n", i_strongest);
  WiFi.begin(wifi_ssid, wifi_pass, 0, WiFi.BSSID(i_strongest));
  return (WiFi.BSSIDstr(i_strongest));
}
I have tested the code with reverse conditions (i.e. to connect to the weakest signal) and it works this way, too ;)...

Who is online

Users browsing this forum: No registered users and 92 guests