BLYNK.connect() timeout event syntax

I want to add an event if a connection timeout occurs and was wondering if I can get a comment on what I have found (and it compiles).

Reading the doc’s I see that “bool result = Blynk.connect();” will give a false if the default 30 second timeout occurs. So I have said…

Blynk.begin(auth, ssid, pass);
 
 while (Blynk.connect() == false) {
     bool result = Blynk.connect();      
       if(!result){
           goToSleep();
       }
 }

Thanx

Please edit your post and add triple backticks ( ``` ) before and after your sketch.

I had it inside “code” mark down but the quotes seem to maintain format so thanx for that

Blynk.begin is a blocking command. Code execution will not progress on to the while loop until a connection to WiFi and the Blynk server has successfully been established.
This makes all of your code within the while loop redundant.

If you want a non-blocking connection routine then you should start by manually creating the WiFi connection, then if this is successful use Blynk.config() and Blynk.connect().
Using a while loop is not appropriate in that situation.

Pete.

1 Like

@PeteKnight Thank you for your comment and feedback, the fountain of knowledge that you offer this forum is second to none and greatly appreciated.

You’re right, this is about the WiFi connection more than the Blynk server connection. If the Wifi connects I don’t seem to have failures or timeouts with the Blynk server connection but being a rural location and battery project there can be times when there is no WiFi due to a blackout and just going back to sleep till the next cycle seems the logical way to go.

Information or documentation just seems to be very thin on this subject?

You might want to have a look at this project…

Note that you’ll need to use blynk.cloud rather than blynk-cloud.com in the Blynk.config() for the new version of Blynk, and add your template ID at the very top of the sketch.

It’s worth reading through the whole of the topic, as the project changes significantly over time.

Pete.

1 Like

Thank you yet again @PeteKnight, Mr Google didn’t find this so the reference referral is much appreciated.

FYI, before your reply came through I had a crack at my own 2-step, 2 x timeout config. It compiles fine and I just need to test it to confirm. It’s close to the same as your beehive project except I also added the Blynk connect timeout to cover all bases. For archive completeness this is what I’ll try (and refine as needed). Once tested and confirmed I’ll report back for the record.

Once again, thank you!
Cheers
Ralph

// Constants
#include "credentials.h"
#define BLYNK_FIRMWARE_VERSION        "0.1.0"
#define BLYNK_PRINT Serial
#include <BlynkSimpleEsp8266_SSL.h>

// WiFi Callback
bool connectToWiFi(void){   
    WiFi.begin(ssid, pass);
    int i = 0;
    while(WiFi.status() != WL_CONNECTED){
        i++;
        delay(500);
        if(i >= 60){
            return false;
        }
    }
    WiFi.mode(WIFI_STA);
    return true;
}

// Setup Calls
  Serial.println("ESP Awake Now............");

  bool wifiConnect = connectToWiFi();
  if(wifiConnect == false){
      goToSleep();
  }
  Blynk.config(auth);   
  while (Blynk.connect() == false) {
      bool result = Blynk.connect();    
        if(result == false){
           goToSleep(); 
        }
  }
  
  Serial.println(""); Serial.println("Blynk Connected............\n");

I still think the while loop is the wrong approach.

When you call Blynk.connect() it will attempt to connect until the timeout expires. The default timeout is 30 seconds.

If it fails then Blynk.connected() (note the difference!) will return false.

Whenever the code encounters a Blynk.run() command, if Blynk.connected() is false then it will attempt to re-connect again.
For this reason, Blynk.connect() could be regarded as being redundant, but I prefer to use it anyway.

More (Legacy) info here…

Pete.

1 Like

I’ve been trying to get this bit of the project sorted theoretically before doing a test but I think I need to try testing the theory now before I waste any more of your time.

I now realize that I don’t need to quit on failure as it would put abnormalities in my daily averaging results. Also in run mode I’ll never hit the main loop so “Blynk.run()” never happens. There will be a “PGM” mode to be always on for updates but that’s separate, already tested and works fine.

Things I’ve been doing have come from my understanding, what already works and the V2 doc’s

If I understand what you are saying when “Blynk.config & Blink.connect” are called setup doesn’t continue till either a connection or timeout? If that’s the case I will try this then:-

 Serial.println("ESP Awake Now............");
  bool wifiConnect = connectToWiFi();
    if(wifiConnect == true){
      Blynk.config(auth);
        bool result = Blynk.connect();
          if(result == true){
            Serial.println("Blynk Connected............");
          }else{
            Serial.println("Blynk Failed to connect but we will Update the data anyway\n");
          }
    }else{
      Serial.println("WiFi Connection Failure......We will Update the data anyway\n");
  }  

Thanks again for all your time and help @PeteKnight
Cheers
Ralph

You are correct. The “while” statement is redundant andI have now tested my latest version as per my last reply and it seems to work as you’d expect. Here’s the serial monitor proof

Thanks for your patience and help on this
Cheers
Ralph

1 Like

Good day.
Please tell me how to reduce this interval (30 seconds)?
It is necessary that connections to the server be provided, for example, once a minute, but that they be of a minimum duration and do not interrupt the execution of program cycles, since there are inputs and outputs of the controller that must be processed.
I’m talking about Blynk 2.0 of course.
ESP32 controller.
Thank you.

Well, the normal scenario would obviously be that you create a connection at start-up and maintain it indefinitely.
The you can use Blynk.connect(timeout in seconds) to reduce (or increase) the default amount of time tat the process will attempt to establish that connection before timing-out, but obviously the timeout can only be reduced so far before it fails to make a connection at all.

When you’re using Blynk.config the Blynk.connect is optional, and its only really necessary when you want to specify a timeout. However, I prefer to explicitly call Blynk.connect at the point where I want the connection to be created.
With Blynk.config, the device will attempt to connect to the Blynk server if it’s currently disconnected when it encounters a Blynk.run() command, which is why Blynk.connect is optional.

Obviously, if there is no WiFi connection or no internet connection, or the Blynk server can’t be reached because it is down, then having Blynk.run() in the void loop will make the program execution freeze for the timeout period each time the void loop is executed.
This is why its a good idea to have Blynk.run() inside an if statement that checks if the device is running in connected mode. You can maybe have a timer that sets a connected mode flag if it has successfully connected to the internet and pinged an external server.

The Blynk.connected command returns a Boolean true/false if the connection was established…

bool success=Blynk.connected(optional timeout seconds);

Pete.

1 Like

If possible, a question about Blynk.connect().
There is no detailed explanation in the documentation, and it is not entirely clear to me what exactly is called Blynk.connect(timeout)? Is this the time the controller waits to connect to the server, or is it the period of time after which the connection is retried?
I don’t have a complete understanding of how Blynk.connect() works and therefore I can’t apply it correctly…
Thank you!

When Blynk.connect(timeout) is called the device will attempt to connect to the Blynk server via the already existing internet connection.
If a connection hasn’t been established by the time the timeout period has passed, the code will continue without the device being connected to Blynk.

Pete.

2 Likes

I use this sketch to connect:

bool BlynkCon = false; // server connection status
bool wifiOk = false;  //  wifi connection status
unsigned long prevMil; // time variable

if ( (wifiOk) && (!BlynkCon) && (millis() - prevMil > 40000) ) //connect to the server if there is wifi and there is no connection to the server. Period 40 sec.
    {
     Blynk.connect(25); 
     prevMil = millis();
    }
BlynkCon = Blynk.connected();
if (BlynkCon) 
    {
    Blynk.run();
    }

Everything works only if the default timeout (Blynk.connect() ).
But if I use any other timeout (for example 25) - nothing works - the BlynkCon variable never becomes “true”, and the connection to the server appears for a few seconds and disappears, then appears and disappears again, and so on.
I can’t figure out if this is a bug in the library or I made a mistake somewhere…

P.S. The reason is not insufficient timeout, because the real connection time is up to 5 seconds. And even if the timeout is 5 seconds, there is a connection to the server, but it disappears continuously and Blynk.connected() continuously = false.

It’s impossible to say based on just a small snippet of code.

Pete.

#define BLYNK_TEMPLATE_ID		"TMPLxxxxxxxx"
#define BLYNK_DEVICE_NAME		"DeviceName"
#define BLYNK_AUTH_TOKEN 		"AuthToken"
#define BLYNK_FIRMWARE_VERSION	"0.0.1" 
// #define BLYNK_PRINT Serial
#include <BlynkSimpleEsp32.h>
#include <Update.h>  
#include <HTTPClient.h>  
char auth[] = BLYNK_AUTH_TOKEN;
bool StartDelay_24813074 = false;
bool BlynkCon = false; 
unsigned long ConnectTime_24813074;
unsigned long prevMil;
#include <WiFi.h>
#include <EEPROM.h>
bool ESPControllerWifiClient_HRD = 0;
bool ESPControllerWifiClient_status = 1;
bool isWifiClientReconectWite = 0;
unsigned long startWifiClientReconectWite ;
bool ESPControllerWifiClient_isDHCP = 1;
bool ESPControllerWifiClient_IsNeedReconect = 0;
bool ESPControllerWifiClient_workStatus = 1;
char ESPControllerWifiClient_SSID[40] = "12345678";
char ESPControllerWifiClient_password[40] = "12345678";
IPAddress ESPControllerWifiClient_ip(0, 0, 0, 0);
IPAddress  ESPControllerWifiClient_dns (0, 0, 0, 1);
IPAddress  ESPControllerWifiClient_gateway (0, 0, 0, 1);
IPAddress ESPControllerWifiClient_subnet (255, 255, 255, 0);
uint8_t ESPControllerWifiClient_mac[6] = {0x0, 0x0, 0x0, 0x0, 0x0, 0x0};
bool isNeededEEpromCommit = 0;
bool _SysParRead_1_Out;
bool Out_238044322_149185419;
bool Out_128069072_149185419;

String overTheAirURL = "";
BLYNK_WRITE(InternalPinOTA) 
{
    	overTheAirURL = param.asString();
    	HTTPClient http;
    	Blynk.disconnect();
    	http.begin(overTheAirURL);
    	int httpCode = http.GET();
    	if (httpCode != HTTP_CODE_OK) 
    {
        		return;
        	
    }
    	int contentLength = http.getSize();
    	if (contentLength <= 0) 
    {
        		return;
        	
    }
    	bool canBegin = Update.begin(contentLength);
    	if (!canBegin) 
    {
        		return;
        	
    }
    	Client& client = http.getStream();
    	int written = Update.writeStream(client);
    	if (written != contentLength) 
    {
        		return;
        	
    }
    	if (!Update.end()) 
    {
        		return;
        	
    }
    	if (!Update.isFinished()) 
    {
        		return;
        	
    }
    	reboot();
}
void setup()
{
    
    Blynk.config(auth);
    EEPROM.begin(1);
    WiFi.mode(WIFI_STA);
    if (WiFi.getAutoConnect() != true) WiFi.setAutoConnect(true);
    WiFi.setAutoReconnect(true);
    _esp32WifiModuleClientReconnect();
    _parseMacAddressString(WiFi.macAddress(), ESPControllerWifiClient_mac);
}
void loop()
{
    if (((ESPControllerWifiClient_status)) && (!BlynkCon) && (millis() - prevMil > (60 * 1000)))
    {
        Blynk.connect();
        prevMil = millis();
    }
    BlynkCon = Blynk.connected();
    if (BlynkCon)
    {
        Blynk.run();
        Out_238044322_149185419 = BlynkCon; 
          if (Out_238044322_149185419) 
        {
            	    StartDelay_24813074  = _isTimer(ConnectTime_24813074, 1000);
        }
        else 
        {
            	    StartDelay_24813074 = false;
        }
        Out_128069072_149185419 = StartDelay_24813074;
    }
    else
    {
        Out_238044322_149185419 = false;
        Out_128069072_149185419 = false;
    }
    if (isNeededEEpromCommit)
    {
        EEPROM.commit();
        isNeededEEpromCommit=0;
    }
    if(ESPControllerWifiClient_IsNeedReconect) 
    {
        _esp32WifiModuleClientReconnect();
        ESPControllerWifiClient_IsNeedReconect = 0;
    }
    ESPControllerWifiClient_status = WiFi.status() == WL_CONNECTED;
    if (ESPControllerWifiClient_status) 
    {
         if (! ESPControllerWifiClient_HRD) 
        {
            ESPControllerWifiClient_ip =  WiFi.localIP();
            ESPControllerWifiClient_subnet =  WiFi.subnetMask();
            ESPControllerWifiClient_gateway =  WiFi.gatewayIP();
            ESPControllerWifiClient_dns =  WiFi.dnsIP();
            ESPControllerWifiClient_HRD = 1;
        }
    }
     else 
    {
        ESPControllerWifiClient_HRD = 0;
    }
    if(ESPControllerWifiClient_workStatus&&(! ESPControllerWifiClient_status))
    {
        if (! isWifiClientReconectWite) 
        {
            isWifiClientReconectWite = 1;
            startWifiClientReconectWite = millis();
        }
         else 
        {
            if (_isTimer(startWifiClientReconectWite , 5000)) 
            {
                WiFi.disconnect();
                _esp32WifiModuleClientReconnect();
                isWifiClientReconectWite = 0;
            }
        }
    }
    
    _SysParRead_1_Out =  ESPControllerWifiClient_status;
}
bool _isTimer(unsigned long startTime, unsigned long period)
{
    unsigned long currentTime;
    currentTime = millis();
    if (currentTime>= startTime) 
    {
        return (currentTime>=(startTime + period));
    }
     else 
    {
        return (currentTime >=(4294967295-startTime+period));
    }
}
byte readByteFromEEPROM(int addres, byte bitAddres, byte chipAddres)
{
    return EEPROM.readByte(addres);
}
void updateByteToEEPROM(int addres, byte bitAddres, byte chipAddres, byte value)
{
    EEPROM.writeByte(addres, value);
    isNeededEEpromCommit = 1;
    return;
}
int hexStrToInt(String instring)
{
    byte len = instring.length();
    if  (len == 0) return 0;
    int result = 0;
    for (byte i = 0; i < 8; i++)   
    {
        char ch = instring[i];
        if (ch == 0) break;
        result <<= 4;
        if (isdigit(ch))
        result = result | (ch - '0');
        else result = result | (ch - 'A' + 10);
    }
    return result;
}
void _esp32WifiModuleClientReconnect()
{
    if(ESPControllerWifiClient_isDHCP) 
    {
         WiFi.config(0U, 0U, 0U, 0U, 0U);
    }
     else 
    {
        WiFi.config(ESPControllerWifiClient_ip, ESPControllerWifiClient_gateway, ESPControllerWifiClient_subnet, ESPControllerWifiClient_dns , ESPControllerWifiClient_dns);
    }
    WiFi.begin(ESPControllerWifiClient_SSID, ESPControllerWifiClient_password);
}
bool _checkMacAddres(byte array[])
{
    bool result = 0;
    for (byte i = 0; i < 6; i++)
    {
        if (array[i] == 255) 
        {
            return 0;
        }
        if (array[i] > 0) 
        {
            result = 1;
        }
    }
    return result;
}
void _parseMacAddressString(String value, byte array[])
{
    int index;
    byte buffer[6] = {255, 255, 255, 255, 255, 255};
    byte raz = 0;
    String tempString;
    while ((value.length() > 0) && (raz <= 6)) 
    {
        index = value.indexOf(":");
        if (index == -1) 
        {
            tempString = value;
            value = "";
        }
         else 
        {
            tempString = value.substring(0, index);
            value = value.substring(index + 1);
        }
        buffer[raz] = byte(hexStrToInt(tempString));
        raz++;
    }
    if (_checkMacAddres(buffer))
    {
        for (byte i = 0; i < 6; i++)
        {
            array[i] = buffer[i];
        }
    }
}
bool _compareMacAddreses(byte array1[], byte array2[])
{
    for (byte i = 0; i < 6; i++)
    {
        if (array1[i] != array2[i]) 
        {
            return 0;
        }
    }
    return 1;
}
bool _compareMacAddresWithString(byte array[], String value)
{
    byte buffer[6] = {255, 255, 255, 255, 255, 255};
    _parseMacAddressString(value,  buffer);
    return _compareMacAddreses(array, buffer);
}
bool _checkMacAddresString(String value)
{
    byte buffer[6] = {255, 255, 255, 255, 255, 255};
    _parseMacAddressString(value,  buffer);
    return _checkMacAddres(buffer);
}
String _macAddresToString(byte array[])
{
    String result = "";
    String  temp ="";
    for (byte i = 0; i < 6; i++)
    {
        temp=String(array[i],HEX);
        if (temp.length()  < 2) 
        {
            temp = String("0") + temp;
        }
        result = result + temp;
        if (i < 5) 
        {
               result = result + String(":");
        }
    }
    result.toUpperCase();
    return result;
}
void reboot()
{
    #if defined(ARDUINO_ARCH_MEGAAVR)
    	wdt_enable(WDT_PERIOD_8CLK_gc);
    #elif defined(__AVR__)
    	wdt_enable(WDTO_15MS);
    #elif defined(__arm__)
    	NVIC_SystemReset();
    #elif defined(ESP8266) || defined(ESP32)
    	ESP.restart();
    #else
    	#error "MCU reset procedure not implemented"
    #endif
    	for (; ;) 
    {
    }
}
BLYNK_CONNECTED()
{
    	ConnectTime_24813074 = millis();
    	Serial.println(String(ConnectTime_24813074));
    	Blynk.syncAll();
    	
}

Here is the whole code.
But I don’t understand why it is needed, if by default - Blynk.connect() - everything works correctly, but with any other timeout value - nothing works.

Why aren’t you calling Blynk.connect(timeout) from your void setup, and why s9 much stuff in your void loop? - this is probably what is causing the disconnections in the first place.

Pete.

1 Like

Ok. Please tell me, did you use Blynk.connect(timeout) in your projects? Are you okay with this?

I don’t run Blynk code on my devices, I use MQTT and Node-Red. But, I have used it in the past and it works as expected when you use it once, in void setup.

Pete.

1 Like