Added wifmanager

This commit is contained in:
Magnus Persson 2022-01-09 23:12:40 +01:00
parent 7f775d78eb
commit 4ff114642e
9 changed files with 5659 additions and 107 deletions

View File

@ -0,0 +1,368 @@
/****************************************************************************************************************************
ESP_DoubleResetDetector.h
For ESP8266 / ESP32 boards
ESP_DoubleResetDetector is a library for the ESP8266/Arduino platform
to enable trigger configure mode by resetting ESP32 / ESP8266 twice.
Forked from DataCute https://github.com/datacute/DoubleResetDetector
Built by Khoi Hoang https://github.com/khoih-prog/ESP_DoubleResetDetector
Licensed under MIT license
Version: 1.2.1
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 15/12/2019 Initial coding
1.0.1 K Hoang 30/12/2019 Now can use EEPROM or SPIFFS for both ESP8266 and ESP32. RTC still OK for ESP8266
1.0.2 K Hoang 10/04/2020 Fix bug by left-over cpp file and in example.
1.0.3 K Hoang 13/05/2020 Update to use LittleFS for ESP8266 core 2.7.1+
1.1.0 K Hoang 04/12/2020 Add support to LittleFS for ESP32 using LITTLEFS Library
1.1.1 K Hoang 28/12/2020 Suppress all possible compiler warnings
1.1.2 K Hoang 10/10/2021 Update `platform.ini` and `library.json`
1.2.0 K Hoang 26/11/2021 Auto detect ESP32 core and use either built-in LittleFS or LITTLEFS library
1.2.1 K Hoang 26/11/2021 Fix compile error for ESP32 core v1.0.5-
*****************************************************************************************************************************/
#pragma once
#ifndef ESP_DoubleResetDetector_H
#define ESP_DoubleResetDetector_H
#if defined(ARDUINO) && (ARDUINO >= 100)
#include <Arduino.h>
#else
#include <WProgram.h>
#endif
#define ESP_DOUBLE_RESET_DETECTOR_VERSION "ESP_DoubleResetDetector v1.2.1"
#define ESP_DOUBLERESETDETECTOR_VERSION ESP_DOUBLE_RESET_DETECTOR_VERSION
//#define ESP_DRD_USE_EEPROM false
//#define ESP_DRD_USE_LITTLEFS false
//#define ESP_DRD_USE_SPIFFS false
//#define ESP8266_DRD_USE_RTC false //true
#ifdef ESP32
#if (!ESP_DRD_USE_EEPROM && !ESP_DRD_USE_SPIFFS && !ESP_DRD_USE_LITTLEFS)
#warning Neither EEPROM, SPIFFS nor LittleFS selected. Default to EEPROM
#ifdef ESP_DRD_USE_EEPROM
#undef ESP_DRD_USE_EEPROM
#define ESP_DRD_USE_EEPROM true
#endif
#endif
#endif
#ifdef ESP8266
#if (!ESP8266_DRD_USE_RTC && !ESP_DRD_USE_EEPROM && !ESP_DRD_USE_SPIFFS && !ESP_DRD_USE_LITTLEFS)
#warning Neither RTC, EEPROM, LITTLEFS nor SPIFFS selected. Default to EEPROM
#ifdef ESP_DRD_USE_EEPROM
#undef ESP_DRD_USE_EEPROM
#define ESP_DRD_USE_EEPROM true
#endif
#endif
#endif
//default to use EEPROM, otherwise, use LITTLEFS (higher priority), then SPIFFS
#if ESP_DRD_USE_EEPROM
#include <EEPROM.h>
#define FLAG_DATA_SIZE 4
#ifndef EEPROM_SIZE
#define EEPROM_SIZE 512
#endif
#ifndef EEPROM_START
#define EEPROM_START 256
#endif
#elif ( ESP_DRD_USE_LITTLEFS || ESP_DRD_USE_SPIFFS )
#include <FS.h>
#ifdef ESP32
#if ESP_DRD_USE_LITTLEFS
// Check cores/esp32/esp_arduino_version.h and cores/esp32/core_version.h
//#if ( ESP_ARDUINO_VERSION >= ESP_ARDUINO_VERSION_VAL(2, 0, 0) ) //(ESP_ARDUINO_VERSION_MAJOR >= 2)
#if ( defined(ESP_ARDUINO_VERSION_MAJOR) && (ESP_ARDUINO_VERSION_MAJOR >= 2) )
#warning Using ESP32 Core 1.0.6 or 2.0.0+
// The library has been merged into esp32 core from release 1.0.6
#include <LittleFS.h>
#define FileFS LittleFS
#define FS_Name "LittleFS"
#else
#warning Using ESP32 Core 1.0.5-. You must install LITTLEFS library
// The library has been merged into esp32 core from release 1.0.6
#include <LITTLEFS.h> // https://github.com/lorol/LITTLEFS
#define FileFS LITTLEFS
#define FS_Name "LittleFS"
#endif
#else
#include "SPIFFS.h"
// ESP32 core 1.0.4 still uses SPIFFS
#define FileFS SPIFFS
#endif
#else
// From ESP8266 core 2.7.1
#include <LittleFS.h>
#if ESP_DRD_USE_LITTLEFS
#define FileFS LittleFS
#else
#define FileFS SPIFFS
#endif
#endif // #if ESP_DRD_USE_EEPROM
#define DRD_FILENAME "/drd.dat"
#endif //#if ESP_DRD_USE_EEPROM
#ifndef DOUBLERESETDETECTOR_DEBUG
#define DOUBLERESETDETECTOR_DEBUG false
#endif
#define DOUBLERESETDETECTOR_FLAG_SET 0xD0D01234
#define DOUBLERESETDETECTOR_FLAG_CLEAR 0xD0D04321
class DoubleResetDetector
{
public:
DoubleResetDetector(int timeout, int address)
{
#if ESP_DRD_USE_EEPROM
#if (DOUBLERESETDETECTOR_DEBUG)
Serial.printf("EEPROM size = %d, start = %d\n", EEPROM_SIZE, EEPROM_START);
#endif
EEPROM.begin(EEPROM_SIZE);
#elif ( ESP_DRD_USE_LITTLEFS || ESP_DRD_USE_SPIFFS )
// LittleFS / SPIFFS code
if (!FileFS.begin())
{
#if (DOUBLERESETDETECTOR_DEBUG)
#if ESP_DRD_USE_LITTLEFS
Serial.println("LittleFS failed!. Please use SPIFFS or EEPROM.");
#else
Serial.println("SPIFFS failed!. Please use LittleFS or EEPROM.");
#endif
#endif
}
#else
#ifdef ESP8266
//RTC only for ESP8266
#endif
#endif
this->timeout = timeout * 1000;
this->address = address;
doubleResetDetected = false;
waitingForDoubleReset = false;
};
bool detectDoubleReset()
{
doubleResetDetected = detectRecentlyResetFlag();
if (doubleResetDetected)
{
#if (DOUBLERESETDETECTOR_DEBUG)
Serial.println("doubleResetDetected");
#endif
clearRecentlyResetFlag();
}
else
{
#if (DOUBLERESETDETECTOR_DEBUG)
Serial.println("No doubleResetDetected");
#endif
setRecentlyResetFlag();
waitingForDoubleReset = true;
}
return doubleResetDetected;
};
void loop()
{
if (waitingForDoubleReset && millis() > timeout)
{
#if (DOUBLERESETDETECTOR_DEBUG)
Serial.println("Stop doubleResetDetecting");
#endif
stop();
}
};
void stop()
{
clearRecentlyResetFlag();
waitingForDoubleReset = false;
};
bool doubleResetDetected;
private:
uint32_t DOUBLERESETDETECTOR_FLAG;
unsigned long timeout;
int address;
bool waitingForDoubleReset;
bool detectRecentlyResetFlag()
{
#if (ESP_DRD_USE_EEPROM)
EEPROM.get(EEPROM_START, DOUBLERESETDETECTOR_FLAG);
doubleResetDetectorFlag = DOUBLERESETDETECTOR_FLAG;
#if (DOUBLERESETDETECTOR_DEBUG)
Serial.printf("EEPROM Flag read = 0x%X\n", DOUBLERESETDETECTOR_FLAG);
#endif
#elif ( ESP_DRD_USE_LITTLEFS || ESP_DRD_USE_SPIFFS )
// LittleFS / SPIFFS code
if (FileFS.exists(DRD_FILENAME))
{
// if config file exists, load
File file = FileFS.open(DRD_FILENAME, "r");
if (!file)
{
#if (DOUBLERESETDETECTOR_DEBUG)
Serial.println("Loading config file failed");
#endif
}
file.readBytes((char *) &DOUBLERESETDETECTOR_FLAG, sizeof(DOUBLERESETDETECTOR_FLAG));
doubleResetDetectorFlag = DOUBLERESETDETECTOR_FLAG;
#if (DOUBLERESETDETECTOR_DEBUG)
#if ESP_DRD_USE_LITTLEFS
Serial.printf("LittleFS Flag read = 0x%X\n", DOUBLERESETDETECTOR_FLAG);
#else
Serial.printf("SPIFFS Flag read = 0x%X\n", DOUBLERESETDETECTOR_FLAG);
#endif
#endif
file.close();
}
#else
#ifdef ESP8266
//RTC only for ESP8266
ESP.rtcUserMemoryRead(address, &doubleResetDetectorFlag, sizeof(doubleResetDetectorFlag));
#endif
#endif
doubleResetDetected = (doubleResetDetectorFlag == DOUBLERESETDETECTOR_FLAG_SET);
return doubleResetDetected;
};
void setRecentlyResetFlag()
{
doubleResetDetectorFlag = DOUBLERESETDETECTOR_FLAG_SET;
DOUBLERESETDETECTOR_FLAG = DOUBLERESETDETECTOR_FLAG_SET;
#if (ESP_DRD_USE_EEPROM)
EEPROM.put(EEPROM_START, DOUBLERESETDETECTOR_FLAG);
EEPROM.commit();
#if (DOUBLERESETDETECTOR_DEBUG)
delay(1000);
EEPROM.get(EEPROM_START, DOUBLERESETDETECTOR_FLAG);
Serial.printf("SetFlag write = 0x%X\n", DOUBLERESETDETECTOR_FLAG);
#endif
#elif ( ESP_DRD_USE_LITTLEFS || ESP_DRD_USE_SPIFFS )
// LittleFS / SPIFFS code
File file = FileFS.open(DRD_FILENAME, "w");
#if (DOUBLERESETDETECTOR_DEBUG)
Serial.println("Saving config file...");
#endif
if (file)
{
file.write((uint8_t *) &DOUBLERESETDETECTOR_FLAG, sizeof(DOUBLERESETDETECTOR_FLAG));
file.close();
#if (DOUBLERESETDETECTOR_DEBUG)
Serial.println("Saving config file OK");
#endif
}
else
{
#if (DOUBLERESETDETECTOR_DEBUG)
Serial.println("Saving config file failed");
#endif
}
#else
#ifdef ESP8266
//RTC only for ESP8266
ESP.rtcUserMemoryWrite(address, &doubleResetDetectorFlag, sizeof(doubleResetDetectorFlag));
#endif
#endif
};
void clearRecentlyResetFlag()
{
doubleResetDetectorFlag = DOUBLERESETDETECTOR_FLAG_CLEAR;
DOUBLERESETDETECTOR_FLAG = DOUBLERESETDETECTOR_FLAG_CLEAR;
#if (ESP_DRD_USE_EEPROM)
//DOUBLERESETDETECTOR_FLAG = DOUBLERESETDETECTOR_FLAG_CLEAR;
EEPROM.put(EEPROM_START, DOUBLERESETDETECTOR_FLAG);
EEPROM.commit();
#if (DOUBLERESETDETECTOR_DEBUG)
delay(1000);
EEPROM.get(EEPROM_START, DOUBLERESETDETECTOR_FLAG);
Serial.printf("ClearFlag write = 0x%X\n", DOUBLERESETDETECTOR_FLAG);
#endif
#elif ( ESP_DRD_USE_LITTLEFS || ESP_DRD_USE_SPIFFS )
// LittleFS / SPIFFS code
File file = FileFS.open(DRD_FILENAME, "w");
#if (DOUBLERESETDETECTOR_DEBUG)
Serial.println("Saving config file...");
#endif
if (file)
{
file.write((uint8_t *) &DOUBLERESETDETECTOR_FLAG, sizeof(DOUBLERESETDETECTOR_FLAG));
file.close();
#if (DOUBLERESETDETECTOR_DEBUG)
Serial.println("Saving config file OK");
#endif
}
else
{
#if (DOUBLERESETDETECTOR_DEBUG)
Serial.println("Saving config file failed");
#endif
}
#else
#ifdef ESP8266
//RTC only for ESP8266
ESP.rtcUserMemoryWrite(address, &doubleResetDetectorFlag, sizeof(doubleResetDetectorFlag));
#endif
#endif
};
uint32_t doubleResetDetectorFlag;
};
#endif // ESP_DoubleResetDetector_H

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,127 @@
/****************************************************************************************************************************
ESP_WiFiManager_Debug.h
For ESP8266 / ESP32 boards
ESP_WiFiManager is a library for the ESP8266/Arduino platform
(https://github.com/esp8266/Arduino) to enable easy
configuration and reconfiguration of WiFi credentials using a Captive Portal
inspired by:
http://www.esp8266.com/viewtopic.php?f=29&t=2520
https://github.com/chriscook8/esp-arduino-apboot
https://github.com/esp8266/Arduino/blob/master/libraries/DNSServer/examples/CaptivePortalAdvanced/
Modified from Tzapu https://github.com/tzapu/WiFiManager
and from Ken Taylor https://github.com/kentaylor
Built by Khoi Hoang https://github.com/khoih-prog/ESP_WiFiManager
Licensed under MIT license
Version: 1.8.0
Version Modified By Date Comments
------- ----------- ---------- -----------
1.0.0 K Hoang 07/10/2019 Initial coding
1.0.1 K Hoang 13/12/2019 Fix bug. Add features. Add support for ESP32
1.0.2 K Hoang 19/12/2019 Fix bug thatkeeps ConfigPortal in endless loop if Portal/Router SSID or Password is NULL.
1.0.3 K Hoang 05/01/2020 Option not displaying AvailablePages in Info page. Enhance README.md. Modify examples
1.0.4 K Hoang 07/01/2020 Add RFC952 setHostname feature.
1.0.5 K Hoang 15/01/2020 Add configurable DNS feature. Thanks to @Amorphous of https://community.blynk.cc
1.0.6 K Hoang 03/02/2020 Add support for ArduinoJson version 6.0.0+ ( tested with v6.14.1 )
1.0.7 K Hoang 13/04/2020 Reduce start time, fix SPIFFS bug in examples, update README.md
1.0.8 K Hoang 10/06/2020 Fix STAstaticIP issue. Restructure code. Add LittleFS support for ESP8266 core 2.7.1+
1.0.9 K Hoang 29/07/2020 Fix ESP32 STAstaticIP bug. Permit changing from DHCP <-> static IP using Config Portal.
Add, enhance examples (fix MDNS for ESP32)
1.0.10 K Hoang 08/08/2020 Add more features to Config Portal. Use random WiFi AP channel to avoid conflict.
1.0.11 K Hoang 17/08/2020 Add CORS feature. Fix bug in softAP, autoConnect, resetSettings.
1.1.0 K Hoang 28/08/2020 Add MultiWiFi feature to autoconnect to best WiFi at runtime
1.1.1 K Hoang 30/08/2020 Add setCORSHeader function to allow flexible CORS. Fix typo and minor improvement.
1.1.2 K Hoang 17/08/2020 Fix bug. Add example.
1.2.0 K Hoang 09/10/2020 Restore cpp code besides Impl.h code to use if linker error. Fix bug.
1.3.0 K Hoang 04/12/2020 Add LittleFS support to ESP32 using LITTLEFS Library
1.4.1 K Hoang 22/12/2020 Fix staticIP not saved. Add functions. Add complex examples. Sync with ESPAsync_WiFiManager
1.4.2 K Hoang 14/01/2021 Fix examples' bug not using saved WiFi Credentials after losing all WiFi connections.
1.4.3 K Hoang 23/01/2021 Fix examples' bug not saving Static IP in certain cases.
1.5.0 K Hoang 12/02/2021 Add support to new ESP32-S2
1.5.1 K Hoang 26/03/2021 Fix compiler error if setting Compiler Warnings to All. Retest with esp32 core v1.0.6
1.5.2 K Hoang 08/04/2021 Fix example misleading messages.
1.5.3 K Hoang 13/04/2021 Add dnsServer error message.
1.6.0 K Hoang 20/04/2021 Add support to new ESP32-C3 using SPIFFS or EEPROM
1.6.1 K Hoang 25/04/2021 Fix MultiWiFi bug. Fix captive-portal bug if CP AP address is not default 192.168.4.1
1.7.0 K Hoang 06/05/2021 Set _timezoneName. Add support to new ESP32-S2 (METRO_ESP32S2, FUNHOUSE_ESP32S2, etc.)
1.7.1 K Hoang 08/05/2021 Fix Json bug. Fix timezoneName not displayed in Info page.
1.7.2 K Hoang 08/05/2021 Fix warnings with ESP8266 core v3.0.0
1.7.3 K Hoang 29/07/2021 Fix MultiWiFi connection issue with ESP32 core v2.0.0-rc1+
1.7.4 K Hoang 13/08/2021 Add WiFi scanning of hidden SSIDs
1.7.5 K Hoang 10/10/2021 Update `platform.ini` and `library.json`
1.7.6 K Hoang 26/11/2021 Auto detect ESP32 core and use either built-in LittleFS or LITTLEFS library
1.7.7 K Hoang 26/11/2021 Fix compile error for ESP32 core v1.0.5-
1.7.8 K Hoang 30/11/2021 Fix bug to permit using HTTP port different from 80. Fix bug
1.8.0 K Hoang 29/12/2021 Fix `multiple-definitions` linker error and weird bug related to src_cpp
*****************************************************************************************************************************/
#pragma once
#ifndef ESP_WiFiManager_Debug_H
#define ESP_WiFiManager_Debug_H
#ifdef WIFIMGR_DEBUG_PORT
#define WM_DBG_PORT WIFIMGR_DEBUG_PORT
#else
#define WM_DBG_PORT Serial
#endif
// Change _WIFIMGR_LOGLEVEL_ to set tracing and logging verbosity
// 0: DISABLED: no logging
// 1: ERROR: errors
// 2: WARN: errors and warnings
// 3: INFO: errors, warnings and informational (default)
// 4: DEBUG: errors, warnings, informational and debug
#ifndef _WIFIMGR_LOGLEVEL_
#define _WIFIMGR_LOGLEVEL_ 0
#endif
const char WM_MARK[] = "[WM] ";
const char WM_SP[] = " ";
#define WM_PRINT WM_DBG_PORT.print
#define WM_PRINTLN WM_DBG_PORT.println
#define WM_PRINT_MARK WM_PRINT(WM_MARK)
#define WM_PRINT_SP WM_PRINT(WM_SP)
////////////////////////////////////////////////////
#define LOGERROR(x) if(_WIFIMGR_LOGLEVEL_>0) { WM_PRINT_MARK; WM_PRINTLN(x); }
#define LOGERROR0(x) if(_WIFIMGR_LOGLEVEL_>0) { WM_PRINT(x); }
#define LOGERROR1(x,y) if(_WIFIMGR_LOGLEVEL_>0) { WM_PRINT_MARK; WM_PRINT(x); WM_PRINT_SP; WM_PRINTLN(y); }
#define LOGERROR2(x,y,z) if(_WIFIMGR_LOGLEVEL_>0) { WM_PRINT_MARK; WM_PRINT(x); WM_PRINT_SP; WM_PRINT(y); WM_PRINT_SP; WM_PRINTLN(z); }
#define LOGERROR3(x,y,z,w) if(_WIFIMGR_LOGLEVEL_>0) { WM_PRINT_MARK; WM_PRINT(x); WM_PRINT_SP; WM_PRINT(y); WM_PRINT_SP; WM_PRINT(z); WM_PRINT_SP; WM_PRINTLN(w); }
////////////////////////////////////////////////////
#define LOGWARN(x) if(_WIFIMGR_LOGLEVEL_>1) { WM_PRINT_MARK; WM_PRINTLN(x); }
#define LOGWARN0(x) if(_WIFIMGR_LOGLEVEL_>1) { WM_PRINT(x); }
#define LOGWARN1(x,y) if(_WIFIMGR_LOGLEVEL_>1) { WM_PRINT_MARK; WM_PRINT(x); WM_PRINT_SP; WM_PRINTLN(y); }
#define LOGWARN2(x,y,z) if(_WIFIMGR_LOGLEVEL_>1) { WM_PRINT_MARK; WM_PRINT(x); WM_PRINT_SP; WM_PRINT(y); WM_PRINT_SP; WM_PRINTLN(z); }
#define LOGWARN3(x,y,z,w) if(_WIFIMGR_LOGLEVEL_>1) { WM_PRINT_MARK; WM_PRINT(x); WM_PRINT_SP; WM_PRINT(y); WM_PRINT_SP; WM_PRINT(z); WM_PRINT_SP; WM_PRINTLN(w); }
////////////////////////////////////////////////////
#define LOGINFO(x) if(_WIFIMGR_LOGLEVEL_>2) { WM_PRINT_MARK; WM_PRINTLN(x); }
#define LOGINFO0(x) if(_WIFIMGR_LOGLEVEL_>2) { WM_PRINT(x); }
#define LOGINFO1(x,y) if(_WIFIMGR_LOGLEVEL_>2) { WM_PRINT_MARK; WM_PRINT(x); WM_PRINT_SP; WM_PRINTLN(y); }
#define LOGINFO2(x,y,z) if(_WIFIMGR_LOGLEVEL_>2) { WM_PRINT_MARK; WM_PRINT(x); WM_PRINT_SP; WM_PRINT(y); WM_PRINT_SP; WM_PRINTLN(z); }
#define LOGINFO3(x,y,z,w) if(_WIFIMGR_LOGLEVEL_>2) { WM_PRINT_MARK; WM_PRINT(x); WM_PRINT_SP; WM_PRINT(y); WM_PRINT_SP; WM_PRINT(z); WM_PRINT_SP; WM_PRINTLN(w); }
////////////////////////////////////////////////////
#define LOGDEBUG(x) if(_WIFIMGR_LOGLEVEL_>3) { WM_PRINT_MARK; WM_PRINTLN(x); }
#define LOGDEBUG0(x) if(_WIFIMGR_LOGLEVEL_>3) { WM_PRINT(x); }
#define LOGDEBUG1(x,y) if(_WIFIMGR_LOGLEVEL_>3) { WM_PRINT_MARK; WM_PRINT(x); WM_PRINT_SP; WM_PRINTLN(y); }
#define LOGDEBUG2(x,y,z) if(_WIFIMGR_LOGLEVEL_>3) { WM_PRINT_MARK; WM_PRINT(x); WM_PRINT_SP; WM_PRINT(y); WM_PRINT_SP; WM_PRINTLN(z); }
#define LOGDEBUG3(x,y,z,w) if(_WIFIMGR_LOGLEVEL_>3) { WM_PRINT_MARK; WM_PRINT(x); WM_PRINT_SP; WM_PRINT(y); WM_PRINT_SP; WM_PRINT(z); WM_PRINT_SP; WM_PRINTLN(w); }
////////////////////////////////////////////////////
#endif //ESP_WiFiManager_Debug_H

File diff suppressed because it is too large Load Diff

View File

@ -15,13 +15,12 @@ include_dir = lib
[common_env_data] [common_env_data]
upload_speed = 921600 upload_speed = 921600
monitor_speed = 115200 monitor_speed = 115200
#platform = espressif8266 @ 2.6.3
platform = espressif8266 @ 3.2.0 platform = espressif8266 @ 3.2.0
framework = arduino framework = arduino
board = d1_mini board = d1_mini
build_unflags = build_unflags =
#src_build_flags = -Wunused-variable -Wregister -Wchar-subscripts
build_flags = build_flags =
-Wl,-Map,output.map
-D BAUD=${common_env_data.monitor_speed} -D BAUD=${common_env_data.monitor_speed}
-D ACTIVATE_OTA -D ACTIVATE_OTA
#-D USE_GYRO_TEMP # If this is enabled the DS18 will not be used, temp is read from the gyro. #-D USE_GYRO_TEMP # If this is enabled the DS18 will not be used, temp is read from the gyro.
@ -45,11 +44,11 @@ build_flags =
-D CFG_APPVER="\"0.5.0\"" -D CFG_APPVER="\"0.5.0\""
lib_deps = # Switched to forks for better version control. lib_deps = # Switched to forks for better version control.
# Using local copy of this library # Using local copy of this library
#https://github.com/mp-se/i2cdevlib # https://github.com/jrowberg/i2cdevlib.git #https://github.com/jrowberg/i2cdevlib.git#<document>
#https://github.com/khoih-prog/ESP_WiFiManager#<document>
#https://github.com/khoih-prog/ESP_DoubleResetDetector#<document>
https://github.com/mp-se/tinyexpr # https://github.com/codeplea/tinyexpr https://github.com/mp-se/tinyexpr # https://github.com/codeplea/tinyexpr
https://github.com/mp-se/incbin # https://github.com/graphitemaster/incbin https://github.com/mp-se/incbin # https://github.com/graphitemaster/incbin
https://github.com/mp-se/ESP_DoubleResetDetector#v1.2.1 # https://github.com/khoih-prog/ESP_DoubleResetDetector
https://github.com/mp-se/WiFiManager#2.0.5-beta # https://github.com/tzapu/WiFiManager
https://github.com/mp-se/Arduino-Log#1.1.1 # https://github.com/thijse/Arduino-Log https://github.com/mp-se/Arduino-Log#1.1.1 # https://github.com/thijse/Arduino-Log
https://github.com/mp-se/ArduinoJson#v6.18.5 # https://github.com/bblanchon/ArduinoJson https://github.com/mp-se/ArduinoJson#v6.18.5 # https://github.com/bblanchon/ArduinoJson
https://github.com/mp-se/OneWire#v2.3.6 # https://github.com/PaulStoffregen/OneWire https://github.com/mp-se/OneWire#v2.3.6 # https://github.com/PaulStoffregen/OneWire
@ -68,7 +67,7 @@ extra_scripts =
build_unflags = build_unflags =
${common_env_data.build_unflags} ${common_env_data.build_unflags}
build_flags = build_flags =
#-D PIO_FRAMEWORK_ARDUINO_ENABLE_EXCEPTIONS -D PIO_FRAMEWORK_ARDUINO_ENABLE_EXCEPTIONS
#-D SKIP_SLEEPMODE #-D SKIP_SLEEPMODE
${common_env_data.build_flags} ${common_env_data.build_flags}
-D COLLECT_PERFDATA # This option will collect runtime data for a few defined methods to measure time, dumped to serial and/or influxdb -D COLLECT_PERFDATA # This option will collect runtime data for a few defined methods to measure time, dumped to serial and/or influxdb

View File

@ -32,13 +32,6 @@ SOFTWARE.
#include <webserver.hpp> #include <webserver.hpp>
#include <wifi.hpp> #include <wifi.hpp>
// Settings for double reset detector.
#define ESP_DRD_USE_LITTLEFS true
#define DRD_TIMEOUT 2
#define DRD_ADDRESS 0
#include <ESP_DoubleResetDetector.h>
extern DoubleResetDetector *drd; // Declared in WifiManager_Lite
// Define constats for this program // Define constats for this program
#ifdef DEACTIVATE_SLEEPMODE #ifdef DEACTIVATE_SLEEPMODE
const int interval = 1000; // ms, time to wait between changes to output const int interval = 1000; // ms, time to wait between changes to output
@ -105,8 +98,6 @@ void setup() {
LOG_PERF_START("main-setup"); LOG_PERF_START("main-setup");
runtimeMillis = millis(); runtimeMillis = millis();
drd = new DoubleResetDetector(DRD_TIMEOUT, DRD_ADDRESS);
bool dt = drd->detectDoubleReset();
#if LOG_LEVEL == 6 && !defined(MAIN_DISABLE_LOGGING) #if LOG_LEVEL == 6 && !defined(MAIN_DISABLE_LOGGING)
delay(3000); // Wait a few seconds when using debug version so that serial is delay(3000); // Wait a few seconds when using debug version so that serial is
// started. // started.
@ -126,18 +117,15 @@ void setup() {
ESP.wdtDisable(); ESP.wdtDisable();
ESP.wdtEnable(5000); // 5 seconds ESP.wdtEnable(5000); // 5 seconds
if (dt) { // No stored config, move to portal
Log.notice(F("Main: Detected doubletap on reset. Reset reason=%s" CR), if( !myWifi.hasConfig() ) {
ESP.getResetReason().c_str()); Log.notice(F("Main: No wifi configuration detected, entering wifi setup." CR));
runMode = RunMode::wifiSetupMode;
} }
#ifdef SKIP_SLEEPMODE // Double reset, go to portal.
// If we are running in debug more we skip this part. makes is hard to debug if( myWifi.isDoubleResetDetected() ) {
// in case of crash/watchdog reset Log.notice(F("Main: Double reset detected, entering wifi setup." CR));
dt = false;
#endif
if( !myWifi.hasConfig() ) {
runMode = RunMode::wifiSetupMode; runMode = RunMode::wifiSetupMode;
} }
@ -145,7 +133,6 @@ void setup() {
switch (runMode) { switch (runMode) {
case RunMode::wifiSetupMode: case RunMode::wifiSetupMode:
myWifi.startPortal(); myWifi.startPortal();
Log.notice(F("Main: No wifi configuration detected, running in wifiSetupMode." CR));
break; break;
default: default:
@ -274,7 +261,6 @@ void goToSleep(int sleepInterval) {
sleepInterval, (millis() - runtimeMillis) / 1000, volt); sleepInterval, (millis() - runtimeMillis) / 1000, volt);
LittleFS.end(); LittleFS.end();
myGyro.enterSleep(); myGyro.enterSleep();
drd->stop();
LOG_PERF_STOP("run-time"); LOG_PERF_STOP("run-time");
LOG_PERF_PUSH(); LOG_PERF_PUSH();
delay(100); delay(100);
@ -285,11 +271,12 @@ void goToSleep(int sleepInterval) {
// Main loops // Main loops
// //
void loop() { void loop() {
drd->loop(); // myDRD->loop();
switch (runMode) { switch (runMode) {
case RunMode::configurationMode: case RunMode::configurationMode:
myWebServer.loop(); myWebServer.loop();
myWifi.loop();
loopGravityOnInterval(); loopGravityOnInterval();
break; break;
@ -298,26 +285,31 @@ void loop() {
// conserve battery. // conserve battery.
if (!myWifi.isConnected()) { // no connection to wifi if (!myWifi.isConnected()) { // no connection to wifi
Log.notice(F("MAIN: No connection to wifi established, sleeping for 60s." CR)); Log.notice(F("MAIN: No connection to wifi established, sleeping for 60s." CR));
myWifi.stopDoubleReset();
goToSleep(60); goToSleep(60);
} }
if( loopReadGravity() ) if( loopReadGravity() ) {
myWifi.stopDoubleReset();
goToSleep(myConfig.getSleepInterval()); goToSleep(myConfig.getSleepInterval());
}
// If the sensor is moving and we are not getting a clear reading, we enter // If the sensor is moving and we are not getting a clear reading, we enter
// sleep for a short time to conserve battery. // sleep for a short time to conserve battery.
if (((millis() - stableGyroMillis) > 10000L)) { // 10s since last stable gyro reading if (((millis() - stableGyroMillis) > 10000L)) { // 10s since last stable gyro reading
Log.notice(F("MAIN: Unable to get a stable reading for 10s, sleeping for 60s." CR)); Log.notice(F("MAIN: Unable to get a stable reading for 10s, sleeping for 60s." CR));
myWifi.stopDoubleReset();
goToSleep(60); goToSleep(60);
} }
LOG_PERF_START("loop-gyro-read"); LOG_PERF_START("loop-gyro-read");
myGyro.read(); myGyro.read();
LOG_PERF_STOP("loop-gyro-read"); LOG_PERF_STOP("loop-gyro-read");
myWifi.loop();
break; break;
case RunMode::wifiSetupMode: case RunMode::wifiSetupMode:
myWifi.portalLoop(); myWifi.loop();
break; break;
} }
} }

View File

@ -21,12 +21,12 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
*/ */
#include <ArduinoJson.h> #include <wifi.hpp>
#include <ArduinoJson.hpp>
#include <ESP8266HTTPClient.h> #include <ESP8266HTTPClient.h>
#include <ESP8266httpUpdate.h> #include <ESP8266httpUpdate.h>
#include <ESP8266mDNS.h> //#include <ESP8266mDNS.h>
#include <LittleFS.h> #include <LittleFS.h>
#include <ESP_WiFiManager_Lite.h>
#include <incbin.h> #include <incbin.h>
#include <calc.hpp> #include <calc.hpp>
@ -34,91 +34,153 @@ SOFTWARE.
#include <gyro.hpp> #include <gyro.hpp>
#include <helper.hpp> #include <helper.hpp>
#include <tempsensor.hpp> #include <tempsensor.hpp>
#include <wifi.hpp>
Wifi myWifi; /*
// Configuration settings for WifiManager_Lite
#define ESP_WM_LITE_DEBUG_OUTPUT Serial
#define _ESP_WM_LITE_LOGLEVEL_ 3
#define MULTIRESETDETECTOR_DEBUG true
#define USE_DYNAMIC_PARAMETERS false
#define CONFIG_TIMEOUT 120*1000
#define USING_MRD false // We use DRD instead
#define REQUIRE_ONE_SET_SSID_PW true
#include <ESP_WiFiManager_Lite.h>
bool LOAD_DEFAULT_CONFIG_DATA = false;
ESP_WiFiManager_Lite* wifiManager = 0;
ESP_WM_LITE_Configuration defaultConfig;
*/
// Settings for DRD
#define ESP_DRD_USE_LITTLEFS true
#define ESP_DRD_USE_SPIFFS false
#define ESP_DRD_USE_EEPROM false
#define DOUBLERESETDETECTOR_DEBUG true
#include <ESP_DoubleResetDetector.h>
#define DRD_TIMEOUT 3
#define DRD_ADDRESS 0
// Settings for WIFI Manager
/*#define USING_AFRICA false
#define USING_AMERICA true
#define USING_ANTARCTICA false
#define USING_ASIA false
#define USING_ATLANTIC false
#define USING_AUSTRALIA false
#define USING_EUROPE true
#define USING_INDIAN false
#define USING_PACIFIC false
#define USING_ETC_GMT false
#define USE_CLOUDFLARE_NTP false
#define CONFIG_FILENAME F("/wifi_cred.dat")*/
#define USE_ESP_WIFIMANAGER_NTP false
#define USE_CLOUDFLARE_NTP false
#define USING_CORS_FEATURE false
#define NUM_WIFI_CREDENTIALS 1
#define USE_STATIC_IP_CONFIG_IN_CP false
#include <ESP_WiFiManager.h>
const char WM_HTTP_FORM_START[] PROGMEM = "<form method='get' action='wifisave'><fieldset><div><label>SSID</label><input id='s' name='s' length=32 placeholder='SSID'><div></div></div><div><label>Password</label><input id='p' name='p' length=64 placeholder='password'><div></div></div><div hidden><label>SSID1</label><input id='s1' name='s1' length=32 placeholder='SSID1'><div></div></div><div hidden><label>Password</label><input id='p1' name='p1' length=64 placeholder='password1'><div></div></div></fieldset>";
#include <ESP_WiFiManager-Impl.h>
ESP_WiFiManager* myWifiManager;
DoubleResetDetector* myDRD;
WifiConnection myWifi;
const char *userSSID = USER_SSID; const char *userSSID = USER_SSID;
const char *userPWD = USER_SSID_PWD; const char *userPWD = USER_SSID_PWD;
const int PIN_LED = 2;
//
// Constructor
//
WifiConnection::WifiConnection() {
myDRD = new DoubleResetDetector(DRD_TIMEOUT, DRD_ADDRESS);
}
// //
// Check if we have a valid wifi configuration // Check if we have a valid wifi configuration
// //
bool Wifi::hasConfig() { bool WifiConnection::hasConfig() {
if (strlen(myConfig.getWifiSSID()) ) return true; if (strlen(myConfig.getWifiSSID()) ) return true;
if (strlen(userSSID) ) return true; if (strlen(userSSID) ) return true;
return false; return false;
} }
//
// Check if the wifi is connected
//
bool WifiConnection::isConnected() {
return WiFi.status() == WL_CONNECTED;
}
//
// Get the IP adress
//
String WifiConnection::getIPAddress() {
return WiFi.localIP().toString();
}
//
// Additional method to detect double reset.
//
bool WifiConnection::isDoubleResetDetected() {
if (myDRD->detectDoubleReset()) {
Log.notice(F("WIFI: Double reset has been detected." CR));
return true;
}
return false;
}
//
// Stop double reset detection
//
void WifiConnection::stopDoubleReset() {
myDRD->stop();
}
// //
// Start the wifi manager // Start the wifi manager
// //
bool Wifi::startPortal() { void WifiConnection::startPortal() {
Log.notice(F("WIFI: Starting Wifi config portal." CR)); Log.notice(F("WIFI: Starting Wifi config portal." CR));
return true;
pinMode(PIN_LED, OUTPUT);
digitalWrite(PIN_LED, LOW);
myWifiManager = new ESP_WiFiManager(WIFI_MDNS);
myWifiManager->setMinimumSignalQuality(-1);
myWifiManager->setConfigPortalChannel(0);
myWifiManager->setConfigPortalTimeout(120);
if (myWifiManager->startConfigPortal(WIFI_DEFAULT_SSID, WIFI_DEFAULT_PWD)) {
Log.notice(F("WIFI: Exited portal, connected to wifi." CR));
myConfig.setWifiSSID(myWifiManager->getSSID());
myConfig.setWifiPass(myWifiManager->getPW());
myConfig.saveFile();
}
else {
Log.notice(F("WIFI: Exited portal, no connection to wifi." CR)); Serial.println(F("Not connected to WiFi"));
}
stopDoubleReset();
delay(500);
ESP.reset();
} }
// //
// Call the wifi manager in loop // Call the wifi manager in loop
// //
void Wifi::portalLoop() { void WifiConnection::loop() {
myDRD->loop();
} }
// //
// Connect to last known access point or create one if connection is not // Connect to last known access point or create one if connection is not
// working. // working.
// //
// REMOVE bool Wifi::connect(bool showPortal) { bool WifiConnection::connect() {
bool Wifi::connect() {
WiFi.persistent(true);
WiFi.mode(WIFI_STA);
/* REMOVE
if (!strlen(myConfig.getWifiSSID())) {
Log.info(
F("WIFI: No SSID seams to be stored, forcing portal to start." CR));
showPortal = true;
} else {
// Log.info(F("WIFI: Using SSID=%s and %s." CR), myConfig.getWifiSSID(),
// myConfig.getWifiPass()); Log.info(F("WIFI: Using SSID=%s and %s." CR),
// myConfig.getWifiSSID(), "*****");
}
if (strlen(userSSID) == 0 && showPortal) {
#if LOG_LEVEL == 6
Log.verbose(
F("WIFI: Connecting to WIFI via connection manager (portal=%s)." CR),
showPortal ? "true" : "false");
#endif
WiFiManager myWifiManager;
Log.notice(F("WIFI: Starting wifi portal." CR));
myWifiManager.setDebugOutput(true);
myWifiManager.setClass("invert");
myWifiManager.setConfigPortalTimeout(120); // Keep it open for 120 seconds
bool f =
myWifiManager.startConfigPortal(WIFI_DEFAULT_SSID, WIFI_DEFAULT_PWD);
if (f) {
// Log.notice(F("WIFI: Success got values from WIFI portal=%s,%s." CR),
// myWifiManager.getWiFiSSID(), myWifiManager.getWiFiPass() );
Log.notice(F("WIFI: Success got values from WIFI portal=%s,%s." CR),
myWifiManager.getWiFiSSID(), "*****");
myConfig.setWifiSSID(myWifiManager.getWiFiSSID());
myConfig.setWifiPass(myWifiManager.getWiFiPass());
myConfig.saveFile();
} else {
Log.notice(F("WIFI: Failure from WIFI portal, rebooting." CR));
delay(200);
ESP.reset();
}
}
*/
// Connect to wifi // Connect to wifi
int i = 0; int i = 0;
// Log.notice(F("WIFI: Connecting to WIFI, mode=%d,persistent=%d,fhy=%d ."
// CR), WiFi.getMode(), WiFi.getPersistent(), WiFi.getPhyMode() );
WiFi.mode(WIFI_STA); WiFi.mode(WIFI_STA);
if (strlen(userSSID)) { if (strlen(userSSID)) {
Log.notice(F("WIFI: Connecting to wifi using hardcoded settings %s." CR), Log.notice(F("WIFI: Connecting to wifi using hardcoded settings %s." CR),
@ -140,21 +202,22 @@ bool Wifi::connect() {
Log.error(F("WIFI: Failed to connect to wifi %d, aborting %s." CR), Log.error(F("WIFI: Failed to connect to wifi %d, aborting %s." CR),
WiFi.status(), getIPAddress().c_str()); WiFi.status(), getIPAddress().c_str());
WiFi.disconnect(); WiFi.disconnect();
return connectedFlag; // Return to main that we have failed to connect.
}
}
Serial.print(CR); Serial.print(CR);
connectedFlag = true; return false; // Return to main that we have failed to connect.
}
}
Serial.print(CR);
Log.notice(F("WIFI: Connected to wifi ip=%s." CR), getIPAddress().c_str()); Log.notice(F("WIFI: Connected to wifi ip=%s." CR), getIPAddress().c_str());
Log.notice(F("WIFI: Using mDNS name %s." CR), myConfig.getMDNS()); Log.notice(F("WIFI: Using mDNS name %s." CR), myConfig.getMDNS());
return connectedFlag; return true;
} }
// //
// This will erase the stored credentials and forcing the WIFI manager to AP // This will erase the stored credentials and forcing the WIFI manager to AP
// mode. // mode.
// //
bool Wifi::disconnect() { bool WifiConnection::disconnect() {
Log.notice(F("WIFI: Erasing stored WIFI credentials." CR)); Log.notice(F("WIFI: Erasing stored WIFI credentials." CR));
// Erase WIFI credentials // Erase WIFI credentials
return WiFi.disconnect(true); return WiFi.disconnect(true);
@ -165,7 +228,7 @@ bool Wifi::disconnect() {
// //
// //
// //
bool Wifi::updateFirmware() { bool WifiConnection::updateFirmware() {
if (!newFirmware) { if (!newFirmware) {
Log.notice(F("WIFI: No newer version exist, skipping update." CR)); Log.notice(F("WIFI: No newer version exist, skipping update." CR));
return false; return false;
@ -200,7 +263,7 @@ bool Wifi::updateFirmware() {
// //
// Download and save file // Download and save file
// //
void Wifi::downloadFile(const char *fname) { void WifiConnection::downloadFile(const char *fname) {
#if LOG_LEVEL == 6 #if LOG_LEVEL == 6
Log.verbose(F("WIFI: Download file %s." CR), fname); Log.verbose(F("WIFI: Download file %s." CR), fname);
#endif #endif
@ -228,7 +291,7 @@ void Wifi::downloadFile(const char *fname) {
// //
// Check what firmware version is available over OTA // Check what firmware version is available over OTA
// //
bool Wifi::checkFirmwareVersion() { bool WifiConnection::checkFirmwareVersion() {
#if LOG_LEVEL == 6 #if LOG_LEVEL == 6
Log.verbose(F("WIFI: Checking if new version exist." CR)); Log.verbose(F("WIFI: Checking if new version exist." CR));
#endif #endif
@ -309,7 +372,7 @@ bool Wifi::checkFirmwareVersion() {
// //
// Parse a version string in the format M.m.p (eg. 1.2.10) // Parse a version string in the format M.m.p (eg. 1.2.10)
// //
bool Wifi::parseFirmwareVersionString(int (&num)[3], const char *version) { bool WifiConnection::parseFirmwareVersionString(int (&num)[3], const char *version) {
#if LOG_LEVEL == 6 #if LOG_LEVEL == 6
Log.verbose(F("WIFI: Parsing version number string %s." CR), version); Log.verbose(F("WIFI: Parsing version number string %s." CR), version);
#endif #endif

View File

@ -25,13 +25,13 @@ SOFTWARE.
#define SRC_WIFI_HPP_ #define SRC_WIFI_HPP_
// Include // Include
#include <ESP8266WiFi.h> //#include <ESP8266WiFi.h>
#include <Arduino.h>
// classes // classes
class Wifi { class WifiConnection {
private: private:
// WIFI // WIFI
bool connectedFlag = false;
// OTA // OTA
bool newFirmware = false; bool newFirmware = false;
@ -40,13 +40,16 @@ class Wifi {
public: public:
// WIFI // WIFI
WifiConnection();
bool connect(); bool connect();
bool disconnect(); bool disconnect();
bool isConnected() { return connectedFlag; } bool isConnected();
bool isDoubleResetDetected();
void stopDoubleReset();
bool hasConfig(); bool hasConfig();
String getIPAddress() { return WiFi.localIP().toString(); } String getIPAddress();
bool startPortal(); void startPortal();
void portalLoop(); void loop();
// OTA // OTA
bool updateFirmware(); bool updateFirmware();
@ -54,7 +57,7 @@ class Wifi {
}; };
// Global instance created // Global instance created
extern Wifi myWifi; extern WifiConnection myWifi;
#endif // SRC_WIFI_HPP_ #endif // SRC_WIFI_HPP_