BuilderKit firmware may stuck in connect()

#1

The BuilderKit firmware as of May 03, 2016, may stuck in connect() function if WiFi is bad.

  WiFi.begin(WIFI_SSID, WIFI_PASS);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }

This code invokes WiFi.begin once, and then waits for WiFi to become connected.
However, per WiFi.status() docs, the status may become WL_CONNECT_FAILED “when the connection fails for all the attempts”.
Arduino example code places the WiFi.begin line inside the loop, so that the WiFi stack can retry connection indefinitely.

  device.connectSecure(wifiClient, LOSANT_ACCESS_KEY, LOSANT_ACCESS_SECRET);
  while(!device.connected()) {
    delay(500);
  }

This code starts a connection to Losant, and then wait for it to become connected.
If WiFi becomes disconnected at this point, it’s impossible to get connected to Losant, and the code is stuck in this loop.
To resolve this issue, check for WiFi connectivity inside the loop, and return if WiFi get disconnected. After returning, the next loop() will invoke connect() to try again.

1 Like

#2

For reference, my connect() function currently looks like this:

bool connect()
{
  int wifiAttempts = 0;
  while (WiFi.status() != WL_CONNECTED) {
    WiFi.begin(WIFI_SSID, WIFI_PASS);
    delay(500);
    if (++wifiAttempts > 120) {
      return false;
    }
  }

  device.connectSecure(wifiClient, LOSANT_ACCESS_KEY, LOSANT_ACCESS_SECRET);

  int losantAttempts = 0;
  while (!device.connected()) {
    if (WiFi.status() != WL_CONNECTED) {
      return false;
    }
    delay(500);
    if (++losantAttempts > 120) {
      return false;
    }
  }

  return true;
}

void ensureConnected()
{
  bool needReconnect = false;
  if (WiFi.status() != WL_CONNECTED) {
    needReconnect = true;
  }
  if (!device.connected()) {
    needReconnect = true;
  }
  while (needReconnect) {
    needReconnect = !connect();
  }
}

ensureConnected() is called at the top of loop(). It’s unnecessary in setup().

full code

0 Likes

#3

This look good. I’ll review it and make appropriates changes to the repo. Thanks!

0 Likes

#4

The updated sample code invokes ESP.restart() when it cannot connect to Losant within 5 seconds.


Is there a particular reason that a reset is required?
Otherwise, I feel it’s overkill. It should be sufficient to disconnect the WiFi, wait a few seconds, and reconnect to WiFi.


The WiFi connection code is still:


In case WiFi goes into WL_CONNECT_FAILED state, it would be stuck forever.

0 Likes