初始化提交

This commit is contained in:
王立帮
2024-07-20 22:09:06 +08:00
commit c247dd07a6
6876 changed files with 2743096 additions and 0 deletions

View File

@@ -0,0 +1,141 @@
/**
* 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 can run in a blocking mode or a non blocking mode
// Be sure to know how to process loops with no delay() if using non blocking
bool wm_nonblocking = false; // change to true to use non blocking
WiFiManager wm; // global wm instance
WiFiManagerParameter custom_field; // global param ( for non blocking w params )
void setup() {
WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP
Serial.begin(115200);
Serial.setDebugOutput(true);
delay(3000);
Serial.println("\n Starting");
pinMode(TRIGGER_PIN, INPUT);
// wm.resetSettings(); // wipe settings
if(wm_nonblocking) wm.setConfigPortalBlocking(false);
// 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() {
if(wm_nonblocking) wm.process(); // avoid delays() in loop when non-blocking and other long running code
checkButton();
// put your main code here, to run repeatedly:
}

View File

@@ -0,0 +1,41 @@
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
void setup() {
// WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP
// it is a good practice to make sure your code sets wifi mode how you want it.
// 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 wm;
// reset settings - wipe stored credentials for testing
// these are stored by the esp library
// 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:
}

View File

@@ -0,0 +1,27 @@
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
WiFiManager wm;
void setup() {
WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP
// put your setup code here, to run once:
Serial.begin(115200);
//reset settings - wipe credentials for testing
//wm.resetSettings();
wm.setConfigPortalBlocking(false);
wm.setConfigPortalTimeout(60);
//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:
}

View File

@@ -0,0 +1,36 @@
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
WiFiManager wm;
WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "", 40);
void setup() {
WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP
// 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());
}

View File

@@ -0,0 +1,85 @@
/**
* 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.
* startAP = true will start both the configportal AP and webportal
*/
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
// include MDNS
#ifdef ESP8266
#include <ESP8266mDNS.h>
#elif defined(ESP32)
#include <ESPmDNS.h>
#endif
// 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() {
WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP
// put your setup code here, to run once
Serial.begin(115200);
Serial.setDebugOutput(true);
delay(1000);
Serial.println("\n Starting");
pinMode(TRIGGER_PIN, INPUT_PULLUP);
// wm.resetSettings();
wm.setHostname("MDNSEXAMPLE");
// wm.setEnableConfigPortal(false);
// wm.setConfigPortalBlocking(false);
wm.autoConnect();
}
void loop() {
#ifdef ESP8266
MDNS.update();
#endif
doWiFiManager();
// put your main code here, to run repeatedly:
}
void doWiFiManager(){
// is auto timeout portal running
if(portalRunning){
wm.process(); // do processing
// check for timeout
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();
}
}

View File

@@ -0,0 +1,42 @@
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
void configModeCallback (WiFiManager *myWiFiManager) {
Serial.println("Entered config mode");
Serial.println(WiFi.softAPIP());
//if you used auto generated SSID, print it
Serial.println(myWiFiManager->getConfigPortalSSID());
}
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 settings - for testing
//wifiManager.resetSettings();
//set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode
wifiManager.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()) {
Serial.println("failed to connect and hit timeout");
//reset and try again, or maybe put it to deep sleep
ESP.restart();
delay(1000);
}
//if you get here you have connected to the WiFi
Serial.println("connected...yeey :)");
}
void loop() {
// put your main code here, to run repeatedly:
}

View File

@@ -0,0 +1,43 @@
#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:
Serial.begin(115200);
Serial.println();
//WiFiManager
//Local intialization. Once its business is done, there is no need to keep it around
WiFiManager wifiManager;
//exit after config instead of connecting
wifiManager.setBreakAfterConfig(true);
//reset settings - for testing
//wifiManager.resetSettings();
//tries to connect to last known settings
//if it does not connect it starts an access point with the specified name
//here "AutoConnectAP" with password "password"
//and goes into a blocking loop awaiting configuration
if (!wifiManager.autoConnect("AutoConnectAP", "password")) {
Serial.println("failed to connect, we should reset as see if it connects");
delay(3000);
ESP.restart();
delay(5000);
}
//if you get here you have connected to the WiFi
Serial.println("connected...yeey :)");
Serial.println("local ip");
Serial.println(WiFi.localIP());
}
void loop() {
// put your main code here, to run repeatedly:
}

View File

@@ -0,0 +1,71 @@
#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
* although the IP shows in the config portal, the changes will revert
* to the IP set in the source file.
* 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";
//char static_sn[16] = "255.255.255.0";
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println();
//WiFiManager
//Local intialization. Once its business is done, there is no need to keep it around
WiFiManager wifiManager;
//reset settings - for testing
//wifiManager.resetSettings();
//set static ip
//block1 should be used for ESP8266 core 2.1.0 or newer, otherwise use block2
//start-block1
//IPAddress _ip,_gw,_sn;
//_ip.fromString(static_ip);
//_gw.fromString(static_gw);
//_sn.fromString(static_sn);
//end-block1
//start-block2
IPAddress _ip = IPAddress(10, 0, 1, 78);
IPAddress _gw = IPAddress(10, 0, 1, 1);
IPAddress _sn = IPAddress(255, 255, 255, 0);
//end-block2
wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn);
//tries to connect to last known settings
//if it does not connect it starts an access point with the specified name
//here "AutoConnectAP" with password "password"
//and goes into a blocking loop awaiting configuration
if (!wifiManager.autoConnect("AutoConnectAP", "password")) {
Serial.println("failed to connect, we should reset as see if it connects");
delay(3000);
ESP.restart();
delay(5000);
}
//if you get here you have connected to the WiFi
Serial.println("connected...yeey :)");
Serial.println("local ip");
Serial.println(WiFi.localIP());
}
void loop() {
// put your main code here, to run repeatedly:
}

View File

@@ -0,0 +1,38 @@
#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 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.setConfigPortalTimeout(180);
//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.restart();
delay(5000);
}
//if you get here you have connected to the WiFi
Serial.println("connected...yeey :)");
}
void loop() {
// put your main code here, to run repeatedly:
}

View File

@@ -0,0 +1,47 @@
/**
* 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() {
WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP
// 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
//wm.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:
}

View File

@@ -0,0 +1,51 @@
/**
* 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() {
WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP
// 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.stopWebPortal();
portalRunning = false;
}
}
}
}

View File

@@ -0,0 +1,79 @@
/**
* Basic example using LittleFS to store data
*/
#include <Arduino.h>
#include <LittleFS.h>
#include <FS.h>
String readFile(fs::FS &fs, const char * path){
Serial.printf("Reading file: %s\r\n", path);
File file = fs.open(path, "r");
if(!file || file.isDirectory()){
Serial.println("- empty file or failed to open file");
return String();
}
Serial.println("- read from file:");
String fileContent;
while(file.available()){
fileContent+=String((char)file.read());
}
file.close();
Serial.println(fileContent);
return fileContent;
}
void writeFile(fs::FS &fs, const char * path, const char * message){
Serial.printf("Writing file: %s\r\n", path);
File file = fs.open(path, "w");
if(!file){
Serial.println("- failed to open file for writing");
return;
}
if(file.print(message)){
Serial.println("- file written");
} else {
Serial.println("- write failed");
}
file.close();
}
int data = 4;
#include <WiFiManager.h>
#define TRIGGER_PIN 2
int timeout = 120; // seconds to run for
void setup() {
if (!LittleFS.begin()) { //to start littlefs
Serial.println("LittleFS mount failed");
return;
}
data = readFile(LittleFS, "/data.txt").toInt();
WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP
// put your setup code here, to run once:
pinMode(TRIGGER_PIN, INPUT_PULLUP);
WiFiManager wm;
//wm.resetSettings();
bool res;
res = wm.autoConnect("Setup");
if(!res) {
Serial.println("Failed to connect");
// ESP.restart();
}
}
void loop() {
if ( digitalRead(TRIGGER_PIN) == LOW) {
WiFiManager wm;
//wm.resetSettings();
wm.setConfigPortalTimeout(timeout);
if (!wm.startConfigPortal("Sharmander")) {
Serial.println("failed to connect and hit timeout");
delay(3000);
ESP.restart();
delay(5000);
}
Serial.println("connected...yeey :)");
}
}

View File

@@ -0,0 +1,169 @@
#include <FS.h> //this needs to be first, or it all crashes and burns...
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
#ifdef ESP32
#include <SPIFFS.h>
#endif
#include <ArduinoJson.h> //https://github.com/bblanchon/ArduinoJson
//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 api_token[34] = "YOUR_API_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);
#if defined(ARDUINOJSON_VERSION_MAJOR) && ARDUINOJSON_VERSION_MAJOR >= 6
DynamicJsonDocument json(1024);
auto deserializeError = deserializeJson(json, buf.get());
serializeJson(json, Serial);
if ( ! deserializeError ) {
#else
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.parseObject(buf.get());
json.printTo(Serial);
if (json.success()) {
#endif
Serial.println("\nparsed json");
strcpy(mqtt_server, json["mqtt_server"]);
strcpy(mqtt_port, json["mqtt_port"]);
strcpy(api_token, json["api_token"]);
} else {
Serial.println("failed to load json config");
}
configFile.close();
}
}
} 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_api_token("apikey", "API token", 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_api_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("AutoConnectAP", "password")) {
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 :)");
//read updated parameters
strcpy(mqtt_server, custom_mqtt_server.getValue());
strcpy(mqtt_port, custom_mqtt_port.getValue());
strcpy(api_token, custom_api_token.getValue());
Serial.println("The values in the file are: ");
Serial.println("\tmqtt_server : " + String(mqtt_server));
Serial.println("\tmqtt_port : " + String(mqtt_port));
Serial.println("\tapi_token : " + String(api_token));
//save the custom parameters to FS
if (shouldSaveConfig) {
Serial.println("saving config");
#if defined(ARDUINOJSON_VERSION_MAJOR) && ARDUINOJSON_VERSION_MAJOR >= 6
DynamicJsonDocument json(1024);
#else
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.createObject();
#endif
json["mqtt_server"] = mqtt_server;
json["mqtt_port"] = mqtt_port;
json["api_token"] = api_token;
File configFile = SPIFFS.open("/config.json", "w");
if (!configFile) {
Serial.println("failed to open config file for writing");
}
#if defined(ARDUINOJSON_VERSION_MAJOR) && ARDUINOJSON_VERSION_MAJOR >= 6
serializeJson(json, Serial);
serializeJson(json, configFile);
#else
json.printTo(Serial);
json.printTo(configFile);
#endif
configFile.close();
//end save
}
Serial.println("local ip");
Serial.println(WiFi.localIP());
}
void loop() {
// put your main code here, to run repeatedly:
}

View File

@@ -0,0 +1,194 @@
#include <FS.h> //this needs to be first, or it all crashes and burns...
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
#ifdef ESP32
#include <SPIFFS.h>
#endif
#include <ArduinoJson.h> //https://github.com/bblanchon/ArduinoJson
//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 api_token[34] = "YOUR_APITOKEN";
//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;
//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);
#if defined(ARDUINOJSON_VERSION_MAJOR) && ARDUINOJSON_VERSION_MAJOR >= 6
DynamicJsonDocument json(1024);
auto deserializeError = deserializeJson(json, buf.get());
serializeJson(json, Serial);
if ( ! deserializeError ) {
#else
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.parseObject(buf.get());
json.printTo(Serial);
if (json.success()) {
#endif
Serial.println("\nparsed json");
strcpy(mqtt_server, json["mqtt_server"]);
strcpy(mqtt_port, json["mqtt_port"]);
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");
}
}
}
} else {
Serial.println("failed to mount FS");
}
//end read
Serial.println(static_ip);
Serial.println(api_token);
Serial.println(mqtt_server);
// 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_api_token("apikey", "API token", api_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
IPAddress _ip, _gw, _sn;
_ip.fromString(static_ip);
_gw.fromString(static_gw);
_sn.fromString(static_sn);
wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn);
//add all your parameters here
wifiManager.addParameter(&custom_mqtt_server);
wifiManager.addParameter(&custom_mqtt_port);
wifiManager.addParameter(&custom_api_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("AutoConnectAP", "password")) {
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 :)");
//read updated parameters
strcpy(mqtt_server, custom_mqtt_server.getValue());
strcpy(mqtt_port, custom_mqtt_port.getValue());
strcpy(api_token, custom_api_token.getValue());
//save the custom parameters to FS
if (shouldSaveConfig) {
Serial.println("saving config");
#if defined(ARDUINOJSON_VERSION_MAJOR) && ARDUINOJSON_VERSION_MAJOR >= 6
DynamicJsonDocument json(1024);
#else
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.createObject();
#endif
json["mqtt_server"] = mqtt_server;
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");
}
#if defined(ARDUINOJSON_VERSION_MAJOR) && ARDUINOJSON_VERSION_MAJOR >= 6
serializeJson(json, Serial);
serializeJson(json, configFile);
#else
json.printTo(Serial);
json.printTo(configFile);
#endif
configFile.close();
//end save
}
Serial.println("local ip");
Serial.println(WiFi.localIP());
Serial.println(WiFi.gatewayIP());
Serial.println(WiFi.subnetMask());
}
void loop() {
// put your main code here, to run repeatedly:
}

View File

@@ -0,0 +1,143 @@
/**
* 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() {
WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP
pinMode(SETUP_PIN, INPUT_PULLUP);
Serial.begin(115200);
//Delay to push SETUP button
Serial.println("Press setup button");
for (int sec = 3; sec > 0; sec--) {
Serial.print(sec);
Serial.print("..");
delay(1000);
}
// warning for example only, this will initialize empty memory into your vars
// always init flash memory or add some checksum bits
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() {
}

View File

@@ -0,0 +1,416 @@
/**
* This is a kind of unit test for DEV for now
* It contains many of the public methods
*
*/
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
#include <time.h>
#include <stdio.h>
#define USEOTA
// enable OTA
#ifdef USEOTA
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#endif
const char* modes[] = { "NULL", "STA", "AP", "STA+AP" };
unsigned long mtime = 0;
WiFiManager wm;
// TEST OPTION FLAGS
bool TEST_CP = false; // always start the configportal, even if ap found
int TESP_CP_TIMEOUT = 90; // test cp timeout
bool TEST_NET = true; // do a network test after connect, (gets ntp time)
bool ALLOWONDEMAND = true; // enable on demand
int ONDDEMANDPIN = 0; // gpio for button
bool WMISBLOCKING = true; // use blocking or non blocking mode, non global params wont work in non blocking
// char ssid[] = "*************"; // your network SSID (name)
// char pass[] = "********"; // your network password
//callbacks
// called after AP mode and config portal has started
// setAPCallback( std::function<void(WiFiManager*)> func );
// called after webserver has started
// setWebServerCallback( std::function<void()> func );
// called when settings reset have been triggered
// setConfigResetCallback( std::function<void()> func );
// called when wifi settings have been changed and connection was successful ( or setBreakAfterConfig(true) )
// setSaveConfigCallback( std::function<void()> func );
// called when saving either params-in-wifi or params page
// setSaveParamsCallback( std::function<void()> func );
// called when saving params-in-wifi or params before anything else happens (eg wifi)
// setPreSaveConfigCallback( std::function<void()> func );
// called just before doing OTA update
// setPreOtaUpdateCallback( std::function<void()> func );
void saveWifiCallback(){
Serial.println("[CALLBACK] saveCallback fired");
}
//gets called when WiFiManager enters configuration mode
void configModeCallback (WiFiManager *myWiFiManager) {
Serial.println("[CALLBACK] configModeCallback fired");
// 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());
//
// esp_wifi_set_bandwidth(WIFI_IF_AP, WIFI_BW_HT20);
}
void saveParamCallback(){
Serial.println("[CALLBACK] saveParamCallback fired");
// wm.stopConfigPortal();
}
void bindServerCallback(){
wm.server->on("/custom",handleRoute); // this is now crashing esp32 for some reason
// wm.server->on("/info",handleRoute); // you can override wm!
}
void handleRoute(){
Serial.println("[HTTP] handle route");
wm.server->send(200, "text/plain", "hello from user code");
}
void handlePreOtaUpdateCallback(){
Update.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf("CUSTOM Progress: %u%%\r", (progress / (total / 100)));
});
}
void setup() {
// WiFi.mode(WIFI_STA); // explicitly set mode, esp can default to STA+AP
// put your setup code here, to run once:
Serial.begin(115200);
// Serial.setDebugOutput(true);
Serial.println("\n Starting");
// WiFi.setSleepMode(WIFI_NONE_SLEEP); // disable sleep, can improve ap stability
Serial.println("Error - TEST");
Serial.println("Information- - TEST");
Serial.println("[ERROR] TEST");
Serial.println("[INFORMATION] TEST");
wm.setDebugOutput(true);
wm.debugPlatformInfo();
//reset settings - for testing
// wm.resetSettings();
// wm.erase();
// setup some parameters
WiFiManagerParameter custom_html("<p style=\"color:pink;font-weight:Bold;\">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)
WiFiManagerParameter custom_input_type("input_pwd", "input pass", "", 15,"type='password'"); // custom input attrs (ip mask)
const char _customHtml_checkbox[] = "type=\"checkbox\"";
WiFiManagerParameter custom_checkbox("my_checkbox", "My Checkbox", "T", 2, _customHtml_checkbox,WFM_LABEL_AFTER);
const char *bufferStr = R"(
<!-- INPUT CHOICE -->
<br/>
<p>Select Choice</p>
<input style='display: inline-block;' type='radio' id='choice1' name='program_selection' value='1'>
<label for='choice1'>Choice1</label><br/>
<input style='display: inline-block;' type='radio' id='choice2' name='program_selection' value='2'>
<label for='choice2'>Choice2</label><br/>
<!-- INPUT SELECT -->
<br/>
<label for='input_select'>Label for Input Select</label>
<select name="input_select" id="input_select" class="button">
<option value="0">Option 1</option>
<option value="1" selected>Option 2</option>
<option value="2">Option 3</option>
<option value="3">Option 4</option>
</select>
)";
WiFiManagerParameter custom_html_inputs(bufferStr);
// callbacks
wm.setAPCallback(configModeCallback);
wm.setWebServerCallback(bindServerCallback);
wm.setSaveConfigCallback(saveWifiCallback);
wm.setSaveParamsCallback(saveParamCallback);
wm.setPreOtaUpdateCallback(handlePreOtaUpdateCallback);
// 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);
wm.addParameter(&custom_checkbox);
wm.addParameter(&custom_input_type);
wm.addParameter(&custom_html_inputs);
// set values later if you want
custom_html.setValue("test",4);
custom_token.setValue("test",4);
// const char* icon = "
// <link rel='icon' type='image/png' sizes='16x16' href='data:image/png;base64,
// iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAAMFBMVEU0OkArMjhobHEoPUPFEBIu
// O0L+AAC2FBZ2JyuNICOfGx7xAwTjCAlCNTvVDA1aLzQ3COjMAAAAVUlEQVQI12NgwAaCDSA0888G
// CItjn0szWGBJTVoGSCjWs8TleQCQYV95evdxkFT8Kpe0PLDi5WfKd4LUsN5zS1sKFolt8bwAZrCa
// GqNYJAgFDEpQAAAzmxafI4vZWwAAAABJRU5ErkJggg==' />";
// set custom html head content , inside <head>
// examples of favicon, or meta tags etc
// const char* headhtml = "<link rel='icon' type='image/png' href='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAADQElEQVRoQ+2YjW0VQQyE7Q6gAkgFkAogFUAqgFQAVACpAKiAUAFQAaECQgWECggVGH1PPrRvn3dv9/YkFOksoUhhfzwz9ngvKrc89JbnLxuA/63gpsCmwCADWwkNEji8fVNgotDM7osI/x777x5l9F6JyB8R4eeVql4P0y8yNsjM7KGIPBORp558T04A+CwiH1UVUItiUQmZ2XMReSEiAFgjAPBeVS96D+sCYGaUx4cFbLfmhSpnqnrZuqEJgJnd8cQplVLciAgX//Cf0ToIeOB9wpmloLQAwpnVmAXgdf6pwjpJIz+XNoeZQQZlODV9vhc1Tuf6owrAk/8qIhFbJH7eI3eEzsvydQEICqBEkZwiALfF70HyHPpqScPV5HFjeFu476SkRA0AzOfy4hYwstj2ZkDgaphE7m6XqnoS7Q0BOPs/sw0kDROzjdXcCMFCNwzIy0EcRcOvBACfh4k0wgOmBX4xjfmk4DKTS31hgNWIKBCI8gdzogTgjYjQWFMw+o9LzJoZ63GUmjWm2wGDc7EvDDOj/1IVMIyD9SUAL0WEhpriRlXv5je5S+U1i2N88zdPuoVkeB+ls4SyxCoP3kVm9jsjpEsBLoOBNC5U9SwpGdakFkviuFP1keblATkTENTYcxkzgxTKOI3jyDxqLkQT87pMA++H3XvJBYtsNbBN6vuXq5S737WqHkW1VgMQNXJ0RshMqbbT33sJ5kpHWymzcJjNTeJIymJZtSQd9NHQHS1vodoFoTMkfbJzpRnLzB2vi6BZAJxWaCr+62BC+jzAxVJb3dmmiLzLwZhZNPE5e880Suo2AZgB8e8idxherqUPnT3brBDTlPxO3Z66rVwIwySXugdNd+5ejhqp/+NmgIwGX3Py3QBmlEi54KlwmjkOytQ+iJrLJj23S4GkOeecg8G091no737qvRRdzE+HLALQoMTBbJgBsCj5RSWUlUVJiZ4SOljb05eLFWgoJ5oY6yTyJp62D39jDANoKKcSocPJD5dQYzlFAFZJflUArgTPZKZwLXAnHmerfJquUkKZEgyzqOb5TuDt1P3nwxobqwPocZA11m4A1mBx5IxNgRH21ti7KbAGiyNn3HoF/gJ0w05A8xclpwAAAABJRU5ErkJggg==' />";
// const char* headhtml = "<meta name='color-scheme' content='dark light'><style></style><script></script>";
// wm.setCustomHeadElement(headhtml);
// set custom html menu content , inside menu item "custom", see setMenu()
const char* menuhtml = "<form action='/custom' method='get'><button>Custom</button></form><br/>\n";
wm.setCustomMenuHTML(menuhtml);
// invert theme, dark
wm.setDarkMode(true);
// show scan RSSI as percentage, instead of signal stength graphic
// wm.setScanDispPerc(true);
/*
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","custom","close","sep","erase","update","restart","exit"};
wm.setMenu(menu); // custom menu, pass vector
// wm.setParamsPage(true); // move params to seperate page, not wifi, do not combine with setmenu!
// set STA static 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 AP 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));
// set country
// setting wifi country seems to improve OSX soft ap connectivity,
// may help others as well, default is CN which has different channels
// wm.setCountry("US"); // crashing on esp32 2.0
// set Hostname
wm.setHostname(("WM_"+wm.getDefaultAPName()).c_str());
// wm.setHostname("WM_RANDO_1234");
// set custom channel
// wm.setWiFiAPChannel(13);
// set AP hidden
// wm.setAPHidden(true);
// show password publicly in form
// wm.setShowPassword(true);
// sets wether wm configportal is a blocking loop(legacy) or not, use wm.process() in loop if false
// wm.setConfigPortalBlocking(false);
if(!WMISBLOCKING){
wm.setConfigPortalBlocking(false);
}
//sets timeout until configuration portal gets turned off
//useful to make it all retry or go to sleep in seconds
wm.setConfigPortalTimeout(120);
// set min quality to show in web list, default 8%
// wm.setMinimumSignalQuality(50);
// set connection timeout
// wm.setConnectTimeout(20);
// set wifi connect retries
// wm.setConnectRetries(2);
// connect after portal save toggle
// wm.setSaveConnect(false); // do not connect, only save
// show static ip fields
// wm.setShowStaticFields(true);
// wm.startConfigPortal("AutoConnectAP", "password");
// This is sometimes necessary, it is still unknown when and why this is needed but it may solve some race condition or bug in esp SDK/lib
// wm.setCleanConnect(true); // disconnect before connect, clean connect
wm.setBreakAfterConfig(true); // needed to use saveWifiCallback
// set custom webserver port, automatic captive portal does not work with custom ports!
// wm.setHttpPort(8080);
//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
// use autoconnect, but prevent configportal from auto starting
// wm.setEnableConfigPortal(false);
wifiInfo();
// to preload autoconnect with credentials
// wm.preloadWiFi("ssid","password");
if(!wm.autoConnect("WM_AutoConnectAP","12345678")) {
Serial.println("failed to connect and hit timeout");
}
else if(TEST_CP) {
// start configportal always
delay(1000);
Serial.println("TEST_CP ENABLED");
wm.setConfigPortalTimeout(TESP_CP_TIMEOUT);
wm.startConfigPortal("WM_ConnectAP","12345678");
}
else {
//if you get here you have connected to the WiFi
Serial.println("connected...yeey :)");
}
wifiInfo();
pinMode(ONDDEMANDPIN, INPUT_PULLUP);
#ifdef USEOTA
ArduinoOTA.begin();
#endif
}
void wifiInfo(){
// can contain gargbage on esp32 if wifi is not ready yet
Serial.println("[WIFI] WIFI INFO DEBUG");
// WiFi.printDiag(Serial);
Serial.println("[WIFI] SAVED: " + (String)(wm.getWiFiIsSaved() ? "YES" : "NO"));
Serial.println("[WIFI] SSID: " + (String)wm.getWiFiSSID());
Serial.println("[WIFI] PASS: " + (String)wm.getWiFiPass());
Serial.println("[WIFI] HOSTNAME: " + (String)WiFi.getHostname());
}
void loop() {
if(!WMISBLOCKING){
wm.process();
}
#ifdef USEOTA
ArduinoOTA.handle();
#endif
// is configuration portal requested?
if (ALLOWONDEMAND && digitalRead(ONDDEMANDPIN) == LOW ) {
delay(100);
if ( digitalRead(ONDDEMANDPIN) == LOW ){
Serial.println("BUTTON PRESSED");
// button reset/reboot
// wm.resetSettings();
// wm.reboot();
// delay(200);
// return;
wm.setConfigPortalTimeout(140);
wm.setParamsPage(false); // move params to seperate page, not wifi, do not combine with setmenu!
// disable captive portal redirection
// wm.setCaptivePortalEnable(false);
if (!wm.startConfigPortal("OnDemandAP","12345678")) {
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 :)");
getTime();
}
}
// every 10 seconds
if(millis()-mtime > 10000 ){
if(WiFi.status() == WL_CONNECTED){
getTime();
}
else Serial.println("No Wifi");
mtime = millis();
}
// put your main code here, to run repeatedly:
delay(100);
}
void getTime() {
int tz = -5;
int dst = 0;
time_t now = time(nullptr);
unsigned timeout = 5000; // try for timeout
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 ) { // what is this ?
delay(100);
Serial.print(".");
now = time(nullptr);
if((millis() - start) > timeout){
Serial.println("\n[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
}

View File

@@ -0,0 +1,51 @@
// wifi_basic.ino
#include <Arduino.h>
#include <WiFi.h>
// #define NVSERASE
#ifdef NVSERASE
#include <nvs.h>
#include <nvs_flash.h>
#endif
void setup(){
Serial.begin(115200);
delay(2000);
Serial.println("Startup....");
#ifdef NVSERASE
esp_err_t err;
err = nvs_flash_init();
err = nvs_flash_erase();
#endif
Serial.setDebugOutput(true);
WiFi.begin("hellowifi","noonehere");
while (WiFi.status() != WL_CONNECTED && millis()<15000) {
delay(500);
Serial.print(".");
}
if(WiFi.status() == WL_CONNECTED){
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
// Serial.println(WiFi.localIP());
}
else {
Serial.println("WiFi NOT CONNECTED, starting ap");
///////////////
/// BUG
// WiFi.enableSTA(false); // BREAKS softap start, says ok BUT no ap found
delay(2000);
WiFi.softAP("espsoftap","12345678");
}
}
void loop(){
}

View File

@@ -0,0 +1,26 @@
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
bool _enteredConfigMode = false;
void setup(){
Serial.begin(115200);
WiFiManager wifiManager;
// wifiManager.setAPCallback([this](WiFiManager* wifiManager) {
wifiManager.setAPCallback([&](WiFiManager* wifiManager) {
Serial.printf("Entered config mode:ip=%s, ssid='%s'\n",
WiFi.softAPIP().toString().c_str(),
wifiManager->getConfigPortalSSID().c_str());
_enteredConfigMode = true;
});
wifiManager.resetSettings();
if (!wifiManager.autoConnect()) {
Serial.printf("*** Failed to connect and hit timeout\n");
ESP.restart();
delay(1000);
}
}
void loop(){
}