add wifi manager esp32 (#414)

* add wifi manager esp32
This commit is contained in:
Florian authored and GitHub committed 2019-06-22 13:43:54 +02:00
1 parent 1a0dacaf3f
commit feb489633b
35 files changed
+4953 -1066

No files matched your search

@@ -0,0 +1,133 @@
/**
* WiFiManager advanced demo, contains advanced configurartion options
* Implements TRIGGEN_PIN button press, press for ondemand configportal, hold for 3 seconds for reset settings.
*/
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
#define TRIGGER_PIN 0
WiFiManager wm; // global wm instance
WiFiManagerParameter custom_field; // global param ( for non blocking w params )
void setup() {
Serial.begin(115200);
Serial.setDebugOutput(true);
delay(3000);
Serial.println("\n Starting");
pinMode(TRIGGER_PIN, INPUT);
// wm.resetSettings(); // wipe settings
// add a custom input field
int customFieldLength = 40;
// new (&custom_field) WiFiManagerParameter("customfieldid", "Custom Field Label", "Custom Field Value", customFieldLength,"placeholder=\"Custom Field Placeholder\"");
// test custom html input type(checkbox)
// new (&custom_field) WiFiManagerParameter("customfieldid", "Custom Field Label", "Custom Field Value", customFieldLength,"placeholder=\"Custom Field Placeholder\" type=\"checkbox\""); // custom html type
// test custom html(radio)
const char* custom_radio_str = "<br/><label for='customfieldid'>Custom Field Label</label><input type='radio' name='customfieldid' value='1' checked> One<br><input type='radio' name='customfieldid' value='2'> Two<br><input type='radio' name='customfieldid' value='3'> Three";
new (&custom_field) WiFiManagerParameter(custom_radio_str); // custom html input
wm.addParameter(&custom_field);
wm.setSaveParamsCallback(saveParamCallback);
// custom menu via array or vector
//
// menu tokens, "wifi","wifinoscan","info","param","close","sep","erase","restart","exit" (sep is seperator) (if param is in menu, params will not show up in wifi page!)
// const char* menu[] = {"wifi","info","param","sep","restart","exit"};
// wm.setMenu(menu,6);
std::vector<const char *> menu = {"wifi","info","param","sep","restart","exit"};
wm.setMenu(menu);
// set dark theme
wm.setClass("invert");
//set static ip
// wm.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); // set static ip,gw,sn
// wm.setShowStaticFields(true); // force show static ip fields
// wm.setShowDnsFields(true); // force show dns field always
// wm.setConnectTimeout(20); // how long to try to connect for before continuing
wm.setConfigPortalTimeout(30); // auto close configportal after n seconds
// wm.setCaptivePortalEnable(false); // disable captive portal redirection
// wm.setAPClientCheck(true); // avoid timeout if client connected to softap
// wifi scan settings
// wm.setRemoveDuplicateAPs(false); // do not remove duplicate ap names (true)
// wm.setMinimumSignalQuality(20); // set min RSSI (percentage) to show in scans, null = 8%
// wm.setShowInfoErase(false); // do not show erase button on info page
// wm.setScanDispPerc(true); // show RSSI as percentage not graph icons
// wm.setBreakAfterConfig(true); // always exit configportal even if wifi save fails
bool res;
// res = wm.autoConnect(); // auto generated AP name from chipid
// res = wm.autoConnect("AutoConnectAP"); // anonymous ap
res = wm.autoConnect("AutoConnectAP","password"); // password protected ap
if(!res) {
Serial.println("Failed to connect or hit timeout");
// ESP.restart();
}
else {
//if you get here you have connected to the WiFi
Serial.println("connected...yeey :)");
}
}
void checkButton(){
// check for button press
if ( digitalRead(TRIGGER_PIN) == LOW ) {
// poor mans debounce/press-hold, code not ideal for production
delay(50);
if( digitalRead(TRIGGER_PIN) == LOW ){
Serial.println("Button Pressed");
// still holding button for 3000 ms, reset settings, code not ideaa for production
delay(3000); // reset delay hold
if( digitalRead(TRIGGER_PIN) == LOW ){
Serial.println("Button Held");
Serial.println("Erasing Config, restarting");
wm.resetSettings();
ESP.restart();
}
// start portal w delay
Serial.println("Starting config portal");
wm.setConfigPortalTimeout(120);
if (!wm.startConfigPortal("OnDemandAP","password")) {
Serial.println("failed to connect or hit timeout");
delay(3000);
// ESP.restart();
} else {
//if you get here you have connected to the WiFi
Serial.println("connected...yeey :)");
}
}
}
}
String getParam(String name){
//read parameter from server, for customhmtl input
String value;
if(wm.server->hasArg(name)) {
value = wm.server->arg(name);
}
return value;
}
void saveParamCallback(){
Serial.println("[CALLBACK] saveParamCallback fired");
Serial.println("PARAM customfieldid = " + getParam("customfieldid"));
}
void loop() {
checkButton();
// put your main code here, to run repeatedly:
}
@@ -1,38 +0,0 @@
#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
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
//WiFiManager
//Local intialization. Once its business is done, there is no need to keep it around
WiFiManager wifiManager;
//reset saved settings
//wifiManager.resetSettings();
//set custom ip for portal
//wifiManager.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
//fetches ssid and pass from eeprom 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
wifiManager.autoConnect("AutoConnectAP");
//or use this for auto generated name ESP + ChipID
//wifiManager.autoConnect();
//if you get here you have connected to the WiFi
Serial.println("connected...yeey :)");
}
void loop() {
// put your main code here, to run repeatedly:
}
@@ -1,18 +1,20 @@
#include <FS.h> //this needs to be first, or it all crashes and burns...
#include <FS.h> // this needs to be first, or it all crashes and burns...
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
#include <ArduinoJson.h> // https://github.com/bblanchon/ArduinoJson
#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
#ifdef ESP32
#include <SPIFFS.h>
#endif
//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";
char mqtt_port[6] = "8080";
char api_token[32] = "YOUR_API_TOKEN";
//default custom static IP
char static_ip[16] = "10.0.1.56";
char static_gw[16] = "10.0.1.1";
char static_sn[16] = "255.255.255.0";
//flag for saving data
bool shouldSaveConfig = false;
@@ -23,14 +25,9 @@ void saveConfigCallback () {
shouldSaveConfig = true;
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println();
void setupSpiffs(){
//clean FS, for testing
//SPIFFS.format();
// SPIFFS.format();
//read configuration from FS json
Serial.println("mounting FS...");
@@ -56,74 +53,89 @@ void setup() {
strcpy(mqtt_server, json["mqtt_server"]);
strcpy(mqtt_port, json["mqtt_port"]);
strcpy(blynk_token, json["blynk_token"]);
strcpy(api_token, json["api_token"]);
// if(json["ip"]) {
// Serial.println("setting custom ip from config");
// strcpy(static_ip, json["ip"]);
// strcpy(static_gw, json["gateway"]);
// strcpy(static_sn, json["subnet"]);
// Serial.println(static_ip);
// } else {
// Serial.println("no custom ip in config");
// }
} else {
Serial.println("failed to load json config");
}
configFile.close();
}
}
} else {
Serial.println("failed to mount FS");
}
//end read
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println();
setupSpiffs();
// WiFiManager, Local intialization. Once its business is done, there is no need to keep it around
WiFiManager wm;
//set config save notify callback
wm.setSaveConfigCallback(saveConfigCallback);
// setup custom parameters
//
// 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, 32);
WiFiManagerParameter custom_api_token("api", "api token", "", 32);
//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);
wm.addParameter(&custom_mqtt_server);
wm.addParameter(&custom_mqtt_port);
wm.addParameter(&custom_api_token);
//reset settings - for testing
//wifiManager.resetSettings();
// set static ip
// IPAddress _ip,_gw,_sn;
// _ip.fromString(static_ip);
// _gw.fromString(static_gw);
// _sn.fromString(static_sn);
// wm.setSTAStaticIPConfig(_ip, _gw, _sn);
//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);
//reset settings - wipe credentials for testing
//wm.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"
//automatically connect using saved credentials if they exist
//If connection fails it starts an access point with the specified name
//here "AutoConnectAP" if empty will auto generate basedcon chipid, if password is blank it will be anonymous
//and goes into a blocking loop awaiting configuration
if (!wifiManager.autoConnect("AutoConnectAP", "password")) {
if (!wm.autoConnect("AutoConnectAP", "password")) {
Serial.println("failed to connect and hit timeout");
delay(3000);
//reset and try again, or maybe put it to deep sleep
ESP.reset();
// if we still have not connected restart and try all over again
ESP.restart();
delay(5000);
}
// always start configportal for a little while
// wm.setConfigPortalTimeout(60);
// wm.startConfigPortal("AutoConnectAP","password");
//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());
strcpy(api_token, custom_api_token.getValue());
//save the custom parameters to FS
if (shouldSaveConfig) {
@@ -131,23 +143,29 @@ void setup() {
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.createObject();
json["mqtt_server"] = mqtt_server;
json["mqtt_port"] = mqtt_port;
json["blynk_token"] = blynk_token;
json["mqtt_port"] = mqtt_port;
json["api_token"] = api_token;
// json["ip"] = WiFi.localIP().toString();
// json["gateway"] = WiFi.gatewayIP().toString();
// json["subnet"] = WiFi.subnetMask().toString();
File configFile = SPIFFS.open("/config.json", "w");
if (!configFile) {
Serial.println("failed to open config file for writing");
}
json.printTo(Serial);
json.prettyPrintTo(Serial);
json.printTo(configFile);
configFile.close();
//end save
shouldSaveConfig = false;
}
Serial.println("local ip");
Serial.println(WiFi.localIP());
Serial.println(WiFi.gatewayIP());
Serial.println(WiFi.subnetMask());
}
void loop() {
@@ -1,19 +1,16 @@
#include <FS.h> //this needs to be first, or it all crashes and burns...
#include <FS.h> // this needs to be first, or it all crashes and burns...
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
#include <ArduinoJson.h> // https://github.com/bblanchon/ArduinoJson
#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
#ifdef ESP32
#include <SPIFFS.h>
#endif
//define your default values here, if there are different values in config.json, they are overwritten.
//length should be max size + 1
char mqtt_server[40];
char mqtt_port[6] = "8080";
char blynk_token[33] = "YOUR_BLYNK_TOKEN";
char mqtt_port[6] = "8080";
char api_token[32] = "YOUR_API_TOKEN";
//default custom static IP
char static_ip[16] = "10.0.1.56";
char static_gw[16] = "10.0.1.1";
@@ -28,13 +25,9 @@ void saveConfigCallback () {
shouldSaveConfig = true;
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println();
void setupSpiffs(){
//clean FS, for testing
//SPIFFS.format();
// SPIFFS.format();
//read configuration from FS json
Serial.println("mounting FS...");
@@ -60,24 +53,18 @@ void setup() {
strcpy(mqtt_server, json["mqtt_server"]);
strcpy(mqtt_port, json["mqtt_port"]);
strcpy(blynk_token, json["blynk_token"]);
strcpy(api_token, json["api_token"]);
if(json["ip"]) {
Serial.println("setting custom ip from config");
//static_ip = json["ip"];
strcpy(static_ip, json["ip"]);
strcpy(static_gw, json["gateway"]);
strcpy(static_sn, json["subnet"]);
//strcat(static_ip, json["ip"]);
//static_gw = json["gateway"];
//static_sn = json["subnet"];
Serial.println(static_ip);
/* Serial.println("converting ip");
IPAddress ip = ipFromCharArray(static_ip);
Serial.println(ip);*/
} else {
Serial.println("no custom ip in config");
}
} else {
Serial.println("failed to load json config");
}
@@ -87,59 +74,54 @@ void setup() {
Serial.println("failed to mount FS");
}
//end read
Serial.println(static_ip);
Serial.println(blynk_token);
Serial.println(mqtt_server);
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println();
setupSpiffs();
// WiFiManager, Local intialization. Once its business is done, there is no need to keep it around
WiFiManager wm;
//set config save notify callback
wm.setSaveConfigCallback(saveConfigCallback);
// setup custom parameters
//
// 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, 5);
WiFiManagerParameter custom_blynk_token("blynk", "blynk token", blynk_token, 34);
WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 6);
WiFiManagerParameter custom_api_token("api", "api token", "", 32);
//WiFiManager
//Local intialization. Once its business is done, there is no need to keep it around
WiFiManager wifiManager;
//add all your parameters here
wm.addParameter(&custom_mqtt_server);
wm.addParameter(&custom_mqtt_port);
wm.addParameter(&custom_api_token);
//set config save notify callback
wifiManager.setSaveConfigCallback(saveConfigCallback);
//set static ip
// set static ip
IPAddress _ip,_gw,_sn;
_ip.fromString(static_ip);
_gw.fromString(static_gw);
_sn.fromString(static_sn);
wm.setSTAStaticIPConfig(_ip, _gw, _sn);
wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn);
//add all your parameters here
wifiManager.addParameter(&custom_mqtt_server);
wifiManager.addParameter(&custom_mqtt_port);
wifiManager.addParameter(&custom_blynk_token);
//reset settings - wipe credentials for testing
//wm.resetSettings();
//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"
//automatically connect using saved credentials if they exist
//If connection fails it starts an access point with the specified name
//here "AutoConnectAP" if empty will auto generate basedcon chipid, if password is blank it will be anonymous
//and goes into a blocking loop awaiting configuration
if (!wifiManager.autoConnect("AutoConnectAP", "password")) {
if (!wm.autoConnect("AutoConnectAP", "password")) {
Serial.println("failed to connect and hit timeout");
delay(3000);
//reset and try again, or maybe put it to deep sleep
ESP.reset();
// if we still have not connected restart and try all over again
ESP.restart();
delay(5000);
}
@@ -149,7 +131,7 @@ void setup() {
//read updated parameters
strcpy(mqtt_server, custom_mqtt_server.getValue());
strcpy(mqtt_port, custom_mqtt_port.getValue());
strcpy(blynk_token, custom_blynk_token.getValue());
strcpy(api_token, custom_api_token.getValue());
//save the custom parameters to FS
if (shouldSaveConfig) {
@@ -157,12 +139,12 @@ void setup() {
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.createObject();
json["mqtt_server"] = mqtt_server;
json["mqtt_port"] = mqtt_port;
json["blynk_token"] = blynk_token;
json["mqtt_port"] = mqtt_port;
json["api_token"] = api_token;
json["ip"] = WiFi.localIP().toString();
json["gateway"] = WiFi.gatewayIP().toString();
json["subnet"] = WiFi.subnetMask().toString();
json["ip"] = WiFi.localIP().toString();
json["gateway"] = WiFi.gatewayIP().toString();
json["subnet"] = WiFi.subnetMask().toString();
File configFile = SPIFFS.open("/config.json", "w");
if (!configFile) {
@@ -173,6 +155,7 @@ void setup() {
json.printTo(configFile);
configFile.close();
//end save
shouldSaveConfig = false;
}
Serial.println("local ip");
@@ -1,19 +1,16 @@
#include <ESP8266WiFi.h> //https://github.com/esp8266/Arduino
// LED will blink when in config mode
//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
//for LED status
#include <Ticker.h>
Ticker ticker;
int LED = BUILTIN_LED;
void tick()
{
//toggle state
int state = digitalRead(BUILTIN_LED); // get the current state of GPIO1 pin
digitalWrite(BUILTIN_LED, !state); // set pin to the opposite state
digitalWrite(LED, !digitalRead(LED)); // set pin to the opposite state
}
//gets called when WiFiManager enters configuration mode
@@ -31,27 +28,27 @@ void setup() {
Serial.begin(115200);
//set led pin as output
pinMode(BUILTIN_LED, OUTPUT);
pinMode(LED, OUTPUT);
// start ticker with 0.5 because we start in AP mode and try to connect
ticker.attach(0.6, tick);
//WiFiManager
//Local intialization. Once its business is done, there is no need to keep it around
WiFiManager wifiManager;
WiFiManager wm;
//reset settings - for testing
//wifiManager.resetSettings();
// wm.resetSettings();
//set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode
wifiManager.setAPCallback(configModeCallback);
wm.setAPCallback(configModeCallback);
//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()) {
if (!wm.autoConnect()) {
Serial.println("failed to connect and hit timeout");
//reset and try again, or maybe put it to deep sleep
ESP.reset();
ESP.restart();
delay(1000);
}
@@ -59,7 +56,7 @@ void setup() {
Serial.println("connected...yeey :)");
ticker.detach();
//keep LED on
digitalWrite(BUILTIN_LED, LOW);
digitalWrite(LED, LOW);
}
void loop() {
+39
View File
@@ -0,0 +1,39 @@
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
// WiFi.mode(WiFi_STA); // it is a good practice to make sure your code sets wifi mode how you want it.
//WiFiManager, Local intialization. Once its business is done, there is no need to keep it around
WiFiManager wm;
//reset settings - wipe credentials for testing
//wm.resetSettings();
// Automatically connect using saved credentials,
// if connection fails, it starts an access point with the specified name ( "AutoConnectAP"),
// if empty will auto generate SSID, if password is blank it will be anonymous AP (wm.autoConnect())
// then goes into a blocking loop awaiting configuration and will return success result
bool res;
// res = wm.autoConnect(); // auto generated AP name from chipid
// res = wm.autoConnect("AutoConnectAP"); // anonymous ap
res = wm.autoConnect("AutoConnectAP","password"); // password protected ap
if(!res) {
Serial.println("Failed to connect");
// ESP.restart();
}
else {
//if you get here you have connected to the WiFi
Serial.println("connected...yeey :)");
}
}
void loop() {
// put your main code here, to run repeatedly:
}
@@ -0,0 +1,265 @@
/**
* This is a kind of unit test for DEV for now
*/
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
#include <time.h>
#define TRIGGER_PIN 0
const char* modes[] = { "NULL", "STA", "AP", "STA+AP" };
// // #define MYOLED
// #include <Wire.h>
// #include <Adafruit_GFX.h>
// #include <Adafruit_SSD1306.h>
// #ifdef MYOLED
// #define SCREEN_WIDTH 128 // OLED display width, in pixels
// #define SCREEN_HEIGHT 32 // OLED display height, in pixels
// // Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
// #define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
// Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
// void init_oled(){
// Wire.begin(SCL,SDA); // begin(sda, scl) SWAP!
// // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
// if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x32
// Serial.println(F("SSD1306 allocation failed"));
// }
// display.clearDisplay();
// display.setTextSize(1); // Normal 1:1 pixepl scale
// display.setTextColor(WHITE); // Draw white text
// display.setCursor(0,0); // Start at top-left corner
// display.display();
// }
// void print_oled(String str,uint8_t size){
// display.clearDisplay();
// display.setTextSize(size);
// display.setTextColor(WHITE);
// display.setCursor(0,0);
// display.println(str);
// display.display();
// }
// #else
// void print_oled(String str,uint8_t size){
// (void)str;
// (void)size;
// }
// #endif
void print_oled(String str,uint8_t size){
(void)str;
(void)size;
}
WiFiManager wm;
bool TEST_CP = false; // always start the configportal
bool TEST_NET = true; // do a network test, get ntp time
char ssid[] = "*************"; // your network SSID (name)
char pass[] = "********"; // your network password
void saveWifiCallback(){
Serial.println("[CALLBACK] saveCallback fired");
}
//gets called when WiFiManager enters configuration mode
void configModeCallback (WiFiManager *myWiFiManager) {
Serial.println("[CALLBACK] configModeCallback fired");
print_oled("WiFiManager Waiting\nIP: " + WiFi.softAPIP().toString() + "\nSSID: " + WiFi.softAPSSID(),1);
// myWiFiManager->setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
// Serial.println(WiFi.softAPIP());
//if you used auto generated SSID, print it
// Serial.println(myWiFiManager->getConfigPortalSSID());
}
void saveParamCallback(){
Serial.println("[CALLBACK] saveParamCallback fired");
// wm.stopConfigPortal();
}
void bindServerCallback(){
wm.server->on("/custom",handleRoute);
// wm.server->on("/info",handleRoute); // can override wm!
}
void handleRoute(){
Serial.println("[HTTP] handle route");
wm.server->send(200, "text/plain", "hello from user code");
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
// Serial.setDebugOutput(true);
// delay(3000);
Serial.println("\n Starting");
// WiFi.setSleepMode(WIFI_NONE_SLEEP); // disable sleep, can improve ap stability
#ifdef OLED
init_oled();
#endif
print_oled(F("Starting..."),2);
wm.debugPlatformInfo();
//Local intialization. Once its business is done, there is no need to keep it around
//reset settings - for testing
// wm.resetSettings();
// wm.erase();
wm.setClass("invert");
//sets timeout until configuration portal gets turned off
//useful to make it all retry or go to sleep
//in seconds
// wm.setConfigPortalTimeout(600);
// wm.setConnectTimeout(5);
// wm.setShowStaticFields(true);
WiFiManagerParameter custom_html("<p>This Is Custom HTML</p>"); // only custom html
WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "", 40);
WiFiManagerParameter custom_mqtt_port("port", "mqtt port", "", 6);
WiFiManagerParameter custom_token("api_token", "api token", "", 16);
WiFiManagerParameter custom_tokenb("invalid token", "invalid token", "", 0); // id is invalid, cannot contain spaces
WiFiManagerParameter custom_ipaddress("input_ip", "input IP", "", 15,"pattern='\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}'"); // custom input attrs (ip mask)
// callbacks
wm.setAPCallback(configModeCallback);
wm.setWebServerCallback(bindServerCallback);
wm.setSaveConfigCallback(saveWifiCallback);
wm.setSaveParamsCallback(saveParamCallback);
//add all your parameters here
wm.addParameter(&custom_html);
wm.addParameter(&custom_mqtt_server);
wm.addParameter(&custom_mqtt_port);
wm.addParameter(&custom_token);
wm.addParameter(&custom_tokenb);
wm.addParameter(&custom_ipaddress);
custom_html.setValue("test",4);
custom_token.setValue("test",4);
// Set cutom menu via menu[] or vector
// const char* menu[] = {"wifi","wifinoscan","info","param","close","sep","erase","restart","exit"};
// wm.setMenu(menu,9); // custom menu array must provide length
std::vector<const char *> menu = {"wifi","wifinoscan","info","param","close","sep","erase","restart","exit"};
wm.setMenu(menu); // custom menu, pass vector
// set static sta ip
// wm.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
// wm.setShowStaticFields(false);
// wm.setShowDnsFields(false);
// set static ip
// wm.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
// wm.setAPStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
// WiFi.mode(WIFI_STA);
// const wifi_country_t COUNTRY_US{"US",1,11,WIFI_COUNTRY_POLICY_AUTO};
// const wifi_country_t COUNTRY_CN{"CN",1,13,WIFI_COUNTRY_POLICY_AUTO};
// const wifi_country_t COUNTRY_JP{"JP",1,14,WIFI_COUNTRY_POLICY_AUTO};
// esp_wifi_set_country(&COUNTRY_US);
// wm.setCountry("US");
wm.setConfigPortalTimeout(120);
// wm.startConfigPortal("AutoConnectAP", "password");
//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
print_oled(F("Connecting..."),2);
if(!wm.autoConnect("AutoConnectAP")) {
Serial.println("failed to connect and hit timeout");
print_oled("Not Connected",2);
}
else if(TEST_CP) {
// start configportal always
wm.setConfigPortalTimeout(60);
wm.startConfigPortal();
}
else {
//if you get here you have connected to the WiFi
Serial.println("connected...yeey :)");
print_oled("Connected\nIP: " + WiFi.localIP().toString() + "\nSSID: " + WiFi.SSID(),1);
}
pinMode(TRIGGER_PIN, INPUT);
}
void loop() {
// is configuration portal requested?
if ( digitalRead(TRIGGER_PIN) == LOW ) {
Serial.println("BUTTON PRESSED");
wm.setConfigPortalTimeout(120);
// disable captive portal redirection
// wm.setCaptivePortalEnable(false);
if (!wm.startConfigPortal("OnDemandAP")) {
Serial.println("failed to connect and hit timeout");
delay(3000);
} else {
//if you get here you have connected to the WiFi
Serial.println("connected...yeey :)");
print_oled("Connected\nIP: " + WiFi.localIP().toString() + "\nSSID: " + WiFi.SSID(),1);
getTime();
}
}
if(WiFi.status() == WL_CONNECTED) getTime();
// put your main code here, to run repeatedly:
delay(5000);
}
void getTime() {
int tz = -5;
int dst = 0;
time_t now = time(nullptr);
unsigned timeout = 5000;
unsigned start = millis();
configTime(tz * 3600, dst * 3600, "pool.ntp.org", "time.nist.gov");
Serial.print("Waiting for NTP time sync: ");
while (now < 8 * 3600 * 2 ) {
delay(100);
Serial.print(".");
now = time(nullptr);
if((millis() - start) > timeout){
Serial.println("[ERROR] Failed to get NTP time.");
return;
}
}
Serial.println("");
struct tm timeinfo;
gmtime_r(&now, &timeinfo);
Serial.print("Current time: ");
Serial.print(asctime(&timeinfo));
}
void debugchipid(){
// WiFi.mode(WIFI_STA);
// WiFi.printDiag(Serial);
// Serial.println(modes[WiFi.getMode()]);
// ESP.eraseConfig();
// wm.resetSettings();
// wm.erase(true);
WiFi.mode(WIFI_AP);
// WiFi.softAP();
WiFi.enableAP(true);
delay(500);
// esp_wifi_start();
delay(1000);
WiFi.printDiag(Serial);
delay(60000);
ESP.restart();
// AP esp_267751
// 507726A4AE30
// ESP32 Chip ID = 507726A4AE30
}
@@ -0,0 +1,26 @@
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
WiFiManager wm;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
//reset settings - wipe credentials for testing
//wm.resetSettings();
wm.setConfigPortalBlocking(false);
//automatically connect using saved credentials if they exist
//If connection fails it starts an access point with the specified name
if(wm.autoConnect("AutoConnectAP")){
Serial.println("connected...yeey :)");
}
else {
Serial.println("Configportal running");
}
}
void loop() {
wm.process();
// put your main code here, to run repeatedly:
}
@@ -0,0 +1,35 @@
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
WiFiManager wm;
WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "", 40);
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
//reset settings - wipe credentials for testing
//wm.resetSettings();
wm.addParameter(&custom_mqtt_server);
wm.setConfigPortalBlocking(false);
wm.setSaveParamsCallback(saveParamsCallback);
//automatically connect using saved credentials if they exist
//If connection fails it starts an access point with the specified name
if(wm.autoConnect("AutoConnectAP")){
Serial.println("connected...yeey :)");
}
else {
Serial.println("Configportal running");
}
}
void loop() {
wm.process();
// put your main code here, to run repeatedly:
}
void saveParamsCallback () {
Serial.println("Get Params:");
Serial.print(custom_mqtt_server.getID());
Serial.print(" : ");
Serial.println(custom_mqtt_server.getValue());
}
@@ -0,0 +1,63 @@
/**
* OnDemandNonBlocking.ino
* example of running the webportal or configportal manually and non blocking
* trigger pin will start a webportal for 120 seconds then turn it off.
* startCP = true will start both the configportal AP and webportal
*/
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
// select which pin will trigger the configuration portal when set to LOW
#define TRIGGER_PIN 0
WiFiManager wm;
unsigned int timeout = 120; // seconds to run for
unsigned int startTime = millis();
bool portalRunning = false;
bool startAP = false; // start AP and webserver if true, else start only webserver
void setup() {
// put your setup code here, to run once
Serial.begin(115200);
Serial.println("\n Starting");
pinMode(TRIGGER_PIN, INPUT_PULLUP);
}
void loop() {
doWiFiManager();
// put your main code here, to run repeatedly:
}
void doWiFiManager(){
// is auto timeout portal running
if(portalRunning){
wm.process();
if((millis()-startTime) > (timeout*1000)){
Serial.println("portaltimeout");
portalRunning = false;
if(startAP){
wm.stopConfigPortal();
}
else{
wm.stopWebPortal();
}
}
}
// is configuration portal requested?
if(digitalRead(TRIGGER_PIN) == LOW && (!portalRunning)) {
if(startAP){
Serial.println("Button Pressed, Starting Config Portal");
wm.setConfigPortalBlocking(false);
wm.startConfigPortal();
}
else{
Serial.println("Button Pressed, Starting Web Portal");
wm.startWebPortal();
}
portalRunning = true;
startTime = millis();
}
}
@@ -1,9 +1,4 @@
#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 <WiFiManager.h> // https://github.com/tzapu/WiFiManager
void configModeCallback (WiFiManager *myWiFiManager) {
Serial.println("Entered config mode");
@@ -32,7 +27,7 @@ void setup() {
if(!wifiManager.autoConnect()) {
Serial.println("failed to connect and hit timeout");
//reset and try again, or maybe put it to deep sleep
ESP.reset();
ESP.restart();
delay(1000);
}
@@ -1,11 +1,5 @@
#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 <FS.h> // this needs to be first, or it all crashes and burns...
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
void setup() {
// put your setup code here, to run once:
@@ -30,7 +24,7 @@ void setup() {
if (!wifiManager.autoConnect("AutoConnectAP", "password")) {
Serial.println("failed to connect, we should reset as see if it connects");
delay(3000);
ESP.reset();
ESP.restart();
delay(5000);
}
@@ -1,12 +1,5 @@
#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 <FS.h> // this needs to be first, or it all crashes and burns...
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
/**************************************************************************************
* this example shows how to set a static IP configuration for the ESP
@@ -15,9 +8,7 @@
* if you want the ability to configure and persist the new IP configuration
* look at the FS examples, which save the config to file
*************************************************************************************/
//default custom static IP
//char static_ip[16] = "10.0.1.59";
//char static_gw[16] = "10.0.1.1";
@@ -61,7 +52,7 @@ void setup() {
if (!wifiManager.autoConnect("AutoConnectAP", "password")) {
Serial.println("failed to connect, we should reset as see if it connects");
delay(3000);
ESP.reset();
ESP.restart();
delay(5000);
}
@@ -1,11 +1,4 @@
#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 <WiFiManager.h> // https://github.com/tzapu/WiFiManager
void setup() {
// put your setup code here, to run once:
@@ -20,7 +13,7 @@ void setup() {
//sets timeout until configuration portal gets turned off
//useful to make it all retry or go to sleep
//in seconds
wifiManager.setTimeout(180);
wifiManager.setConfigPortalTimeout(180);
//fetches ssid and pass and tries to connect
//if it does not connect it starts an access point with the specified name
@@ -30,7 +23,7 @@ void setup() {
Serial.println("failed to connect and hit timeout");
delay(3000);
//reset and try again, or maybe put it to deep sleep
ESP.reset();
ESP.restart();
delay(5000);
}
@@ -0,0 +1,46 @@
/**
* OnDemandConfigPortal.ino
* example of running the configPortal AP manually, independantly from the captiveportal
* trigger pin will start a configPortal AP for 120 seconds then turn it off.
*
*/
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
// select which pin will trigger the configuration portal when set to LOW
#define TRIGGER_PIN 0
int timeout = 120; // seconds to run for
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("\n Starting");
pinMode(TRIGGER_PIN, INPUT_PULLUP);
}
void loop() {
// is configuration portal requested?
if ( digitalRead(TRIGGER_PIN) == LOW) {
WiFiManager wm;
//reset settings - for testing
//wifiManager.resetSettings();
// set configportal timeout
wm.setConfigPortalTimeout(timeout);
if (!wm.startConfigPortal("OnDemandAP")) {
Serial.println("failed to connect and hit timeout");
delay(3000);
//reset and try again, or maybe put it to deep sleep
ESP.restart();
delay(5000);
}
//if you get here you have connected to the WiFi
Serial.println("connected...yeey :)");
}
// put your main code here, to run repeatedly:
}
@@ -0,0 +1,50 @@
/**
* OnDemandWebPortal.ino
* example of running the webportal (always NON blocking)
*/
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
// select which pin will trigger the configuration portal when set to LOW
#define TRIGGER_PIN 0
WiFiManager wm;
bool portalRunning = false;
void setup() {
// put your setup code here, to run once
Serial.begin(115200);
Serial.println("\n Starting");
pinMode(TRIGGER_PIN, INPUT_PULLUP);
}
void loop() {
checkButton();
// put your main code here, to run repeatedly:
}
void checkButton(){
// is auto timeout portal running
if(portalRunning){
wm.process();
}
// is configuration portal requested?
if(digitalRead(TRIGGER_PIN) == LOW) {
delay(50);
if(digitalRead(TRIGGER_PIN) == LOW) {
if(!portalRunning){
Serial.println("Button Pressed, Starting Portal");
wm.startWebPortal();
portalRunning = true;
}
else{
Serial.println("Button Pressed, Stopping Portal");
wm.startWebPortal();
portalRunning = false;
}
}
}
}
@@ -1,60 +0,0 @@
#include <ESP8266WiFi.h> //https://github.com/esp8266/Arduino
//needed for library
#include <ESP8266WebServer.h>
#include <DNSServer.h>
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
// select which pin will trigger the configuration portal when set to LOW
// ESP-01 users please note: the only pins available (0 and 2), are shared
// with the bootloader, so always set them HIGH at power-up
#define TRIGGER_PIN 0
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("\n Starting");
pinMode(TRIGGER_PIN, INPUT);
}
void loop() {
// is configuration portal requested?
if ( digitalRead(TRIGGER_PIN) == LOW ) {
//WiFiManager
//Local intialization. Once its business is done, there is no need to keep it around
WiFiManager wifiManager;
//reset settings - for testing
//wifiManager.resetSettings();
//sets timeout until configuration portal gets turned off
//useful to make it all retry or go to sleep
//in seconds
//wifiManager.setTimeout(120);
//it starts an access point with the specified name
//here "AutoConnectAP"
//and goes into a blocking loop awaiting configuration
//WITHOUT THIS THE AP DOES NOT SEEM TO WORK PROPERLY WITH SDK 1.5 , update to at least 1.5.1
//WiFi.mode(WIFI_STA);
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:
}
@@ -0,0 +1,140 @@
/**
* WiFiManagerParameter child class example
*/
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
#include <Arduino.h>
#include <EEPROM.h>
#define SETUP_PIN 0
class IPAddressParameter : public WiFiManagerParameter {
public:
IPAddressParameter(const char *id, const char *placeholder, IPAddress address)
: WiFiManagerParameter("") {
init(id, placeholder, address.toString().c_str(), 16, "", WFM_LABEL_BEFORE);
}
bool getValue(IPAddress &ip) {
return ip.fromString(WiFiManagerParameter::getValue());
}
};
class IntParameter : public WiFiManagerParameter {
public:
IntParameter(const char *id, const char *placeholder, long value, const uint8_t length = 10)
: WiFiManagerParameter("") {
init(id, placeholder, String(value).c_str(), length, "", WFM_LABEL_BEFORE);
}
long getValue() {
return String(WiFiManagerParameter::getValue()).toInt();
}
};
class FloatParameter : public WiFiManagerParameter {
public:
FloatParameter(const char *id, const char *placeholder, float value, const uint8_t length = 10)
: WiFiManagerParameter("") {
init(id, placeholder, String(value).c_str(), length, "", WFM_LABEL_BEFORE);
}
float getValue() {
return String(WiFiManagerParameter::getValue()).toFloat();
}
};
struct Settings {
float f;
int i;
char s[20];
uint32_t ip;
} sett;
void setup() {
pinMode(SETUP_PIN, INPUT_PULLUP);
Serial.begin(9600);
//Delay to push SETUP button
Serial.println("Press setup button");
for (int sec = 3; sec > 0; sec--) {
Serial.print(sec);
Serial.print("..");
delay(1000);
}
EEPROM.begin( 512 );
EEPROM.get(0, sett);
Serial.println("Settings loaded");
if (digitalRead(SETUP_PIN) == LOW) {
// Button pressed
Serial.println("SETUP");
WiFiManager wm;
sett.s[19] = '\0'; //add null terminator at the end cause overflow
WiFiManagerParameter param_str( "str", "param_string", sett.s, 20);
FloatParameter param_float( "float", "param_float", sett.f);
IntParameter param_int( "int", "param_int", sett.i);
IPAddress ip(sett.ip);
IPAddressParameter param_ip("ip", "param_ip", ip);
wm.addParameter( &param_str );
wm.addParameter( &param_float );
wm.addParameter( &param_int );
wm.addParameter( &param_ip );
//SSID & password parameters already included
wm.startConfigPortal();
strncpy(sett.s, param_str.getValue(), 20);
sett.s[19] = '\0';
sett.f = param_float.getValue();
sett.i = param_int.getValue();
Serial.print("String param: ");
Serial.println(sett.s);
Serial.print("Float param: ");
Serial.println(sett.f);
Serial.print("Int param: ");
Serial.println(sett.i, DEC);
if (param_ip.getValue(ip)) {
sett.ip = ip;
Serial.print("IP param: ");
Serial.println(ip);
} else {
Serial.println("Incorrect IP");
}
EEPROM.put(0, sett);
if (EEPROM.commit()) {
Serial.println("Settings saved");
} else {
Serial.println("EEPROM error");
}
}
else {
Serial.println("WORK");
//connect to saved SSID
WiFi.begin();
//do smth
Serial.print("String param: ");
Serial.println(sett.s);
Serial.print("Float param: ");
Serial.println(sett.f);
Serial.print("Int param: ");
Serial.println(sett.i, DEC);
Serial.print("IP param: ");
IPAddress ip(sett.ip);
Serial.println(ip);
}
}
void loop() {
}