WiFi Manager For Blynk Local server

Hello Blynkers !!

I thought of adding a feature like blynk.inject !! But unfortunately its only for business people !! So i as i was surfing i found WiFi Manager. Which is already used by Blynkers !! But i am thinking of using a local server and this needs additional server and port to specified along with Auth, SSID and Pass.
:point_down:

And @Toro_Blanco had posted this code

#include <FS.h>                   //this needs to be first, or it all crashes and burns...

#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino
#include <BlynkSimpleEsp8266.h>
//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager
#include <SimpleTimer.h>
#include <ArduinoJson.h>          //https://github.com/bblanchon/ArduinoJson


#define BLYNK_PRINT Serial    // Comment this out to disable prints and save space
//#define BLYNK_DEBUG


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

//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 setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println();

  //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(mqtt_server, json["mqtt_server"]);
          //strcpy(mqtt_port, json["mqtt_port"]);
          strcpy(blynk_token, json["blynk_token"]);

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



  // 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_mqtt_server("server", "mqtt server", mqtt_server, 40);
  //WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 6);
  WiFiManagerParameter custom_blynk_token("blynk", "blynk token", blynk_token, 33);

  //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);

  //set static ip
  //wifiManager.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
  
  //add all your parameters here
  //wifiManager.addParameter(&custom_mqtt_server);
  //wifiManager.addParameter(&custom_mqtt_port);
  wifiManager.addParameter(&custom_blynk_token);

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

  //set minimu quality of signal so it ignores AP's under that quality
  //defaults to 8%
  //wifiManager.setMinimumSignalQuality();
  
  //sets timeout until configuration portal gets turned off
  //useful to make it all retry or go to sleep
  //in seconds
  //wifiManager.setTimeout(120);

  //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("Wifi_Manager", "password")) {
    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(mqtt_server, custom_mqtt_server.getValue());
  //strcpy(mqtt_port, custom_mqtt_port.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["mqtt_server"] = mqtt_server;
    //json["mqtt_port"] = mqtt_port;
    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
  }

  //Serial.println("local ip");
  //Serial.println(WiFi.localIP());

  Blynk.config(blynk_token);
  bool result = Blynk.connect();

if (result != true)
{
  Serial.println("BLYNK Connection Fail");
  Serial.println(blynk_token);
  wifiManager.resetSettings();
  ESP.reset();
  delay (5000);
}
else
{
  Serial.println("BLYNK Connected");
}

}

void loop() {
 
Blynk.run();

}

i have made a few minor changes and i have got a place to put in my Local server and the port no. Everything works as it should but once i fill in the credentials it will reboot and throws error
:point_down:

*WM: AutoConnect
*WM: Connecting as wifi client...
*WM: Using last saved values, should be faster
*WM: Connection result: 
*WM: 0
*WM: SET AP
*WM: 
*WM: Configuring access point... 
*WM: Wifi_Manager
*WM: password
*WM: AP IP address: 
*WM: 192.168.4.1
*WM: HTTP server started
*WM: Request redirected to captive portal
*WM: Handle root
*WM: Scan done
*WM: ASUS
*WM: -67
*WM: Uplink
*WM: -68
*WM: Sent config page
*WM: Request redirected to captive portal
*WM: WiFi save
*WM: Parameter
*WM: server
*WM: 192.168.0.xxx
*WM: Parameter
*WM: port
*WM: 8080
*WM: Parameter
*WM: blynk
*WM: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
*WM: Sent wifi save page
*WM: Connecting to new AP
*WM: Connecting as wifi client...
*WM: Connection result: 
*WM: 3
Should save config
connected...yeey :)
saving config
{"server":"192.168.0.xxx","port":"8080","auth":"xxxxxxxxxxxxxxxxxxxxx"}BLYNK Connection Fail
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
*WM: settings invalidated
*WM: THIS MAY CAUSE AP NOT TO START UP PROPERLY. YOU NEED TO COMMENT IT OUT AFTER ERASING THE DATA.
⸮
 ets Jan  8 2013,rst cause:2, boot mode:(1,7)


 ets Jan  8 2013,rst cause:4, boot mode:(1,7)

wdt reset
{d

and cycles over !

This is the modified code :point_down:

#include <FS.h>                   

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


#define BLYNK_PRINT Serial    
//#define BLYNK_DEBUG



char server[15];
char port[6] = "8080";
char auth[34];


bool shouldSaveConfig = false;


void saveConfigCallback () {
  Serial.println("Should save config");
  shouldSaveConfig = true;
}


void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println();

  //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(port, json["port"]);
          strcpy(auth, json["auth"]);

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



  // 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, 15);
  WiFiManagerParameter custom_port("port", "port", port, 6);
  WiFiManagerParameter custom_auth("blynk", "blynk token", auth, 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);

  //set static ip
  //wifiManager.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
  
  //add all your parameters here
  wifiManager.addParameter(&custom_server);
  wifiManager.addParameter(&custom_port);
  wifiManager.addParameter(&custom_auth);

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

  //set minimu quality of signal so it ignores AP's under that quality
  //defaults to 8%
  //wifiManager.setMinimumSignalQuality();
  
  //sets timeout until configuration portal gets turned off
  //useful to make it all retry or go to sleep
  //in seconds
  //wifiManager.setTimeout(120);

  //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("Wifi_Manager", "password")) {
    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(port, custom_port.getValue());
  strcpy(auth, custom_auth.getValue());

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

    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
  }

  //Serial.println("local ip");
  //Serial.println(WiFi.localIP());

  Blynk.config(auth, server);
  bool result = Blynk.connect();

if (result != true)
{
  Serial.println("BLYNK Connection Fail");
  Serial.println(auth);
  wifiManager.resetSettings();
  ESP.reset();
  delay (5000);
}
else
{
  Serial.println("BLYNK Connected");
}
//WiFi.mode(WIFI_STA);
}

void loop() {
 
Blynk.run();

}

Everything works as it should !! It even connects to my Wifi router ! But then it hangs ! It doesn’t connect to my local server ! Where am i going wrong ? Can someone point out my mistake ??

I dont use a local server so my help is limited.

Maybe Blynk.config(auth, server); should be Blynk.config(auth, server, port);

Yes !! Already tried that out !! But still the same issue !!

are you sure the correct port is 8080? (again I dont have any experience with local server)

Have you set up the correct port forwarding on your router?

maybe try connecting without the WiFi Manager code first to make sure it connects.

This line needs to be commented out otherwise it re-formats your SPIFFS each time the ESP restarts.

Pete.

here is the error if Blynk.config(auth, server, port); is used

invalid conversion from 'char*' to 'uint16_t {aka short unsigned int}' [-fpermissive]

This is the serial monitor output

mounting FS...
mounted file system
reading config file
opened config file
{"server":"192.168.0.xxx","port":"8080","auth":"xxxxxxxxxxxxxxx"}
parsed json
*WM: Adding parameter
*WM: server
*WM: Adding parameter
*WM: port
*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: 0
*WM: SET AP
*WM: 
*WM: Configuring access point... 
*WM: Wifi_Manager
*WM: password
*WM: AP IP address: 
*WM: 192.168.4.1
*WM: HTTP server started

Seems to be putting in the credentials. But still no connection between local server and the module !!

No !! I have not setup any port forwarding !!

Yes it does connect !! Works good with only ssid and pass !!

Is the auth code that is being displayed in your serial monitor EXACTLY the same as what you’re entering in the captive portal?
It’s not being truncated at all?

Pete.

Yes i have replaced the auth with “xxxxxxxx”
In the serial monitor the auth token is displayed correctly !!

mounting FS...
mounted file system
reading config file
opened config file
{"server":"192.168.0.103","port":"8080","auth":"53a4dea60299432cb0a8f64c7xxxxxx"}
parsed json
*WM: Adding parameter
*WM: server
*WM: Adding parameter
*WM: port
*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: 0
*WM: SET AP
*WM: 
*WM: Configuring access point... 
*WM: Wifi_Manager
*WM: password
*WM: AP IP address: 
*WM: 192.168.4.1
*WM: HTTP server started
*WM: Request redirected to captive portal

Doesn’t make any difference as i am on local server !! But still i replaced with “xxxxxx”

are you sure this is to your local server, and not the BLYNK cloud server?

did you change the settings in the APP for using a local server?

From my understanding, you always have to specify the ip and port when connecting to a local server.

Yes i am 100% sure that i am on my local server…

Yes ! If not i cant even login to my local server and get the auth token generated !!

Yes this is what i am trying to achieve using the example code you had posted earlier ! I have make few minor changes and i have a place in the web page to enter in the Blynk auth token , SSID and PASS…and also the local server and port !! But as port is always 8080 i have specified it in the earlier stage !!

But the example code what you have provided was also uploaded and it shows that auth token is invalid !! As i dint give it an valid Blynk cloud generated auth !! So i can see Blynk as started by seeing this !!

[3250] 
    ___  __          __
   / _ )/ /_ _____  / /__
  / _  / / // / _ \/  '_/
 /____/_/\_, /_//_/_/\_\
        /___/ v0.6.0 on NodeMCU

But now after modifying the code this doesn’t appear as i have pasted my serial monitor output above !! So i feel that the Blynk is not even started Blynk.config is not initiated i guess !!

What version of the ESP core are you using?

Pete.

ESP8266 core 2.4.1 .
The latest 2.5.0 , 2.5.1, 2.5.2 are very buggy !! the connection is not stable !! It doesnt even connect with the wifi router !!

Here is the original code with the server and port. this is what i modified for the one i had posted.

#include <FS.h>                   //this needs to be first, or it all crashes and burns...

#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino
#include <BlynkSimpleEsp8266.h>
//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager
#include <SimpleTimer.h>
#include <ArduinoJson.h>          //https://github.com/bblanchon/ArduinoJson


#define BLYNK_PRINT Serial    // Comment this out to disable prints and save space
//#define BLYNK_DEBUG


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

//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 setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println();

  //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(mqtt_server, json["mqtt_server"]);
          strcpy(mqtt_port, json["mqtt_port"]);
          strcpy(blynk_token, json["blynk_token"]);

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



  // 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_mqtt_server("server", "mqtt server", mqtt_server, 40);
  WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 6);
  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);

  //set static ip
  //wifiManager.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
  
  //add all your parameters here
  wifiManager.addParameter(&custom_mqtt_server);
  wifiManager.addParameter(&custom_mqtt_port);
  wifiManager.addParameter(&custom_blynk_token);

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

  //set minimu quality of signal so it ignores AP's under that quality
  //defaults to 8%
  //wifiManager.setMinimumSignalQuality();
  
  //sets timeout until configuration portal gets turned off
  //useful to make it all retry or go to sleep
  //in seconds
  //wifiManager.setTimeout(120);

  //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("Wifi_Manager", "password")) {
    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(mqtt_server, custom_mqtt_server.getValue());
  strcpy(mqtt_port, custom_mqtt_port.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["mqtt_server"] = mqtt_server;
    json["mqtt_port"] = mqtt_port;
    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
  }

  //Serial.println("local ip");
  //Serial.println(WiFi.localIP());

  Blynk.config(blynk_token, mqtt_server, mqtt_port);
  bool result = Blynk.connect();

if (result != true)
{
  Serial.println("BLYNK Connection Fail");
  Serial.print("blynk_token:   ");
  Serial.println(blynk_token);
  Serial.print("mqtt_server:   ");
  Serial.println(mqtt_server);
  Serial.print("mqtt_port:   ");
  Serial.println(mqtt_port);
  wifiManager.resetSettings();
  ESP.reset();
  delay (5000);
}
else
{
  Serial.println("BLYNK Connected");
}

}

void loop() {
 
Blynk.run();

}
sketch_jun21a:155: error: invalid conversion from 'char*' to 'uint16_t {aka short unsigned int}' [-fpermissive]

   Blynk.config(blynk_token, mqtt_server, mqtt_port);

                                                   ^

In file included from C:\Users\MADxxx~1\AppData\Local\Temp\arduino_modified_sketch_295734\sketch_jun21a.ino:4:0:

C:\Users\MaxxxxxNP\Documents\Arduino\libraries\Blynk\src/BlynkSimpleEsp8266.h:58:10: error:   initializing argument 3 of 'void BlynkWifi::config(const char*, const char*, uint16_t)' [-fpermissive]

     void config(const char* auth,

          ^

exit status 1
invalid conversion from 'char*' to 'uint16_t {aka short unsigned int}' [-fpermissive]

The code you have posted above doesn’t compile !! Is this something to do with the Wifimanager lib ?

I am not sure, I did not write the code. It was taken from the WiFi manager github.

Maybe try changing to this

char mqtt_server[40];
uint16_t mqtt_port[6] = "8080";
char blynk_token[34] = "YOUR_BLYNK_TOKEN";

Yes ! Even then it should at least compile :stuck_out_tongue_winking_eye: !!! Later we can play with it and fix the problem !!

NO LUCK LOTS OF ERRORS

cannot convert 'uint16_t* {aka short unsigned int*}' to 'char*' for argument '1' to 'char* strcpy(char*, const char*)'

Also tried uint16_t mqtt_port[6] = {8080};

Throws lots of error ! I guess it has to do something with the WiFi Manager Lib then !!

Why not just hard-code “8080” in the Blynk.config statement for now?

Pete.

1 Like