Skip to content

Commit

Permalink
Connect to strongest AP in case of multiple AP's with same SSID (ESP8…
Browse files Browse the repository at this point in the history
…266 and ESP32)
  • Loading branch information
arjenhiemstra committed Oct 31, 2023
1 parent 8b29fe8 commit 6410cb5
Showing 1 changed file with 67 additions and 1 deletion.
68 changes: 67 additions & 1 deletion src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,56 @@ void extraLoop()
#endif
}

#ifdef ARDUINO_ARCH_ESP8266
void get_wifi_bssid(const char *ssid, uint8_t *bssid, uint32_t *wifi_channel)
{
bssid = nullptr;
int n = WiFi.scanNetworks(false, true);

if (n < 1) // no networks found
return;

// sort networks on RSSI value
int indices[n];
for (int i = 0; i < n; i++)
{
indices[i] = i;
}

for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (WiFi.RSSI(indices[j]) > WiFi.RSSI(indices[i]))
{
std::swap(indices[i], indices[j]);
}
}
}

// loop through result and match highest RSSI SSID
for (int i = 0; i < n; i++)
{
char scan_ssid[33]; // ssid can be up to 32chars, => plus null term
strlcpy(scan_ssid, WiFi.SSID(indices[i]).c_str(), sizeof(scan_ssid));

if (strcmp(ssid, scan_ssid) == 0)
{
if (WiFi.BSSID(indices[i]) != 0)
{
bssid = WiFi.BSSID(indices[i]);
*wifi_channel = WiFi.channel();
return;
}
else
{
return;
}
}
}
}
#endif

void checkWifi()
{
int i = 0;
Expand Down Expand Up @@ -142,7 +192,23 @@ void setup_wifi()
}
#endif

WiFi.begin(WIFI_SSID, WIFI_PWD, 0,0,true);
uint8_t *bssid = nullptr;
uint32_t wifi_channel = 0;
#ifdef ARDUINO_ARCH_ESP8266
get_wifi_bssid(WIFI_SSID, bssid, &wifi_channel);
#else //assume ESP32
WiFi.setSortMethod(WIFI_CONNECT_AP_BY_SIGNAL);
WiFi.setScanMethod(WIFI_ALL_CHANNEL_SCAN);
#endif

if (bssid != nullptr)
{
WiFi.begin(WIFI_SSID, WIFI_PWD, wifi_channel, bssid);
}
else
{
WiFi.begin(WIFI_SSID, WIFI_PWD, 0, 0, true);
}
checkWifi();
mqttSerial.printf("Connected. IP Address: %s\n", WiFi.localIP().toString().c_str());
}
Expand Down

0 comments on commit 6410cb5

Please sign in to comment.