Check connection status in loop and reconect

:cry: Avoid all delays…please…

one problem solved:!!!
i Typed the blynk.config command as follows:
Blynk.config(wifi,auth,“139.59.206.133”);
the “wifi” word made the diferrence and the command worked!!!
instead of ip you can use blynk-cloud.com etc…

1 Like

Hi, Costas.
In my project in setup() I use wifi.autoConnect(“AutoConnectAP”) function from library WiFiManager.
It is very useful for setting WiFi parameters (ssid and pass). The project works Ok. If WiFi or Internet is (are) lost the device must continue its work as stand-alone device - this is provided in main loop() with
if(Connected2Blynk)
{
Blynk.run();
}
But if WiFi or Internet is (are) lost and device resetted or power turned off and turned on again
function wifi.autoConnect(“AutoConnectAP”) transfers device in WiFi access point and will wait the entering of WiFi Network parameters. For avoid such case it would can to use a button on board and check its state in main loop - if it is pressed then called function wifi.autoConnect(“AutoConnectAP”), stup() and check connection to WiFi and Blynk using as in Your skatch above. But I would not like use a button.
What do You can to advise me?
Thanks.

@klg you have a few options:

  1. Learn to love buttons. If you use the WioLink you have a ready made “config” button that you can use. Even a piece of wire will do.

  2. Switch the WiFi Manager mode to only be called on request. This request can be called in Blynk and you can hardcode the AP of your Smartphone in the sketch. This way you can connect anywhere and then use Blynk’s Terminal to access WiFi Manager and change the WiFi credentials.

HTH

Thank You.

Hi, Costas. Help me please.
Below showed my sketch, in which I tried to implement the re-connection to the WiFi and Blynk, as you advised above.
But I could not get reconnection and cannot understand, what I do not right.

#include <DNSServer.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <BlynkSimpleEsp8266.h>
#include <EEPROM.h>
#include <ESP8266mDNS.h>
#include <WiFiManager.h>
#include <TimeLib.h>
#include <WidgetRTC.h>
#include <SimpleTimer.h>

WidgetRTC   rtc;
WiFiManager wifi;
SimpleTimer timer;

String ssid;
String pass;

int analogPin = 0;
int rssi;

char auth[] = "xxxxxxxxxxxxxxxxxxxx"; 
unsigned int cur_moisture = 0;

bool Connected2Blynk = false;

//-------------------------------------
void clockDisplay()
{
  String currentTime = String(hour()) + ":" + minute() + ":" + second();
  String currentDate = String(day()) + "." + month() + "." + year();
  Serial.println(currentTime);
  Blynk.virtualWrite(V0, currentTime);
  Blynk.virtualWrite(V1, currentDate);
}


unsigned int moist_sen_level()
{
  unsigned int val;

  val = analogRead(0);
  Serial.print("ADC val="); Serial.println(val);
  val = (val * 100) / 1023;
  Serial.print("moist val(%)="); Serial.println(val);
  return (val);
}
//----------------------------------------
void MyWiFi()
{
  int mytimeout = millis() / 1000;
  ssid = wifi.getSSID();
  pass = wifi.getPassword();
  Serial.print("WiFi param. are: ");
  Serial.print(ssid); Serial.print("__"); Serial.println(pass);

  WiFi.begin(ssid.c_str(), pass.c_str());
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
    if ((millis() / 1000) > mytimeout + 4)
    { // try for less than 4 seconds to connect to WiFi router
      break;
    }
  }

  if (WiFi.status() == WL_CONNECTED)
  {
    Serial.print("\nIP address: ");
    Serial.println(WiFi.localIP());
  }
  else
  {
    Serial.println("\nCheck Router ");
  }
  Blynk.config(auth);
  Connected2Blynk = Blynk.connect(1000);  // 1000 is a timeout of 3333 milliseconds
  mytimeout = millis() / 1000;
  while (Blynk.connect(1000) == false) {
    if ((millis() / 1000) > mytimeout + 4)
    { // try for less than 4 seconds
      break;
    }
  }
}

void CheckConnection()
{
  Connected2Blynk = Blynk.connected();
  if (!Connected2Blynk)
  {
    Serial.println("Not connected to Blynk server");
    MyWiFi();
  }
  else
  {
    Serial.println("Still connected to Blynk server");
  }
}

//------------------------------------
void setup()
{
  Serial.begin(115200);
  wifi.setTimeout(180);
  if (!wifi.autoConnect("AutoConnectAP"))
  {
    Serial.println("failed to connect and hit timeout");
    delay(3000);
  }
  else
  {
    Serial.println("connected");
    ssid = wifi.getSSID();
    pass = wifi.getPassword();
    Blynk.config(auth);    //Blynk.config(auth,WiFi.localIP());
    Serial.print("ssid="); Serial.println(ssid.c_str());
    Serial.print("pass="); Serial.println(pass.c_str());
  }

  if (Blynk.connect() == false)
  {
    delay(4000);
  }

  //first_connection = true;
  Serial.print("Blynk.connect() = "); Serial.println(Blynk.connect());

  setSyncInterval(1);
  rtc.begin();
//  timer.setInterval(20000L, clockDisplay);
//  timer.setInterval(20000L, main_function);
  timer.setInterval(20000L, CheckConnection);
  Serial.println("done setup");
}
//----------------------------
void main_function()
{
  cur_moisture = moist_sen_level();
  Blynk.virtualWrite(V2, cur_moisture);
  rssi = WiFi.RSSI();
  Serial.print("RSSI="); Serial.println(rssi);
}
//----------------------------------------------------------------------------

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

Messages from terminal

*WM: AutoConnect
*WM: Connecting as wifi client...
*WM: Using last saved values, should be faster
*WM: Connection result: 
*WM: 3
*WM: IP Address:
*WM: 192.168.1.39
connected
*WM: Reading SSID
*WM: SSID: 
*WM: klg
*WM: Reading Password
*WM: Password: klgklgklg
ssid=klg
pass=klgklgklg
Blynk.connect() = 1
done setup
Still connected to Blynk server
Still connected to Blynk server
Not connected to Blynk server
WiFi param. are: klg__klgklgklg
..........
Check Router 
Not connected to Blynk server
WiFi param. are: klg__klgklgklg
..........
Check Router 
Not connected to Blynk server
WiFi param. are: klg__klgklgklg
..........
Check Router 
Not connected to Blynk server
WiFi param. are: klg__klgklgklg
..........
Check Router 
Not connected to Blynk server
WiFi param. are: klg__klgklgklg
..........

Ping of blynk-cloud.com:

What You can tell me?

1 Like

@klg Leonid so many things I don’t like in your sketch even though some of it was my code.

What ESP are you using as I notice you have the analogue port as 0?

I don’t like the time format with single digits for minutes and seconds.

I don’t like running WiFiManager sketches when I’m debugging so I disabled that in your sketch. Then I made lots of changes before it worked as it should. Let’s see if I can remember what they were.

Taking your sketch with line numbers 1 to 154:

  1. Comment out lines 122 to 125, you can’t have delays of 4000ms.

  2. I would comment out row 130 as the RTC should be fine without it.

  3. Comment out row 25 this bool is not required.

  4. Comment out row 78 this assignment is not required.

  5. Remove the 1000 at line 80 to leave as () line 81 will break you out of the while loop in 4s.

  6. Comment out line 128 you don’t want to be calling Blynk.connect() in a Serial.println().

  7. Comment out line 90 that assignment is not required.

  8. At line 91 change if (!Connected2Blynk) to if (!Blynk.connected())

Scrap all that I’ll send you a PM.

1 Like

Hi,

I was having the same problem.

I have an ESP8266 Sparkfun Thing Dev running a garage door project (Blynk app shows whether door is open, closed or in between, temp and humidity inside the garage; the door can be activated (open, stop, close) from app via a relay connected to ESP8266). I’d also put a manual pushbutton in the garage to activate the door via the relay.

However, whenever the ESP8266 lost connection to the router, the Blynk.run() function would block the manual pushbutton while it was trying to reconnect. As it is running through a WiFi extender which drops off and won’t reconnect to the main network from time to time, the ESP8266 could lose connection and then block the pushbutton for long periods while Blynk.run() was attempting to reconnect. The pushbutton not working really annoyed my wife.

Following the discussion on this thread (and a bit of experimentation) this code in the main loop seems to work (I’ve left the other functions out to save space - lastConnected is an unsigned long):

void loop()
{
  if (Blynk.connected()) {                        // connected to Blynk Server
    digitalWrite(activateLed, HIGH);              // turn off Blue LED
    Blynk.run();                                  // run Blynk activities
    lastConnected = millis();
  } 
  else {                                          // not connected to Blynk Server
    digitalWrite (activateLed, LOW);              // turn on Blue LED
    if (millis() > (lastConnected+120000)) {      // if it has been 2 minutes or more since the last connection or last attempt to connect to Blynk Server
      Blynk.connectWiFi(ssid, passwd);
      if (WiFi.status() == WL_CONNECTED){
        Blynk.config(auth);
        Blynk.connect();
      }
      lastConnected = millis();
    }
  }  
  checkDoorState();                               // check the position of the door and manual pushbuton
  sendDoorState();                                // send the status of the door on a change of status or once every 65 secs (to avoid flooding) 
  offLeds();                                      // turn off the LEDS on the panel if there's been no status change for 5 mins.
}

It waits 2 minutes after losing connection then between re connection attempts to minimize the time it’s blocking the pushbutton. It takes the WiFi extender about 2 minutes to reboot itself.

Hope this helps

1 Like

Thanks for helps
I will try it.

hi!

today i’ve faced the same problem: i had to restart my router, and my sonoff devices remained offline, even after 10+ minutes wait time. the only solution was to manually reset all esp devices! :frowning: some of them are in hardly accessible places…

i wonder if this is still considered normal behaviour of the latest blynk library? it is a shame that after we have working ota and embedded wifi in our boards, we still need to manually reset the devices after power outage or router restart. (yes, it happens rarely, but still not too nice)

my questions to the developers:

  • this is a known bug, or just not considered as an important issue?
  • if bug: it is planned to be resolved in near future?
  • currently there is an official / recommended workaround for this?

@Dmitriy, @vshymanskyy?

thanks!

@wanek,

Here is some code I use that seems to handle blynk connection states and reconnects just fine. You may want to really study the Blynk.connect() source as well, you’ll note it has an internal timeout check already.

#define BLYNK_PRINT Serial

// Blynk app
#include <BlynkSimpleEsp8266.h>
#include <RTClib.h>
#include <WidgetRTC.h>

// Non Blynk specific, local files
#include <Esp.h>

// device hardware specific
#include <PCF85063TP.h>
PCD85063TP RTC;

// WiFi settings
char ssid[] = "xxx";
char pass[] = "xxx";

// Blynk Settings
char auth[] = "xxx";

// Blynk Widgets
WidgetTerminal terminalWidget(V8);
WidgetRTC rtcWidget;  // requires RTC widget in app
BlynkTimer blynkTimer;  // SimpleTimer replacement

// Sketch variables
boolean connectInProgress;
int connectTimerId;


//
// This is called when Blynk has successfully connected
//
BLYNK_CONNECTED() 
{
  syncBlynkTime = true;   // (re)set time to synchronize with Blynk by default
  rtcWidget.begin();      // sets setSyncProvider internally and immediately call Blynk.sendInternal("rtc", "sync");
  setSyncInterval(5*60);  // subsequent time sync interval in seconds (5 minutes), once that interval has elapsed, time will set itself to timeNeedsSync

 
}

/*
 * Blynk feature was postponed until a later release
BLYNK_DISCONNECTED()
{
#ifdef BLYNK_PRINT
  Serial.println("[_\\|/_] Blynk Disonnected.");
  #endif
}
*/

//
// This is called when Smartphone App is opened
//
BLYNK_APP_CONNECTED() 
{
  #ifdef BLYNK_PRINT
  Serial.println("[_\\|/_] Blynk App Connected.");
  #endif
}

//
// This is called when Smartphone App is closed
//
BLYNK_APP_DISCONNECTED() 
{
  #ifdef BLYNK_PRINT
  Serial.println("[_\\|/_] Blynk App Disconnected.");
  #endif
}

 //
// checks connection to Blynk server and attempts reconnect if needed
//
void checkBlynkConnection()
{
  if (!Blynk.connected() && !connectInProgress)
  {
    connectInProgress = true;  

    if(!Blynk.connect())
    {
      #ifdef BLYNK_PRINT
      Serial.println("[_\\|/_] Blynk Connect failed");
      #endif
    }
    else
    {
      #ifdef BLYNK_PRINT
      Serial.println("[_\\|/_] Blynk Connected");  
      #endif
    }
  
    connectInProgress = false; // either it connected or timed out
  }
}

//
// all initialization and timer setups go here
//
void setup()
{
  Serial.begin(115200);
  RTC.begin();

  // timer tasks
  connectTimerId = blynkTimer.setInterval(300000L, checkBlynkConnection);   // check Blynk connection every 5 minutes

  // non-blocking Blynk setup
  Blynk.config(auth, BLYNK_DEFAULT_DOMAIN, BLYNK_DEFAULT_PORT);
  Blynk.disconnect(); // skip connecting to the Blynk server until checkBlynkConnection timer fires

  // this allows setup() to continue/exit and the main loop() to begin without blocking
  blynkTimer.setTimeout(2000L, checkBlynkConnection); // in  2 seconds, do initial connection check
}

// Main processing loop.
void loop()
{
  blynkTimer.run();
  
  // only attempt Blynk-related functions when connected to Blynk
  if (Blynk.connected())
  {
    Blynk.run();
  }
}

I use Blynk.connect() in setup, in loop I just have Blynk.run() and when I restart the router the wifi connects automatically and Blynk connection is re-established. It does show “Blynk connecting” a few times while the router is restarting.

Is not automatically connecting still an issue that I need to account for in my sketch?

Probably yes. What happens if your WiFi / internet is down for many hours? Presumably the rest of your sketch doesn’t run. For some projects it’s important the sketch proceeds with or without access to the Blynk server.

Thanks @Costas . Yeah, definitely haven’t tested WiFi being down for hours. But if it is down for a few minutes the rest of the sketch keeps running and WiFi is auto-reconnected after being available using the regular Blynk.connect() and Blynk.run().

@DIYTerminator there shouldn’t be any difference between minutes and hours. If your sketch can handle minutes it will probably handle hours.

@Costas, i think you might be my savior. I am trying to make a double check connection. First time we will check if we have wifi.
If not wifi connection: we are going offline and continue to execute the code.
If we have wifi connection: we will try to connect to blynk. If not connected to blynk in 3 seconds we give up and continue with the code. The periodic check to see if the blynk server is available should be around 10 minutes. in all this time my code should still work.

At this time everything is perfect if we have both wifi and blynk connection. Also perfect if we do not have wifi connection. The code works as it should. But if i have wifi and NOT blynk connection everything halts. I have tried so many times with so many pieces of code that even i don’t know what i am doing… Can you please have a look and tell mee what i am doing wrong? At this point with wifi connected but without blynk server, the led blinks once every xxx seconds. many seconds…


#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <SimpleTimer.h>

const char* ssid          = "SSID";
const char* password      = "PASS";
const char* host          = "SERVER";
const char  auth[]        = "TOKEN";
const int   checkInterval = 1000;

SimpleTimer timer;


void setup()
{
  pinMode(BUILTIN_LED, OUTPUT);    //led

  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Blynk.config(auth, host);
  timer.setInterval(checkInterval, blynkCheck);
  timer.setInterval(200, worktime);
}
void blynkCheck() {
  if (WiFi.status() == 3) {
    if (!Blynk.connected()) {
      Serial.println("WiFi OK, trying to connect to the server...");
      Blynk.connect();
    }
  }
  if (WiFi.status() == 1) {
    Serial.println("No WiFi connection, going offline.");
  }
}

void worktime() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(300);                       // wait
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(300); 
}

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

I used blynk.begin() and my board was rebooting. Found the truant line by commenting and trying out the sketch. I commented blynk.begin and replaced it with blynk.config() in setup and blynk.run in loop. Works well now.

Setup section part:

  //config blynk
  Blynk.config(settings.blynkToken, settings.blynkServer, atoi(settings.blynkPort));
 
  connectBlynk();
  //Blynk.begin(settings);

  //check if connected to Blynk server
  if (!wifiClient.connected()) {
    digitalWrite(BlynkLED, HIGH);
    digitalWrite(wifiLED, HIGH);
    Serial.print("\nBlynk server unreachable. Trying once more");
    connectBlynk();
    return;
  }

loop section

void loop()
{
  // Reconnect to Blynk Cloud
  if (!wifiClient.connected()) {
    digitalWrite(BlynkLED, HIGH);
    connectBlynk();
    return;
  }
  Blynk.run();  
}
1 Like

the code in the loop should be in a timer instead, otherwise it will block the rest of your sketch if there is no wifi / internet / blynk server available.

2 posts were split to a new topic: nodeMCU is not reconnecting after a wifi disruption