BLYNK
HOME       📲 GETTING STARTED       📗 DOCS       ❓HELP CENTER       👉 SKETCH BUILDER

Break blynk.run loop if internet is not available

Hi,
I’m creating a project with the ESP8266 module to control a relay module. I use two ways of communication.

  1. Blynk server: I’m using blynk app to control the relay.
  2. A Local access point with ESP8266.
    I’m using both because I want to control the relay by Blynk app when the internet is available and when the internet is not available I can control it with a self-made App that uses the router as a local access point.
    Now, my problem is, when the internet is available both are working fine I can control relay with both Blynk App and Self-made App but when the internet is not available the blynk loop stuck the program at Blynk.run because without internet it is trying to connect with blynk server and never come out from the loop so whole program stuck there.
    I want to know that is there any way that i can check the internet connection with ESP 8266 so that if it is not available then it can bypass the blynk loop or if blynk server is not connected for few minutes then it can come out from that loop and process further loop and after some time it can recheck that loop again.
    Thanks for helping me in this.

Try this
void loop(){
if(WiFi.status()!=WL_CONNECTED)
ESP.restart();
…loop code…
}

You should write your code so that it works with it without internet connection. There are a few good examples on the forum which does this alrady

Hi, Thanks for help.
but
(WiFi.status()!=WL_CONNECTED) this will only check if wifi is connected or not.
I need to check internet access.

Can you please send me their links. I already write my own code which can run without internet access but when i include Blynk code it stucks when router has no internet access.

Take a look at this, be sure to pay attention to the way it is connecting to BLYNK in the setup:

1 Like

This is my code and I’m stuck in this loop. Annotation%202020-01-07%20181357


#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>
char serverb[] = "blynk-cloud.com";
int port=80;
WiFiClient client;
WiFiServer server(80);

String  command =""; // Command received from Android device

// Set Relay Pins
int relay1 = D0;

char auth[] = "*****************";

 char ssid[] = "";
char pass[] = "";


void setup()
{
  pinMode(relay1, OUTPUT); 
  
  Serial.begin(115200);
  Serial.println("connecting wifi Manager");    
  connectWiFi();
  

Blynk.config(auth);
Serial.println("Check the blynk");
bool result = Blynk.connect(5);
 Serial.println(result);


  server.begin();
 

}

void loop()
{
  if (WiFi.status() != WL_CONNECTED)
  {
   
    delay(50000);
    Serial.println("Creating Hotspot");
    ESP.reset();
  }
    Blynk.run();

    client = server.available();
    if (!client) return; 
    command = checkClient ();
    Serial.println(command);

         if (command == "r1on" || command == "on" || command == "open" )
         {
          digitalWrite(relay1,HIGH);
          delay(400);
          digitalWrite(relay1,LOW);
          sendBackEcho(command);// send command echo back to android device
         }
    else if (command == "r1off" || command == "off" || command == "close")
    {
      digitalWrite(relay1,LOW);
      sendBackEcho(command);// send command echo back to android device
    }else if (command == "hotspot" || command == "setting" )
    {
 
      creatHotspot();
    }
     
    command = "";

}

/* connecting WiFi */
void connectWiFi()
{
  WiFiManager wifiManager;
  
wifiManager.setAPStaticIPConfig(IPAddress(192,168,1,50), IPAddress(192,168,1,1), IPAddress(255,255,255,0));
//wifiManager.setSTAStaticIPConfig(IPAddress(192,168,0,119), IPAddress(192,168,0,1), IPAddress(255,255,255,0));
if (!wifiManager.autoConnect("Relay-Config", "pakistan")) {
    Serial.println("failed to connect, we should reset as see if it connects");
    delay(3000);
    ESP.reset();
    delay(5000);
  }
  
  
}

/* check command received from Android Device */
String checkClient (void)
{
  while(!client.available()) delay(1); 
  String request = client.readStringUntil('\r');
  request.remove(0, 5);
  request.remove(request.length()-9,9);
  return request;
}

/* send command echo back to android device */
void sendBackEcho(String echo)
{
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println("");
  client.println("<!DOCTYPE HTML>");
  client.println("<html>");
  client.println(echo);
  client.println("</html>");
  client.stop();
  delay(1);
}
void gateControl(int x)
{
   if (x>0)
  {
    Serial.println("Gate Open");
    digitalWrite(relay1,HIGH);
    delay(400);
    digitalWrite(relay1,LOW);
    }
  
}  

BLYNK_WRITE(V1)
{Serial.println("Check3 ");
  int pinValue = param.asInt(); // assigning incoming value from pin V1 to a variable
  // You can also use:
  // String i = param.asStr();
  // double d = param.asDouble();
  Serial.print("V1 Slider value is: ");
  Serial.println(pinValue);
  
  gateControl(pinValue);
}
void creatHotspot()
{
  
  
  WiFiManager wifiManager;
  wifiManager.setAPStaticIPConfig(IPAddress(192,168,1,50), IPAddress(192,168,1,1), IPAddress(255,255,255,0));
wifiManager.startConfigPortal("OnDemandAP");
    if (!wifiManager.startConfigPortal("OnDemandAP")) {
      Serial.println("failed to connect and hit timeout");
      delay(3000);
      //reset and try again, or maybe put it to deep sleep
      ESP.reset();
      delay(5000);
    }

    //if you get here you have connected to the WiFi
    Serial.println("connected...yeey :)");
  }


  // put your main code here, to run repeatedly:

@JawadTariq please edit your post using the pencil icon at the bottom and add triple backticks at the beginning and end your code so that it displays correctly.
Triple backticks look like this:
```

Pete.

You could try changing to this in the loop()

 if (Blynk.connected()) {  // If connected run as normal
    Blynk.run();
  } 

I tried it but same results, programm trying to connect with blynk again and again

Maybe change Blynk to use port 8080

Pete.

See this topic:

It may have something to do with this line of code:

bool result = Blynk.connect(5);

From what I gather you will be blocked from doing anything while the device is trying to connect to the BLYNK server. It is figuring out how often the device should try, and for how long that will need to be adjusted to your needs. Maybe try giving the default a try and see if that improves it any.

bool result = Blynk.connect(); 

or

bool result = Blynk.connect(500);

That is expected behavior because original Blynk.run() is a blocking call.

You can try this sketch, based on yours, using non-blocking Blynk_WM to see how to solve the issue. This sketch has been tested and working OK, with or w/o Blynk / Internet.

#ifndef ESP8266
#error This code is intended to run on the ESP8266 platform! Please check your Tools->Board setting.
#endif

#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>

// Not use #define USE_SPIFFS  => using EEPROM for configuration data in WiFiManager
// #define USE_SPIFFS    false => using EEPROM for configuration data in WiFiManager
// #define USE_SPIFFS    true  => using SPIFFS for configuration data in WiFiManager
// Be sure to define USE_SPIFFS before #include <BlynkSimpleEsp8266_WM.h>

#define USE_SPIFFS                  true

// Force some params in Blynk, only valid for library version 1.0.1 and later
#define TIMEOUT_RECONNECT_WIFI                    10000L
#define RESET_IF_CONFIG_TIMEOUT                   true
#define CONFIG_TIMEOUT_RETRYTIMES_BEFORE_RESET    5
// Those above #define's must be placed before #include <BlynkSimpleEsp8266_WM.h>

#include <BlynkSimpleEsp8266_WM.h>    //https://github.com/khoih-prog/Blynk_WM

#include <DNSServer.h>
#include <ESP8266WebServer.h>

#include <Ticker.h>

#define HTTP_PORT       80

WiFiClient client;
WiFiServer server(HTTP_PORT);

String  command = ""; // Command received from Android device

// Set Relay Pins
#define    RELAY1_PIN    D0

Ticker relay_ticker;

#define PROGRAM_DEBUG       true

void set_relay(byte status) 
{ 
  digitalWrite(RELAY1_PIN, status); 
}

#define RELAY_CLICK_TIME_MS      400

void click_relay() 
{
  set_relay(HIGH);
  relay_ticker.once_ms(RELAY_CLICK_TIME_MS, set_relay, (byte) LOW);
} 

/* check command received from Android Device */
String checkClient (void)
{
  while (!client.available()) 
    delay(1);
    
  String request = client.readStringUntil('\r');
  request.remove(0, 5);
  request.remove(request.length()-9,9);
  return request;
}

/* send command echo back to android device */
void sendBackEcho(String echo)
{
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println("");
  client.println("<!DOCTYPE HTML>");
  client.println("<html>");
  client.println(echo);
  client.println("</html>");
  client.stop();
  delay(1);
}

// Blynk PushButton
BLYNK_WRITE(V1)
{ 
  if (param.asInt())
  {
    #if (PROGRAM_DEBUG)
      Serial.println("Gate Open/Close by Blynk Button");
    #endif
    
    click_relay();
  }  
}

void WebServerHandle(void)
{
  client = server.available();
  
  if (!client) 
    return;
    
  command = checkClient();
  
  Serial.println(command);
  
  if (command == "r1on" || command == "on" || command == "open" )
  {
    #if (PROGRAM_DEBUG)
      Serial.println("Gate Open");
    #endif
    
    click_relay();
    sendBackEcho(command);// send command echo back to android device
  }
  else if (command == "r1off" || command == "off" || command == "close")
  {
    #if (PROGRAM_DEBUG)
      Serial.println("Gate Close");
    #endif
    click_relay();
    sendBackEcho(command);// send command echo back to android device
  }
  
  command = "";
}

void setup()
{
  pinMode(RELAY1_PIN, OUTPUT); 
  digitalWrite(RELAY1_PIN, LOW);
  
  Serial.begin(115200);
  Serial.println("\nStarting GateController-Server");
 
  Blynk.begin("GateController-Server"); 
  server.begin();
}

void loop()
{
  Blynk.run();
  WebServerHandle();
}

You certainly have to install Blynk_WM library from Arduino IDE Library Manager.

Some improvements have been made such as :

  1. Use Ticker to eliminate using unwanted delay() in loop()
  2. Remove all unnecessary functions, etc.
  3. Remove unnecessary OnDemand HotSpot as new Blynk.run will reconnect / start config portal if necessary.
  4. Making it easier to read, easier to reconfigure by not using hardcoding if possible

You can add more and more functions later as needed.

1 Like

First of all, Thanks for the help.
Your code is great. but in my case, when internet access is not available I want to bypass/break the Blynk loop which countinously try to connect with blynk server so that I can control relay with my router wifi coonection and when after sometime internet access is available, blynk.begin retry to connect with blynk server again.
In your library when internet is not available, it opens the configuration portal for new wifi connection.

Did you actually upload the code and test? Can you provide the terminal output? How did you test to simulate the loss of Internet?

I still don’t think you you did the test correctly.
You have to simulate the loss of Internet, not the loss of WiFi + Internet.

If the Internet / Blynk is loss, the library will try to reconnect Blynk only, not trying to connect WiFi or open config portal. At this time, the Intranet is still working, and permits the access of WebServer to control the Gate.
If the WiFi (certainly the Internet / Blynk) is loss, there is no way to control using another Intranet computer to access the WebServer. (I think this is how you did the test)

I know it’s difficult and disruptive to simulate Internet loss as this will affect the operation of other devices. But you can do it briefly by

  1. Removing the phone line to DSL modem
  2. Remove the cable line to Cable Modem
    then replacing it back quickly.

In my case, I simulate the situation by using the loss of Local Blynk Server.

This is the output of the test, showing WebServer can still control the Gate when Blynk is loss and Blynk Reconnect is happenning.

Starting GateController-Server
[61] RFC925 Hostname = GateController-Server
[62] Header = ESP8266, SSID = *****, PW = ******
[62] Server = 192.168.2.112, Port = 8080, Token = *************************
[69] Board Name = GateController-Server
[72] 
    ___  __          __
   / _ )/ /_ _____  / /__
  / _  / / // / _ \/  '_/
 /____/_/\_, /_//_/_/\_\
        /___/ v0.6.1 on NodeMCU

[85] connectToWifi: start
[2090] connectToWifi: connected OK
[2090] IP: 192.168.2.114
[2090] begin: WiFi connected. Try connecting to Blynk
[2137] Ready (ping: 35ms).
[2204] begin: WiFi and Blynk connected   <===== Blynk OK
open
Gate Open
close
Gate Close
[91216] Heartbeat timeout
[91517] run: Blynk lost. Try connecting Blynk
[100517] run: Blynk lost. Try connecting Blynk    <===== Blynk loss
open                                          <===== Still can control via WebServer
Gate Open
[109524] run: Blynk lost. Try connecting Blynk
[119337] run: Blynk lost. Try connecting Blynk
close                                          <===== Still can control via WebServer
Gate Close
[129349] run: Blynk lost. Try connecting Blynk
[139347] run: Blynk lost. Try connecting Blynk
[149345] run: Blynk lost. Try connecting Blynk
[159355] run: Blynk lost. Try connecting Blynk
[169358] run: Blynk lost. Try connecting Blynk
[179361] run: Blynk lost. Try connecting Blynk
[189357] run: Blynk lost. Try connecting Blynk
[196275] Ready (ping: 31ms).                         <===== Blynk Reconnect
[196342] run: Blynk reconnected

2 Likes

Thanks for this code. This solved my problem. Sorry for late reply I’m busy in my papers so I didn’t reply you soon. I want to ask that is there any function present in this library to set the Static IP for configuration portal and Station portal like in wifi manager library? If yes, then can you send me those. Thanks again for help.

You can use the new features of v1.0.5 version of the Blynk_WM library: