[SOLVED] How to run Blynk.run() only when WiFi connection is established

@Cejfi updated sketch with various notes:

/* CheckServerV2.ino by Costas 17/7/2016, revised 16/7/2017

  Notes:
  
  Blynk.connectWiFi() doesn't cover WiFi failures i.e. router problems as it's blocking code

  Default Blynk.connect() tries for 5 seconds not 30s as per http://docs.blynk.cc/#blynk-firmware-connection-management-blynkconnect
  Not 6s timeout either (2000UL * 3) as indicated by:
  https://github.com/blynkkk/blynk-library/blob/master/src/Blynk/BlynkProtocol.h#L50
     bool connect(uint32_t timeout = BLYNK_TIMEOUT_MS*3) {
      
  https://github.com/blynkkk/blynk-library/blob/master/src/Blynk/BlynkConfig.h#L37
    #define BLYNK_TIMEOUT_MS     2000UL    
  
  See the 5000L in https://github.com/blynkkk/blynk-library/blob/master/src/Blynk/BlynkProtocol.h#L343
    lastLogin = lastActivityIn - 5000L;  // Reconnect immediately   
  
*/

//#define BLYNK_DEBUG
#define BLYNK_TIMEOUT_MS  750  // must be BEFORE BlynkSimpleEsp8266.h doesn't work !!!
#define BLYNK_HEARTBEAT   17   // must be BEFORE BlynkSimpleEsp8266.h works OK as 17s
#define BLYNK_PRINT Serial    
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>

BlynkTimer timer;

char ssid[]            = "xxxxxxxxxxxxxxxxxx";
char pass[]            = "xxxxxxxxxxxxxxxxxx";
char auth[]            = "xxxxxxxxxxxxxxxxxx";
char server[]          = "blynk-cloud.com";
unsigned int port      = 8442;

void setup() {
  Serial.begin(115200);
  Serial.println();

  // line below is blocking code, consider regular WiFi connection with timeout if you have router problems
  Blynk.connectWiFi(ssid, pass); // used with Blynk.connect() in place of Blynk.begin(auth, ssid, pass, server, port);

  // line below needs to be BEFORE Blynk.connect()
  timer.setInterval(11000L, CheckConnection); // check if still connected every 11s  
  
  Blynk.config(auth, server, port);
  Blynk.connect();                     
}

void CheckConnection(){    // check every 11s if connected to Blynk server
  if(!Blynk.connected()){
    Serial.println("Not connected to Blynk server"); 
    Blynk.connect();  // try to connect to server with default timeout
  }
  else{
    Serial.println("Connected to Blynk server");     
  }
}

void loop() {
  if(Blynk.connected()){
    Blynk.run();
  }
  timer.run();
}
6 Likes