Skip to content

Commit

Permalink
Merge pull request #1 from devgs/fix/wifi_connected_race_cond
Browse files Browse the repository at this point in the history
Fix/wifi connected race cond
  • Loading branch information
Cossid committed Apr 19, 2024
2 parents d1386a8 + 3e964aa commit 632787c
Showing 1 changed file with 42 additions and 6 deletions.
48 changes: 42 additions & 6 deletions cores/beken-72xx/arduino/libraries/WiFi/WiFiEvents.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,39 @@ static void wifiEventTask(void *arg) {
}
}

// There is a race condition, when we have an event about a successful
// connection but no SSID yet returned by BDK. Even a single millisecond
// delay should prevent this from happening. It's better to waste a bit
// of time here than to lose a valid connection down the line.
static String waitForValidSSID(WiFiClass *pWiFi) {
String result;

// Read the initial value that might just be available already.
result = pWiFi->SSID();

if (!result.length()) {
for (std::size_t i = 0; i < 10; i++) {
// Delay and query again.
delay(1);
result = pWiFi->SSID();

if (result.length()) {
LT_DM(WIFI, "Got valid SSID after %u delays", i + 1);
break;
}

// It's a good idea to yield.
yield();
}

if (!result.length()) {
LT_WM(WIFI, "Could not obtain a valid SSID after %u delays", i);
}
}

return result;
}

void wifiEventSendArduino(EventId event) {
event = (EventId)(RW_EVT_ARDUINO | event);
wifiStatusCallback((rw_evt_type *)&event);
Expand All @@ -52,11 +85,6 @@ void wifiEventHandler(rw_evt_type event) {

LT_DM(WIFI, "BK event %u", event);

if (event <= RW_EVT_STA_GOT_IP)
pDATA->lastStaEvent = event;
else
pDATA->lastApEvent = event;

EventId eventId;
EventInfo eventInfo;
String ssid;
Expand Down Expand Up @@ -103,7 +131,7 @@ void wifiEventHandler(rw_evt_type event) {

case RW_EVT_STA_CONNECTED:
eventId = ARDUINO_EVENT_WIFI_STA_CONNECTED;
ssid = pWiFi->SSID();
ssid = waitForValidSSID(pWiFi);
eventInfo.wifi_sta_connected.ssid_len = ssid.length();
eventInfo.wifi_sta_connected.channel = pWiFi->channel();
eventInfo.wifi_sta_connected.authmode = pWiFi->getEncryption();
Expand Down Expand Up @@ -145,5 +173,13 @@ void wifiEventHandler(rw_evt_type event) {
break;
}

// Publish state update only after the event data is retrieved.
// This relates to the race condition with RW_EVT_STA_CONNECTED.
if (event <= RW_EVT_STA_GOT_IP) {
pDATA->lastStaEvent = event;
} else {
pDATA->lastApEvent = event;
}

pWiFi->postEvent(eventId, eventInfo);
}

0 comments on commit 632787c

Please sign in to comment.