NoBlynkBlock by Costas - HELP

Hello. I am trying to add one more thing to the Costas great example of “noBlynkBlock”
Basically exactly what he did for us, with the ability to enter AP mode on request (pin)
So… i took Costas sketch and also wifi.manager (by tzapu). At this point, the sketch is doing what Costas did, and when you put pin 0 to ground you have wifiManager AP page (192.168.4.1) so you can enter new wifi/pass credentials. Everything works just perfect.

Then i was trying to move forward with Tzapu example of adding custom parameters to wifi.manager so i can also enter the token on that config page. While this works just fine in his examples of the library, i cannot make it work with the Costas code. :frowning:

Can someone please help me integrate the SPIFFS part of the tzapu wifi.manager into this code?
No matter how much i’ve tried i end up with 2 possibilities:

  1. Costas code gets messed up
  2. The token field appears on the page, i can enter my token, hit save, but my sketch will never connect to blynk server anymore although wifi stays connected.

This is the current sketch which works perfect, except that it has the token “hard coded”.
THANK YOU!


/* NoBlynkBlock.ino by Costas for https://community.blynk.cc/t/blynk-is-blocking-if-internet-is-down/16809
will recover from server or router going down   

*/
#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino
#include <ESP8266WebServer.h>
#include <DNSServer.h>
#include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager
#include <BlynkSimpleEsp8266.h>

#define TRIGGER_PIN 0

char server[] = "server";
char auth[] = "token";

BlynkTimer timer;
unsigned int myServerTimeout  =  3500;  //  3.5s server connection timeout (SCT)
unsigned int myWiFiTimeout    =  3200;  //  3.2s WiFi connection timeout   (WCT)
unsigned int functionInterval =  2000;  //  2s function call frequency   (FCF)
unsigned int blynkInterval    = 25000;  // 25.0s check server frequency    (CSF)

void setup(){
  Serial.begin(115200);
  Serial.println();
  pinMode(BUILTIN_LED, OUTPUT);
 
  if(WiFi.status() == 6){
    Serial.println("\tWiFi not connected yet.");
  }
  timer.setInterval(functionInterval, myfunction);// run some function at intervals per functionInterval
  timer.setInterval(blynkInterval, checkBlynk);   // check connection to server per blynkInterval
  timer.setInterval(500, configAP );   // check pin to enter config mode
  
  unsigned long startWiFi = millis();

  WiFiManager wifiManager;
  //wifiManager.resetSettings();  //reset settings - for testing
  wifiManager.setTimeout(600);   // 10 minutes to enter data and then Wemos resets to try again.
  
  while (WiFi.status() != WL_CONNECTED){
    delay(500);
    if(millis() > startWiFi + myWiFiTimeout){
      Serial.println("\tCheck the WiFi router. ");
      break;
    }       
  }

  Blynk.config(auth, server);
  checkBlynk();
}

void myfunction(){
  Serial.println("\tLook, no Blynk  block.");
  if(WiFi.status()== 3){
    Serial.println("\tWiFi still  connected.");
    //toggle led state
  int state = digitalRead(BUILTIN_LED);  // get the current state of GPIO2 pin
  digitalWrite(BUILTIN_LED, !state);     // set pin to the opposite state
  }
  if(Blynk.connected()){
    Blynk.virtualWrite(V3, millis() / 1000);
  }
}

void checkBlynk() {
  if (WiFi.status() == WL_CONNECTED)  
  {
    unsigned long startConnecting = millis();    
    while(!Blynk.connected()){
      Blynk.connect();  
      if(millis() > startConnecting + myServerTimeout){
        Serial.print("Unable to connect to server. ");
        break;
      }
    }
  }
  if (WiFi.status() != 3) {
    Serial.print("\tNo WiFi. ");
  } 
  Serial.printf("\tChecking again in %is.\n", blynkInterval / 1000);
  Serial.println(); 
}


void configAP() {
  // is configuration portal requested?
  if ( digitalRead(TRIGGER_PIN) == LOW ) { 
    WiFiManager wifiManager;
    if (!wifiManager.startConfigPortal("AP")) {
      Serial.println("failed to connect and hit timeout");
      delay(5000);
      //reset and try again, or maybe put it to deep sleep
      ESP.reset();
      delay(5000);
    }
  }
}
void loop(){
  timer.run();
  if (Blynk.connected()) {
  Blynk.run();
  }
}

@mugur what did you see as the first line of code in the parameter setting version of WiFi Manager?

Ignoring my NoBlynkBlock sketch, have you ever connected to Blynk via WiFi Manager with the token as a parameter?

You seem to have a lot of code missing for the parameter version.

Create a working parameter sketch, paste it here and I’ll see if I can drop my code into it.

WifiManager with BLYNK Token Input

@Costas
No, i think my english is not serving me well… the code i’ve posted it’s a clean up version. I have removed all related parts that i was not able to make it work with your sketch.

I have my sketch version of wifi manager with 4 parameters. Ssid, pass, server, port based on tzapu examples. That woks perfect as it is. But i cannot make that one to behave like your sketch, let alone make it work on demand (pin to GND) instead of starting as AP as soon as it does not find the saved wifi credentials.

I don’t want to start as AP other way than on my own request. Meaning: loosing wifi keep executing mycode. Loosing blynk keep executing mycode. Of course from time to time check both if they are back.

So, my previous posted code is your sketch “inbreed” with some “on demand” sketch of tzapu. Nothing else there. Here is the working sketch of Tzapu’s wifiManager with custom parameters. Of course this works, but does not have your sketch advantages and i have no clue how to implement “onDemand AP” as i did with your sketch. Long story short: This last sketch because uses FS for storing token/server + your sketch with ONdemand AP as it is already working

#include <FS.h>                   //this needs to be first, or it all crashes and burns...
#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino
//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager
#include <ArduinoJson.h>          //https://github.com/bblanchon/ArduinoJson
#include <BlynkSimpleEsp8266.h>
#include <SimpleTimer.h>
SimpleTimer timer;

//define your default values here, if there are different values in config.json, they are overwritten.
char server[40]="";
char blynk_token[34]="";

int UP_LED = V2; //uplink virtual pin for Blynk(led type)
long int last_UP = millis();
bool runn = 1;

//flag for saving data
bool shouldSaveConfig = false;

//callback notifying us of the need to save config
void saveConfigCallback () {
  Serial.println("Should save config");
  shouldSaveConfig = true;
}

void blink()
{
  //toggle state
  int state = digitalRead(BUILTIN_LED);  // get the current state of GPIO2 pin
  digitalWrite(BUILTIN_LED, !state);     // set pin to the opposite state
}

void blynkLed(){ // pulse led on blynk App only if blynk is connected
    Blynk.virtualWrite(UP_LED,runn * 255);
    runn = !runn;
    last_UP = millis(); 
}
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println();
  pinMode(BUILTIN_LED, OUTPUT);    //led

  timer.setInterval(1000L, blink);      // blynk uplink LED every...miliseconds 
  timer.setInterval(1000L, blynkLed);      // blynk uplink LED every...miliseconds 
  //clean FS, for testing
  //SPIFFS.format();

  //read configuration from FS json
  Serial.println("mounting FS...");

  if (SPIFFS.begin()) {
    Serial.println("mounted file system");
    if (SPIFFS.exists("/config.json")) {
      //file exists, reading and loading
      Serial.println("reading config file");
      File configFile = SPIFFS.open("/config.json", "r");
      if (configFile) {
        Serial.println("opened config file");
        size_t size = configFile.size();
        // Allocate a buffer to store contents of the file.
        std::unique_ptr<char[]> buf(new char[size]);
        configFile.readBytes(buf.get(), size);
        DynamicJsonBuffer jsonBuffer;
        JsonObject& json = jsonBuffer.parseObject(buf.get());
        json.printTo(Serial);
        if (json.success()) {
          Serial.println("\nparsed json");

          strcpy(server, json["server"]);
          strcpy(blynk_token, json["blynk_token"]);

        } else {
          Serial.println("failed to load json config");
        }
      }
    }
  } else {
    Serial.println("failed to mount FS");
  }

  // The extra parameters to be configured (can be either global or just in the setup)
  // After connecting, parameter.getValue() will get you the configured value
  // id/name placeholder/prompt default length
  WiFiManagerParameter custom_server("server", "server", server, 40);
  WiFiManagerParameter custom_blynk_token("blynk", "blynk token", blynk_token, 34);

  //WiFiManager
  //Local intialization. Once its business is done, there is no need to keep it around
  WiFiManager wifiManager;

  //set config save notify callback
  wifiManager.setSaveConfigCallback(saveConfigCallback);
 
  //custom parameters here
  wifiManager.addParameter(&custom_server);
  wifiManager.addParameter(&custom_blynk_token);

  //reset settings - for testing
  //wifiManager.resetSettings();

  //fetches ssid and pass and tries to connect
  //if it does not connect it starts an access point with the specified name
  //here  "AutoConnectAP"
  //and goes into a blocking loop awaiting configuration
  if (!wifiManager.autoConnect("AutoConnectAP")) {
    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 :)");

  //read updated parameters
  strcpy(server, custom_server.getValue());
  strcpy(blynk_token, custom_blynk_token.getValue());

  //save the custom parameters to FS
  if (shouldSaveConfig) {
    Serial.println("saving config");
    DynamicJsonBuffer jsonBuffer;
    JsonObject& json = jsonBuffer.createObject();
    json["server"] = server;
    json["blynk_token"] = blynk_token;

    File configFile = SPIFFS.open("/config.json", "w");
    if (!configFile) {
      Serial.println("failed to open config file for writing");
    }

    json.printTo(Serial);
    json.printTo(configFile);
    configFile.close();
    //end save
  }
Blynk.config(blynk_token, server);//end read
Blynk.connect();
}

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

@Costas, would you please have a look at the latest posted sketch?
What i am doing wrong?

@mugur I will try to find time to load up your sketch and add your extra requirements etc.

Thank you so much!
You are my life saver, and as i can see, not only mine.

@mugur with the latest version of everything I have a WiFi Manager sketch running and button on GPIO 0 brings up the AP to change router / parameters.

Latest WiFi Manager, Core, Android App, Blynk libraries etc.

Which elements of the NoBlynkBlock sketch do you need i.e. are you worried about router / server / both going down?

Once I have your answer I will add the required to the sketch as I have it now.

i need to work with both or any of them down (router/server)

@mugur I have sent you the code via PM. Tested it with our routers and I think it has everything you need.
Should look like this:

mounting FS...
mounted file system
reading config file
opened config file
{"server":"blynk-cloud.com","blynk_token":"01xxxxxxxxxxxxf62"}
parsed json
*WM: Adding parameter
*WM: server
*WM: Adding parameter
*WM: blynk
*WM: 
*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.10.248
Connected OK

AP configured
Connected to server
Connected to server. 	Checking again in 25s.

Connected to server. 	Checking again in 25s.

Connected to server. 	Checking again in 25s.

Connected to server. 	Checking again in 25s.

Connected to server. 	Checking again in 25s.

Connected to server. 	Checking again in 25s.

Connected to server. 	Checking again in 25s.

Connected to server. 	Checking again in 25s.

Connected to server. 	Checking again in 25s.

It should recover from server and router failure etc. Test it thoroughly and then provide your feedback.

Thank you so much! I am not at home but cannot wait to get back so i can test it!

Thanks again for your ongoing support!

1 Like

Well…i got home earlier :slight_smile:
It works perfect. Now i will put my thermostat code right where buit-in led is now.

THANK YOU!

1 Like

Hello Everybody.

About “I have sent you the code via PM”…

I just need the same sketch: I want “Noblynkblock+wifimanager (configmode onrequest)”. Please. may you show it here? Thanks in advance