├── documentation ├── ui.png ├── flow-diagram.png └── wifimanager.drawio.xml ├── examples ├── .gitignore ├── .vscode │ └── extensions.json ├── partitions.csv ├── platformio.ini └── src │ └── main.cpp ├── .vscode └── settings.json ├── .gitignore ├── library.properties ├── library.json ├── README.md ├── wifimanager.h ├── LICENSE └── wifimanager.cpp /documentation/ui.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MartinVerges/esp32-wifi-manager/HEAD/documentation/ui.png -------------------------------------------------------------------------------- /documentation/flow-diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MartinVerges/esp32-wifi-manager/HEAD/documentation/flow-diagram.png -------------------------------------------------------------------------------- /examples/.gitignore: -------------------------------------------------------------------------------- 1 | .pio 2 | .vscode/.browse.c_cpp.db* 3 | .vscode/c_cpp_properties.json 4 | .vscode/launch.json 5 | .vscode/ipch 6 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "string": "cpp", 4 | "bitset": "cpp", 5 | "string_view": "cpp", 6 | "regex": "cpp" 7 | } 8 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Temporary and development files 2 | *.patch 3 | *_patch.cpp 4 | *_validation_*.cpp 5 | *.tmp 6 | *.bak 7 | 8 | # IDE files 9 | .vscode/settings.json 10 | 11 | # Build artifacts 12 | build/ 13 | .pio/ 14 | *.bin 15 | *.elf 16 | *.map 17 | -------------------------------------------------------------------------------- /examples/.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | // See http://go.microsoft.com/fwlink/?LinkId=827846 3 | // for the documentation about the extensions.json format 4 | "recommendations": [ 5 | "platformio.platformio-ide" 6 | ], 7 | "unwantedRecommendations": [ 8 | "ms-vscode.cpptools-extension-pack" 9 | ] 10 | } 11 | -------------------------------------------------------------------------------- /examples/partitions.csv: -------------------------------------------------------------------------------- 1 | # Name, Type, SubType, Offset, Size, Flags 2 | nvs, data, nvs, 0x9000, 0x4000, 3 | otadata, data, ota, 0xd000, 0x2000, 4 | phy_init, data, phy, 0xf000, 0x1000, 5 | app0, app, ota_0, 0x10000, 1536K, 6 | app1, app, ota_1, 0x190000, 1536K, 7 | spiffs, data, spiffs, 0x310000, 704K, 8 | coredump, data, coredump,0x3c0000, 64K, 9 | -------------------------------------------------------------------------------- /library.properties: -------------------------------------------------------------------------------- 1 | name=ESP32_Wifi_Manager 2 | version=1.5.0 3 | author=Martin Verges 4 | maintainer=Martin Verges 5 | sentence=Wifi manager for ESP32 devices 6 | paragraph=A multi wifi manager for arduino based ESP applications, with extensive RESTful API, and configuration stored on non volatile memory. 7 | url=https://github.com/MartinVerges/esp32-wifi-manager 8 | architectures=esp32 9 | includes=wifimanager.h 10 | depends=ArduinoJson 11 | -------------------------------------------------------------------------------- /library.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ESP32 Wifi Manager", 3 | "version": "1.5.0", 4 | "description": "A multi wifi manager for arduino based ESP applications, with extensive RESTful API, and configuration stored on non volatile memory.", 5 | "keywords": "esp32, wifi, ap, softap, sta, restful, api, manager, arduino", 6 | "repository": 7 | { 8 | "type": "git", 9 | "url": "https://github.com/MartinVerges/esp32-wifi-manager" 10 | }, 11 | "authors": 12 | [ 13 | { 14 | "name": "Martin Verges", 15 | "email": "martin@verges.cc", 16 | "maintainer": true 17 | } 18 | ], 19 | "license": "CC-BY-NC-SA-4.0", 20 | "dependencies": { 21 | "bblanchon/ArduinoJson": "^7.3.0" 22 | }, 23 | "frameworks": "arduino", 24 | "platforms": "espressif32" 25 | } 26 | -------------------------------------------------------------------------------- /examples/platformio.ini: -------------------------------------------------------------------------------- 1 | ; PlatformIO Project Configuration File 2 | 3 | [platformio] 4 | description = ESP32 Wifi Manager example 5 | 6 | [env] 7 | framework = arduino 8 | platform = espressif32 9 | platform_packages = framework-arduinoespressif32 10 | 11 | upload_speed = 921600 12 | 13 | monitor_speed = 115200 14 | monitor_rts = 0 15 | monitor_dtr = 0 16 | monitor_filters = 17 | esp32_exception_decoder 18 | default 19 | colorize 20 | time 21 | 22 | board_build.partitions = partitions.csv 23 | 24 | lib_deps = 25 | ESP32Async/ESPAsyncWebServer@^3.7.10 26 | https://github.com/MartinVerges/esp32-wifi-manager.git 27 | # martinverges/ESP32 Wifi Manager 28 | 29 | build_flags = 30 | -std=c++17 31 | -std=gnu++17 32 | -DCORE_DEBUG_LEVEL=1 33 | -Wall 34 | # -DDEBUG_ESP_PORT=Serial 35 | # -DDEBUG_ESP_DNS=1 36 | # -O0 # no optimization, better for debugging 37 | # -ggdb3 # add debug symbols 38 | # -g3 # add debug symbols for other debuggers than gdb 39 | # -DASYNC_WEBSERVER=true 40 | 41 | [env:wemos_d1_mini32] 42 | board = wemos_d1_mini32 43 | board_build.mcu = esp32 44 | 45 | 46 | -------------------------------------------------------------------------------- /documentation/wifimanager.drawio.xml: -------------------------------------------------------------------------------- 1 | 7Vxbd6o4FP41rjXz0C4uAvJYbW2dOaftGdvp6dOsqFEZI/FAvM2vn0SCQEIFLGhb7YMlcZOE7P3t/WUnWNNb09WtB2bj73gAUU1TBquafl3TNLuh0k9WsQ4qDL0eVIw8ZxBUqVFF1/kP8kqF186dAfQTggRjRJxZsrKPXRf2SaIOeB5eJsWGGCV7nYERlCq6fYDk2hdnQMZBbUOzovo76IzGYc+qaQffTEEozJ/EH4MBXsaq9Jua3vIwJsHVdNWCiM1dOC8vnfUL+jYxb//44f8Cz80/n+7/vggaaxe5ZfsIHnRJuU1rQdMLgOZ8vvizknU4gR6euwPIGlFqenNMpoheqvTyX0jImisczAmmVdgjYzzCLkDfMJ5xuSF2CRdTWRm6gyumWFruIdyfBFVtByHeBy1x+QYt+cTDk63uWANbRTBhBHoQNUF/MtoMtIUR9uhXLnYha2pAjYE/SzS4m6i2mXNuuQ58PPf6cIeczk0ceCO4qz0zkGPji9kp19wtxFNIvDUV8CACxFkkjRlwTIy2cpHe6QVXfQEz0CUzeMRL6NGqh/sdBsGUsRw7BHZnYDMrS+pCkkYSVz59vuYIAd/nqsvQbDHNLKBH4GrnXIbfmhzQ3KM1eHEZuQc1xPw45hrqSkWzX5dm/5V6zDMO34NDMycOwzCVCURuLKFh5MYlb+kRO/S5IhE8HPp0YKLpbDvc35oMyZrusWRM2fr41OZ2JGOyitmS+uFtyZRsqdvtXAdsbeiM5h4dN3Y3poU9Zixt2W2N8bQ397MjRUK9zHjaYOogNlV3EC0gcfogJZ4A5IxcWuhTTdOAlWo3tEvHHdGSGZWeNnZKXW+FccZKxpltOR5olJRA06gq0FiyOqlNM1O6eqxpJqL9N3s06psjdvXbPZhSsSv69U338Z+f7O/3L8cGdE3Qkp2iJfOQdKBxpgOle/DQ1WbzATWnD+fmc6FcNgxLTZjQx+cI9pkjHM/CtK/GEsIRxszpwUXsEegoFYExUHM5U4S3KIKWFnwOShFC/xfTZYtn5ljijn2MIf2cuHjJiN9Lp92h/+4hWWJv8uXYgZgrMNRjJwtC95FC4rguun3ghsoaOi7Fm9KD/sYVLIBDnSJiCsSzgLp/MYWJdE5PU1hVdO7Z+NUhw4cLAiz96bu9UJt35oXsHE+Ny8GVQ36yti4NXnrl3bDr61U4JlZYbwdI5z52Eyu+xr+LbtuU1nvZVXZU1+SonqrlvEGdm6lyqdhqkjVeVBfoIxnevaYLcccUrD+YGH7XjobqItxsoaFg4qSG9qAeqdMuR6tTBZcag1YEtA8NLisnthpFsaXZDf1o2KqrAiT2xZYp5o/Eht7AFjVOsI6JzZiAn/JQYT8NwRmoiY1EehG0WCpwZRbTii0QwkXDkEHinFVMEBwjqa26csAlQ6oq5c3DE8xXvYvjqAknfKkZlfnhXVisJDdmGVrSE1eXHKuO5ehCQ4Z2WJYjbxCnpOtOBGBl8Bz16PhKlTOKw8uwkvA6IM+xLDEQGfuhyxDQpYuRqiSeYwi5nHr9ADxH3o1vA4R6FAfyhtsmY+PjIUnbjYMuS9ycyVACAobAtQ+aP03Vt7xjfno7K2/xmixas+VQBVx8ya7ayEuFCuZ7qK/W6V+SCh1yUSpuNFh7UiFDy2ioYiokH2E4LzZCqHwGLpQXYHmPUkX4shX7aFyoLlILY194WcfhQpqh7H5AZad8NdxJPgjzAhyySQtRWqTM/c0J5Y47m5MdHuBz7mOZb/nZQ2w8pmpDPjPCtTF3icPudnGkFIfaXvhKxyahB9z1FHvwy+tpm547mp5SNohPLj6+l4AWSOLtHx//en7E1g91oFmd2Uzp1h8d+yncLS49F3fkDUdLSV97F98Use1L00y2lXPP8b37ImGeotKYp8rZ9GvHj3vSoYente1hD/dEDt6Yhzx4k64ZOQt7cn71Ex/kCN89zUrChgD8JI5VPO9kiAuGvI5VExs69EkOOVN6yiv7AimwCGHF2M7+CNsJnPJeufsg24jigQ6Jb+SGmJ1OKMomLqowYDNJXDLl9ZKJzi6imzjGSkEavIp0VDIjkZS8IMm9SKzrByQzqbMvrxHTX+w7Ue9bgN+Eu2MIDsnWhATXVqKXbWS5SiNhaUc8UyqlLnMv8YR1ly4mU8tjIqnYkFdgZxwUxsH7aH91+LFlkvJ2ePqQODMFFqGLh5Hyp1IyDqrujTNajH4WJxCPfltIv/kf -------------------------------------------------------------------------------- /examples/src/main.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * ESP32 Wifi Manager 3 | * @file basic-usage.cpp 4 | * @brief Short minimal example to make use of the ESP32 Wifi Manager 5 | * @author Martin Verges 6 | * @copyright 2022-2025 7 | * 8 | * Licensed under CC BY-NC-SA 4.0 9 | * (Attribution-NonCommercial-ShareAlike 4.0 International) 10 | **/ 11 | 12 | #include 13 | #include "wifimanager.h" 14 | 15 | // Create a instance of the WifiManager 16 | WIFIMANAGER WifiManager; 17 | AsyncWebServer webServer(80); 18 | 19 | void setup() { 20 | Serial.begin(115200); 21 | Serial.println("\n=== ESP32 WiFi Manager Example ==="); 22 | Serial.println("Starting WiFi Manager..."); 23 | 24 | // Optional: Set the name for your AP and optional password (leave "" for open wifi) 25 | // Default: SoftAP with SSID = ESP_xxxxxx based on efuse without a password 26 | // Must be called before startBackgroundTask() 27 | // WifiManager.configureSoftAp("hotspot_name", "hotspot_password"); 28 | 29 | WifiManager.startBackgroundTask(); // Run the background task to take care of our Wifi 30 | WifiManager.fallbackToSoftAp(true); // Run a SoftAP if no known AP can be reached 31 | WifiManager.attachWebServer(&webServer); // Attach our API to the HTTP Webserver 32 | WifiManager.attachUI(); // Attach the UI to the Webserver 33 | 34 | // Run the Webserver and add your webpages to it 35 | webServer.on("/", HTTP_GET, [](AsyncWebServerRequest *request){ 36 | String response = R"html( 37 | 38 | ESP32 WiFi Manager Demo 39 | 40 |

ESP32 WiFi Manager Demo

41 |

Welcome to the ESP32 WiFi Manager example!

42 | 47 |
48 |

ESP32 WiFi Manager (c) 2022-2025 by Martin Verges

49 | 50 | )html"; 51 | request->send(200, "text/html", response); 52 | }); 53 | 54 | // Start BOTH servers for HTTP and HTTPS captive portal compatibility 55 | webServer.begin(); 56 | Serial.println("HTTP server started on port 80"); 57 | // End Webserver 58 | } 59 | 60 | void loop() { 61 | // your special code to do some good stuff 62 | delay(500); 63 | 64 | // You can use a GPIO or other event to start a softAP, please replace false with a meaningful event 65 | if (false) { 66 | // While we are connected to some WIFI, we can start up a softAP 67 | // The AP will automatically shut down after some time if no client is connected 68 | WifiManager.startSoftAP(); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ESP32 Wifi Manager 2 | 3 | This multi wifi manager runs your ESP32 in a AP+STA mode in a non blocking mode on core 0. 4 | This way you can easily start a softAP and scan for Wifi Networks while beeing conntected to some wifi. 5 | 6 | You can store multiple SSIDs and it will try to connect, reconnect and optionally fallback to softAP. 7 | 8 | ## Why? 9 | 10 | Because all the available solution that I found, where unable to fullfill my requirements. 11 | 12 | ## Focus of this Project 13 | 14 | It is only made and tested it on my ESP32 Microcontroller. 15 | 16 | ## How is it working? 17 | 18 | 1) First of all, if there is no configuration of a known SSID, it starts an AP. 19 | Within the AP you can use your own WebUI using RESTful APIs to configure the AP. 20 | 21 | 2) When a initial SSID is stored into the local database, the background task will try to connect to it. 22 | On success, the AP will timeout and close it self. 23 | You can close the AP if you like to speed that up. 24 | 25 | 3) It's possible to add multiple SSIDs to connect to. 26 | If there are more known SSIDs, the WifiManager will scan for SSIDs in range and pick the strongest Signal to connect to. 27 | 28 | 4) The background task monitors the Wifi status and reconnect if required. 29 | 30 | ### More detailed flow diagram 31 | 32 | Flow diagram 33 | 34 | ## What do I need to do? 35 | 36 | If you want to use this wifi manager, you can create your own Web UI or use a prebuild one available at `/wifi`! 37 | 38 | ## Build in UI 39 | 40 | The UI route is only loaded to `/wifi` if you execute `attachUI()` inside your script. 41 | 42 | Build in UI 43 | 44 | 45 | ## APIs 46 | 47 | | Method | Request URL | Json Body | Info | 48 | | ------ | ----------------------- | -------------------------------------------- | --------------------------------------------------------------- | 49 | | GET | /api/wifi/configlist | none | Get the configured SSID AP list | 50 | | GET | /api/wifi/scan | none | Async Scan for Networks in Range. | 51 | | GET | /api/wifi/status | none | Show Status of the ESP32 | 52 | | POST | /api/wifi/add | `{ "apName": "mySSID", "apPass": "secret" }` | Add a new SSID to the AP list | 53 | | DELETE | /api/wifi/id | `{ "id": 1 }` | Drop the AP list entry using the ID | 54 | | DELETE | /api/wifi/apName | `{ "apName": "mySSID" }` | Drop the AP list entries identified by the AP (SSID) Name | 55 | | POST | /api/wifi/softap/start | none | Open/Create a softAP. Used to switch from client to AP mode | 56 | | POST | /api/wifi/softap/stop | none | Disconnect the softAP and start to connect to known SSIDs | 57 | | POST | /api/wifi/client/stop | none | Disconnect current wifi connection, start to search and connect | 58 | 59 | ### Async scanning 60 | 61 | Due to the way scanning is done on a ESP32, it looks like it's common that your client disconnects. 62 | So wait long enough between first and second scan. 63 | On the 1st request a response body containing `{"status":"scanning"}` will be send to the client. 64 | When you do a scan after long enough wait time, you receive an array of objects. 65 | Example: 66 | ``` 67 | [ 68 | {"channel": 1, "encryptionType": 3, "rssi": -80, "ssid": "My Wifi Network"}, 69 | {"channel": 11, "encryptionType": 0, "rssi": -50, "ssid": "My Public Network"} 70 | ] 71 | ``` 72 | PS: If you find a way to prevent the client disconnect on scan, please let me know! 73 | 74 | ## Dependencies 75 | 76 | This Wifi manager depends on some external libraries to provide the functionality. 77 | These are: 78 | 79 | * Arduino 80 | * Preferences 81 | * ArduinoJson 82 | * ESPAsyncWebServer 83 | 84 | # License 85 | 86 | esp32-wifi-manager (c) by Martin Verges. 87 | 88 | This project is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. 89 | 90 | You should have received a copy of the license along with this work. 91 | If not, see . 92 | 93 | ## Commercial Licenses 94 | 95 | If you want to use this software on a comercial product, you can get an commercial license on request. 96 | -------------------------------------------------------------------------------- /wifimanager.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Wifi Manager 3 | * (c) 2022-2025 Martin Verges 4 | * 5 | * Licensed under CC BY-NC-SA 4.0 6 | * (Attribution-NonCommercial-ShareAlike 4.0 International) 7 | **/ 8 | #ifndef WIFIMANAGER_h 9 | #define WIFIMANAGER_h 10 | 11 | #ifndef WIFIMANAGER_MAX_APS 12 | #define WIFIMANAGER_MAX_APS 4 // Valid range is uint8_t 13 | #endif 14 | 15 | #ifndef CAPTIVEPORTAL_MAX_HANDLERS 16 | #define CAPTIVEPORTAL_MAX_HANDLERS 15 17 | #endif 18 | 19 | #include 20 | #include 21 | #include 22 | #include 23 | 24 | void wifiTask(void* param); 25 | 26 | 27 | class WIFIMANAGER { 28 | private: 29 | AsyncCallbackWebHandler * uiWebHandlers[2]; 30 | uint8_t uiWebHandlerCount = 0; 31 | AsyncCallbackWebHandler * apiWebHandlers[10]; 32 | uint8_t apiWebHandlerCount = 0; 33 | AsyncCallbackWebHandler * captivePortalWebHandlers[CAPTIVEPORTAL_MAX_HANDLERS]; 34 | uint8_t captivePortalWebHandlerCount = 0; 35 | 36 | protected: 37 | AsyncWebServer * webServer; // The Webserver to register routes on 38 | 39 | String apiPrefix = "/api/wifi"; // Prefix for all IP endpionts 40 | String uiPrefix = "/wifi"; // Prefix for all UI endpionts 41 | 42 | Preferences preferences; // Used to store AP credentials to NVS 43 | char * NVS; // Name used for NVS preferences 44 | 45 | struct apCredentials_t { 46 | String apName; // Name of the AP SSID 47 | String apPass; // Password if required to the AP 48 | }; 49 | apCredentials_t apList[WIFIMANAGER_MAX_APS]; // Stored AP list 50 | 51 | uint8_t configuredSSIDs = 0; // Number of stored SSIDs in the NVS 52 | 53 | bool createFallbackAP = true; // Create an AP for configuration if no other connection is available 54 | 55 | uint64_t lastWifiCheckMillis = 0; // Time of last Wifi health check 56 | uint32_t intervalWifiCheckMillis = 15000; // Interval of the Wifi health checks 57 | uint64_t startApTimeMillis = 0; // Time when the AP was started 58 | uint32_t timeoutApMillis = 120000; // Timeout of an AP when no client is connected, if timeout reached rescan, tryconnect or createAP 59 | 60 | String softApName; // Name of the soft AP if created, default to ESP_XXXXXXXX if empty 61 | String softApPass; // Password for the soft AP, default to no password (empty) 62 | 63 | wifi_power_t wifiTxPower = WIFI_POWER_19_5dBm; 64 | 65 | // Wipe the apList credentials 66 | void clearApList(); 67 | 68 | // Get id of the first non empty entry 69 | uint8_t getApEntry(); 70 | 71 | // Print a log message to Serial, can be overwritten 72 | virtual void logMessage(String msg); 73 | 74 | void attachCaptivePortal(); 75 | void detachCaptivePortal(); 76 | 77 | uint32_t getSoftApTimeRemaining(); 78 | bool setMode(wifi_mode_t mode); 79 | 80 | public: 81 | // We let the loop run as as Task 82 | TaskHandle_t wifiTaskHandle; 83 | TaskHandle_t dnsTaskHandle; 84 | volatile bool dnsServerActive = false; 85 | 86 | WIFIMANAGER(const char * ns = "wifimanager"); 87 | virtual ~WIFIMANAGER(); 88 | 89 | // If no known Wifi can't be found, create an AP but retry regulary 90 | void fallbackToSoftAp(bool state = true); 91 | 92 | // Get the current fallback state 93 | bool getFallbackState(); 94 | 95 | // Call to run the Task in the background 96 | void startBackgroundTask(String apName = "", String apPass = ""); 97 | 98 | // Attach a webserver and register api routes 99 | void attachWebServer(AsyncWebServer * srv); 100 | 101 | // Detach the webserver and delete all routes 102 | void detachWebServer(); 103 | 104 | // Attach the optional UI 105 | void attachUI(); 106 | 107 | // Detach the optional UI 108 | void detachUI(); 109 | 110 | // Add another AP to the list of known WIFIs 111 | bool addWifi(String apName, String apPass, bool updateNVS = true); 112 | 113 | // Delete Wifi from apList by ID 114 | bool delWifi(uint8_t apId); 115 | 116 | // Delete Wifi from apList by Name 117 | bool delWifi(String apName); 118 | 119 | // Try each known SSID and connect until none is left or one is connected. 120 | bool tryConnect(); 121 | 122 | bool tryConnectSpecific(uint8_t networkId); 123 | 124 | // Check if a SSID is stored in the config 125 | bool configAvailable(); 126 | 127 | // Set Wifi TX Power. 128 | bool setTxPower(wifi_power_t power, bool applyToRunningWifi = false); 129 | 130 | // Get Wifi TX Power 131 | wifi_power_t getTxPower(bool fromWifi); 132 | 133 | // Preconfigure the SoftAP 134 | void configueSoftAp(String apName = "", String apPass = ""); 135 | 136 | // Start a SoftAP, called if no wifi can be connected 137 | bool startSoftAP(String apName = "", String apPass = ""); 138 | 139 | // Disconnect/Stop SoftAP Mode 140 | void stopSoftAP(); 141 | 142 | // Disconnect/Stop STA Mode 143 | void stopClient(); 144 | 145 | // Disconnect/Stop SoftAP and STA Mode. Optionally end the task loop as well. 146 | void stopWifi(bool killTask = false); 147 | 148 | // Run in the loop to maintain state 149 | void loop(bool force = false); 150 | 151 | // Write AP Settings into persistent storage. Called on each addAP; 152 | bool writeToNVS(); 153 | 154 | // Load AP Settings from NVS it known apList 155 | bool loadFromNVS(); 156 | }; 157 | 158 | #endif 159 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Attribution-NonCommercial-ShareAlike 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International 58 | Public License 59 | 60 | By exercising the Licensed Rights (defined below), You accept and agree 61 | to be bound by the terms and conditions of this Creative Commons 62 | Attribution-NonCommercial-ShareAlike 4.0 International Public License 63 | ("Public License"). To the extent this Public License may be 64 | interpreted as a contract, You are granted the Licensed Rights in 65 | consideration of Your acceptance of these terms and conditions, and the 66 | Licensor grants You such rights in consideration of benefits the 67 | Licensor receives from making the Licensed Material available under 68 | these terms and conditions. 69 | 70 | 71 | Section 1 -- Definitions. 72 | 73 | a. Adapted Material means material subject to Copyright and Similar 74 | Rights that is derived from or based upon the Licensed Material 75 | and in which the Licensed Material is translated, altered, 76 | arranged, transformed, or otherwise modified in a manner requiring 77 | permission under the Copyright and Similar Rights held by the 78 | Licensor. For purposes of this Public License, where the Licensed 79 | Material is a musical work, performance, or sound recording, 80 | Adapted Material is always produced where the Licensed Material is 81 | synched in timed relation with a moving image. 82 | 83 | b. Adapter's License means the license You apply to Your Copyright 84 | and Similar Rights in Your contributions to Adapted Material in 85 | accordance with the terms and conditions of this Public License. 86 | 87 | c. BY-NC-SA Compatible License means a license listed at 88 | creativecommons.org/compatiblelicenses, approved by Creative 89 | Commons as essentially the equivalent of this Public License. 90 | 91 | d. Copyright and Similar Rights means copyright and/or similar rights 92 | closely related to copyright including, without limitation, 93 | performance, broadcast, sound recording, and Sui Generis Database 94 | Rights, without regard to how the rights are labeled or 95 | categorized. For purposes of this Public License, the rights 96 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 97 | Rights. 98 | 99 | e. Effective Technological Measures means those measures that, in the 100 | absence of proper authority, may not be circumvented under laws 101 | fulfilling obligations under Article 11 of the WIPO Copyright 102 | Treaty adopted on December 20, 1996, and/or similar international 103 | agreements. 104 | 105 | f. Exceptions and Limitations means fair use, fair dealing, and/or 106 | any other exception or limitation to Copyright and Similar Rights 107 | that applies to Your use of the Licensed Material. 108 | 109 | g. License Elements means the license attributes listed in the name 110 | of a Creative Commons Public License. The License Elements of this 111 | Public License are Attribution, NonCommercial, and ShareAlike. 112 | 113 | h. Licensed Material means the artistic or literary work, database, 114 | or other material to which the Licensor applied this Public 115 | License. 116 | 117 | i. Licensed Rights means the rights granted to You subject to the 118 | terms and conditions of this Public License, which are limited to 119 | all Copyright and Similar Rights that apply to Your use of the 120 | Licensed Material and that the Licensor has authority to license. 121 | 122 | j. Licensor means the individual(s) or entity(ies) granting rights 123 | under this Public License. 124 | 125 | k. NonCommercial means not primarily intended for or directed towards 126 | commercial advantage or monetary compensation. For purposes of 127 | this Public License, the exchange of the Licensed Material for 128 | other material subject to Copyright and Similar Rights by digital 129 | file-sharing or similar means is NonCommercial provided there is 130 | no payment of monetary compensation in connection with the 131 | exchange. 132 | 133 | l. Share means to provide material to the public by any means or 134 | process that requires permission under the Licensed Rights, such 135 | as reproduction, public display, public performance, distribution, 136 | dissemination, communication, or importation, and to make material 137 | available to the public including in ways that members of the 138 | public may access the material from a place and at a time 139 | individually chosen by them. 140 | 141 | m. Sui Generis Database Rights means rights other than copyright 142 | resulting from Directive 96/9/EC of the European Parliament and of 143 | the Council of 11 March 1996 on the legal protection of databases, 144 | as amended and/or succeeded, as well as other essentially 145 | equivalent rights anywhere in the world. 146 | 147 | n. You means the individual or entity exercising the Licensed Rights 148 | under this Public License. Your has a corresponding meaning. 149 | 150 | 151 | Section 2 -- Scope. 152 | 153 | a. License grant. 154 | 155 | 1. Subject to the terms and conditions of this Public License, 156 | the Licensor hereby grants You a worldwide, royalty-free, 157 | non-sublicensable, non-exclusive, irrevocable license to 158 | exercise the Licensed Rights in the Licensed Material to: 159 | 160 | a. reproduce and Share the Licensed Material, in whole or 161 | in part, for NonCommercial purposes only; and 162 | 163 | b. produce, reproduce, and Share Adapted Material for 164 | NonCommercial purposes only. 165 | 166 | 2. Exceptions and Limitations. For the avoidance of doubt, where 167 | Exceptions and Limitations apply to Your use, this Public 168 | License does not apply, and You do not need to comply with 169 | its terms and conditions. 170 | 171 | 3. Term. The term of this Public License is specified in Section 172 | 6(a). 173 | 174 | 4. Media and formats; technical modifications allowed. The 175 | Licensor authorizes You to exercise the Licensed Rights in 176 | all media and formats whether now known or hereafter created, 177 | and to make technical modifications necessary to do so. The 178 | Licensor waives and/or agrees not to assert any right or 179 | authority to forbid You from making technical modifications 180 | necessary to exercise the Licensed Rights, including 181 | technical modifications necessary to circumvent Effective 182 | Technological Measures. For purposes of this Public License, 183 | simply making modifications authorized by this Section 2(a) 184 | (4) never produces Adapted Material. 185 | 186 | 5. Downstream recipients. 187 | 188 | a. Offer from the Licensor -- Licensed Material. Every 189 | recipient of the Licensed Material automatically 190 | receives an offer from the Licensor to exercise the 191 | Licensed Rights under the terms and conditions of this 192 | Public License. 193 | 194 | b. Additional offer from the Licensor -- Adapted Material. 195 | Every recipient of Adapted Material from You 196 | automatically receives an offer from the Licensor to 197 | exercise the Licensed Rights in the Adapted Material 198 | under the conditions of the Adapter's License You apply. 199 | 200 | c. No downstream restrictions. You may not offer or impose 201 | any additional or different terms or conditions on, or 202 | apply any Effective Technological Measures to, the 203 | Licensed Material if doing so restricts exercise of the 204 | Licensed Rights by any recipient of the Licensed 205 | Material. 206 | 207 | 6. No endorsement. Nothing in this Public License constitutes or 208 | may be construed as permission to assert or imply that You 209 | are, or that Your use of the Licensed Material is, connected 210 | with, or sponsored, endorsed, or granted official status by, 211 | the Licensor or others designated to receive attribution as 212 | provided in Section 3(a)(1)(A)(i). 213 | 214 | b. Other rights. 215 | 216 | 1. Moral rights, such as the right of integrity, are not 217 | licensed under this Public License, nor are publicity, 218 | privacy, and/or other similar personality rights; however, to 219 | the extent possible, the Licensor waives and/or agrees not to 220 | assert any such rights held by the Licensor to the limited 221 | extent necessary to allow You to exercise the Licensed 222 | Rights, but not otherwise. 223 | 224 | 2. Patent and trademark rights are not licensed under this 225 | Public License. 226 | 227 | 3. To the extent possible, the Licensor waives any right to 228 | collect royalties from You for the exercise of the Licensed 229 | Rights, whether directly or through a collecting society 230 | under any voluntary or waivable statutory or compulsory 231 | licensing scheme. In all other cases the Licensor expressly 232 | reserves any right to collect such royalties, including when 233 | the Licensed Material is used other than for NonCommercial 234 | purposes. 235 | 236 | 237 | Section 3 -- License Conditions. 238 | 239 | Your exercise of the Licensed Rights is expressly made subject to the 240 | following conditions. 241 | 242 | a. Attribution. 243 | 244 | 1. If You Share the Licensed Material (including in modified 245 | form), You must: 246 | 247 | a. retain the following if it is supplied by the Licensor 248 | with the Licensed Material: 249 | 250 | i. identification of the creator(s) of the Licensed 251 | Material and any others designated to receive 252 | attribution, in any reasonable manner requested by 253 | the Licensor (including by pseudonym if 254 | designated); 255 | 256 | ii. a copyright notice; 257 | 258 | iii. a notice that refers to this Public License; 259 | 260 | iv. a notice that refers to the disclaimer of 261 | warranties; 262 | 263 | v. a URI or hyperlink to the Licensed Material to the 264 | extent reasonably practicable; 265 | 266 | b. indicate if You modified the Licensed Material and 267 | retain an indication of any previous modifications; and 268 | 269 | c. indicate the Licensed Material is licensed under this 270 | Public License, and include the text of, or the URI or 271 | hyperlink to, this Public License. 272 | 273 | 2. You may satisfy the conditions in Section 3(a)(1) in any 274 | reasonable manner based on the medium, means, and context in 275 | which You Share the Licensed Material. For example, it may be 276 | reasonable to satisfy the conditions by providing a URI or 277 | hyperlink to a resource that includes the required 278 | information. 279 | 3. If requested by the Licensor, You must remove any of the 280 | information required by Section 3(a)(1)(A) to the extent 281 | reasonably practicable. 282 | 283 | b. ShareAlike. 284 | 285 | In addition to the conditions in Section 3(a), if You Share 286 | Adapted Material You produce, the following conditions also apply. 287 | 288 | 1. The Adapter's License You apply must be a Creative Commons 289 | license with the same License Elements, this version or 290 | later, or a BY-NC-SA Compatible License. 291 | 292 | 2. You must include the text of, or the URI or hyperlink to, the 293 | Adapter's License You apply. You may satisfy this condition 294 | in any reasonable manner based on the medium, means, and 295 | context in which You Share Adapted Material. 296 | 297 | 3. You may not offer or impose any additional or different terms 298 | or conditions on, or apply any Effective Technological 299 | Measures to, Adapted Material that restrict exercise of the 300 | rights granted under the Adapter's License You apply. 301 | 302 | 303 | Section 4 -- Sui Generis Database Rights. 304 | 305 | Where the Licensed Rights include Sui Generis Database Rights that 306 | apply to Your use of the Licensed Material: 307 | 308 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 309 | to extract, reuse, reproduce, and Share all or a substantial 310 | portion of the contents of the database for NonCommercial purposes 311 | only; 312 | 313 | b. if You include all or a substantial portion of the database 314 | contents in a database in which You have Sui Generis Database 315 | Rights, then the database in which You have Sui Generis Database 316 | Rights (but not its individual contents) is Adapted Material, 317 | including for purposes of Section 3(b); and 318 | 319 | c. You must comply with the conditions in Section 3(a) if You Share 320 | all or a substantial portion of the contents of the database. 321 | 322 | For the avoidance of doubt, this Section 4 supplements and does not 323 | replace Your obligations under this Public License where the Licensed 324 | Rights include other Copyright and Similar Rights. 325 | 326 | 327 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 328 | 329 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 330 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 331 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 332 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 333 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 334 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 335 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 336 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 337 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 338 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 339 | 340 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 341 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 342 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 343 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 344 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 345 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 346 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 347 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 348 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 349 | 350 | c. The disclaimer of warranties and limitation of liability provided 351 | above shall be interpreted in a manner that, to the extent 352 | possible, most closely approximates an absolute disclaimer and 353 | waiver of all liability. 354 | 355 | 356 | Section 6 -- Term and Termination. 357 | 358 | a. This Public License applies for the term of the Copyright and 359 | Similar Rights licensed here. However, if You fail to comply with 360 | this Public License, then Your rights under this Public License 361 | terminate automatically. 362 | 363 | b. Where Your right to use the Licensed Material has terminated under 364 | Section 6(a), it reinstates: 365 | 366 | 1. automatically as of the date the violation is cured, provided 367 | it is cured within 30 days of Your discovery of the 368 | violation; or 369 | 370 | 2. upon express reinstatement by the Licensor. 371 | 372 | For the avoidance of doubt, this Section 6(b) does not affect any 373 | right the Licensor may have to seek remedies for Your violations 374 | of this Public License. 375 | 376 | c. For the avoidance of doubt, the Licensor may also offer the 377 | Licensed Material under separate terms or conditions or stop 378 | distributing the Licensed Material at any time; however, doing so 379 | will not terminate this Public License. 380 | 381 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 382 | License. 383 | 384 | 385 | Section 7 -- Other Terms and Conditions. 386 | 387 | a. The Licensor shall not be bound by any additional or different 388 | terms or conditions communicated by You unless expressly agreed. 389 | 390 | b. Any arrangements, understandings, or agreements regarding the 391 | Licensed Material not stated herein are separate from and 392 | independent of the terms and conditions of this Public License. 393 | 394 | 395 | Section 8 -- Interpretation. 396 | 397 | a. For the avoidance of doubt, this Public License does not, and 398 | shall not be interpreted to, reduce, limit, restrict, or impose 399 | conditions on any use of the Licensed Material that could lawfully 400 | be made without permission under this Public License. 401 | 402 | b. To the extent possible, if any provision of this Public License is 403 | deemed unenforceable, it shall be automatically reformed to the 404 | minimum extent necessary to make it enforceable. If the provision 405 | cannot be reformed, it shall be severed from this Public License 406 | without affecting the enforceability of the remaining terms and 407 | conditions. 408 | 409 | c. No term or condition of this Public License will be waived and no 410 | failure to comply consented to unless expressly agreed to by the 411 | Licensor. 412 | 413 | d. Nothing in this Public License constitutes or may be interpreted 414 | as a limitation upon, or waiver of, any privileges and immunities 415 | that apply to the Licensor or You, including from the legal 416 | processes of any jurisdiction or authority. 417 | 418 | ======================================================================= 419 | 420 | Creative Commons is not a party to its public 421 | licenses. Notwithstanding, Creative Commons may elect to apply one of 422 | its public licenses to material it publishes and in those instances 423 | will be considered the “Licensor.” The text of the Creative Commons 424 | public licenses is dedicated to the public domain under the CC0 Public 425 | Domain Dedication. Except for the limited purpose of indicating that 426 | material is shared under a Creative Commons public license or as 427 | otherwise permitted by the Creative Commons policies published at 428 | creativecommons.org/policies, Creative Commons does not authorize the 429 | use of the trademark "Creative Commons" or any other trademark or logo 430 | of Creative Commons without its prior written consent including, 431 | without limitation, in connection with any unauthorized modifications 432 | to any of its public licenses or any other arrangements, 433 | understandings, or agreements concerning use of licensed material. For 434 | the avoidance of doubt, this paragraph does not form part of the 435 | public licenses. 436 | 437 | Creative Commons may be contacted at creativecommons.org. 438 | -------------------------------------------------------------------------------- /wifimanager.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Wifi Manager 3 | * (c) 2022-2024 Martin Verges 4 | * 5 | * Licensed under CC BY-NC-SA 4.0 6 | * (Attribution-NonCommercial-ShareAlike 4.0 International) 7 | **/ 8 | #include "wifimanager.h" 9 | #include "AsyncJson.h" 10 | #include "ArduinoJson.h" 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | DNSServer dnsServer; 17 | 18 | /** 19 | * @brief Write a message to the Serial interface 20 | * @param msg The message to be written 21 | * 22 | * This function is a simple wrapper around Serial.print() to write a message 23 | * to the serial console. It can be overwritten by a custom implementation for 24 | * enhanced logging. 25 | */ 26 | void WIFIMANAGER::logMessage(String msg) { 27 | Serial.print(msg); 28 | } 29 | 30 | /** 31 | * @brief Background Task running as a loop forever 32 | * @param param needs to be a valid WIFIMANAGER instance 33 | */ 34 | void wifiBgTask(void* param) { 35 | yield(); 36 | delay(500); // wait a short time until everything is setup before executing the loop forever 37 | yield(); 38 | const TickType_t xDelay = 10000 / portTICK_PERIOD_MS; 39 | WIFIMANAGER * wifimanager = (WIFIMANAGER *) param; 40 | 41 | wifimanager->loop(true); // force run, to skip wait time 42 | delay(500); 43 | 44 | for(;;) { 45 | yield(); 46 | wifimanager->loop(); 47 | yield(); 48 | vTaskDelay(xDelay); 49 | } 50 | } 51 | 52 | void dnsBgTask(void* param) { 53 | yield(); 54 | delay(500); // wait a short time until everything is setup before executing the loop forever 55 | yield(); 56 | const TickType_t xDelay = 50 / portTICK_PERIOD_MS; 57 | WIFIMANAGER * wifimanager = (WIFIMANAGER *) param; 58 | 59 | for(;;) { 60 | yield(); 61 | if (wifimanager->dnsServerActive) dnsServer.processNextRequest(); 62 | yield(); 63 | vTaskDelay(xDelay); 64 | } 65 | } 66 | 67 | /** 68 | * @brief Start the background task, which will take care of the Wifi connection 69 | * 70 | * This method will load the configuration from NVS, try to connect to the configured WIFI(s) 71 | * and then start a background task, which will keep monitoring and trying to reconnect 72 | * to the configured WIFI(s) in case the connection drops. 73 | */ 74 | void WIFIMANAGER::startBackgroundTask(String softApName, String softApPass) { 75 | if (softApName.length()) this->softApName = softApName; 76 | if (softApPass.length()) this->softApPass = softApPass; 77 | loadFromNVS(); 78 | // setMode(WIFI_STA); 79 | tryConnect(); 80 | 81 | BaseType_t taskCreated = xTaskCreatePinnedToCore( 82 | wifiBgTask, 83 | "WifiManager", 84 | 4096, // Stack size in words 85 | this, // Task input parameter 86 | 1, // Priority of the task 87 | &wifiTaskHandle, // Task handle. 88 | 0 // Core where the task should run 89 | ); 90 | 91 | if (taskCreated != pdPASS) { 92 | logMessage("[ERROR] WifiManager: Error creating Wifi background task\n"); 93 | } 94 | 95 | xTaskCreatePinnedToCore( 96 | dnsBgTask, 97 | "WifiManagerDNS", 98 | 4096, // Stack size in words 99 | this, // Task input parameter 100 | 1, // Priority of the task 101 | &dnsTaskHandle, // Task handle. 102 | 0 // Core where the task should run 103 | ); 104 | 105 | if (taskCreated != pdPASS) { 106 | logMessage("[ERROR] WifiManager: Error creating DNS background task\n"); 107 | } 108 | } 109 | 110 | /** 111 | * @brief Construct a new WIFIMANAGER::WIFIMANAGER object 112 | * @details Puts the Wifi mode to AP+STA and registers Wifi Events 113 | * @param ns Namespace for the preferences non volatile storage (NVS) 114 | */ 115 | WIFIMANAGER::WIFIMANAGER(const char * ns) { 116 | NVS = (char *)ns; 117 | 118 | // AP on/off 119 | WiFi.onEvent([&](WiFiEvent_t event, WiFiEventInfo_t info) { 120 | logMessage("[WIFI][EVENT] AP mode started!\n"); 121 | }, ARDUINO_EVENT_WIFI_AP_START 122 | ); 123 | 124 | WiFi.onEvent([&](WiFiEvent_t event, WiFiEventInfo_t info) { 125 | logMessage("[WIFI][EVENT] AP mode stopped!\n"); 126 | }, ARDUINO_EVENT_WIFI_AP_STOP 127 | ); 128 | 129 | // AP client join/leave 130 | WiFi.onEvent([&](WiFiEvent_t event, WiFiEventInfo_t info) { 131 | logMessage(String("[WIFI][EVENT] Client connected - MAC: ") + 132 | String(info.wifi_ap_staconnected.mac[0], HEX) + ":" + 133 | String(info.wifi_ap_staconnected.mac[1], HEX) + ":" + 134 | String(info.wifi_ap_staconnected.mac[2], HEX) + ":" + 135 | String(info.wifi_ap_staconnected.mac[3], HEX) + ":" + 136 | String(info.wifi_ap_staconnected.mac[4], HEX) + ":" + 137 | String(info.wifi_ap_staconnected.mac[5], HEX) + "\n"); 138 | }, ARDUINO_EVENT_WIFI_AP_STACONNECTED 139 | ); 140 | 141 | WiFi.onEvent([&](WiFiEvent_t event, WiFiEventInfo_t info) { 142 | logMessage(String("[WIFI][EVENT] Client disconnected - MAC: ") + 143 | String(info.wifi_ap_stadisconnected.mac[0], HEX) + ":" + 144 | String(info.wifi_ap_stadisconnected.mac[1], HEX) + ":" + 145 | String(info.wifi_ap_stadisconnected.mac[2], HEX) + ":" + 146 | String(info.wifi_ap_stadisconnected.mac[3], HEX) + ":" + 147 | String(info.wifi_ap_stadisconnected.mac[4], HEX) + ":" + 148 | String(info.wifi_ap_stadisconnected.mac[5], HEX) + "\n"); 149 | }, ARDUINO_EVENT_WIFI_AP_STADISCONNECTED 150 | ); 151 | 152 | WiFi.onEvent([&](WiFiEvent_t event, WiFiEventInfo_t info) { 153 | logMessage("[WIFI][EVENT] *** IP ASSIGNED TO CLIENT: " + 154 | IPAddress(info.wifi_ap_staipassigned.ip.addr).toString() + " ***\n"); 155 | }, ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED 156 | ); 157 | 158 | WiFi.onEvent([&](WiFiEvent_t event, WiFiEventInfo_t info) { 159 | logMessage("[WIFI][EVENT] Disconnected from STA\n"); 160 | }, ARDUINO_EVENT_WIFI_STA_DISCONNECTED 161 | ); 162 | WiFi.onEvent([&](WiFiEvent_t event, WiFiEventInfo_t info) { 163 | logMessage("[WIFI][EVENT] Connected to STA\n"); 164 | }, ARDUINO_EVENT_WIFI_STA_CONNECTED 165 | ); 166 | } 167 | 168 | /** 169 | * @brief Destroy the WIFIMANAGER::WIFIMANAGER object 170 | * @details will stop the background task as well but not cleanup the AsyncWebserver 171 | */ 172 | WIFIMANAGER::~WIFIMANAGER() { 173 | dnsServerActive = false; 174 | 175 | // Give DNS task time to stop processing 176 | delay(100); 177 | yield(); 178 | 179 | if (wifiTaskHandle != NULL) { 180 | vTaskDelete(wifiTaskHandle); 181 | wifiTaskHandle = NULL; 182 | } 183 | if (dnsTaskHandle != NULL) { 184 | vTaskDelete(dnsTaskHandle); 185 | dnsTaskHandle = NULL; 186 | } 187 | } 188 | 189 | /** 190 | * @brief If no WIFI is available, fallback to create an AP on the ESP32 191 | * @param state boolean true (create AP) or false (don't create an AP) 192 | */ 193 | void WIFIMANAGER::fallbackToSoftAp(const bool state) { 194 | createFallbackAP = state; 195 | } 196 | 197 | /** 198 | * @brief Get the current configured fallback state 199 | * @return true 200 | * @return false 201 | */ 202 | bool WIFIMANAGER::getFallbackState() { 203 | return createFallbackAP; 204 | } 205 | 206 | /** 207 | * @brief Remove all entries from the current known and configured Wifi list 208 | * @details This only affects memory, not the storage! 209 | * @details If you wan't to persist this, you need to call writeToNVS() 210 | */ 211 | void WIFIMANAGER::clearApList() { 212 | for(uint8_t i=0; i 0) { 233 | sprintf(tmpKey, "apPass%d", i); 234 | String apPass = preferences.getString(tmpKey); 235 | logMessage(String("[WIFI] Load SSID '") + apName + "' to " + String(i+1) + ". slot.\n"); 236 | apList[i].apName = apName; 237 | apList[i].apPass = apPass; 238 | configuredSSIDs++; 239 | } 240 | } 241 | } 242 | preferences.end(); 243 | return true; 244 | } 245 | logMessage("[WIFI] Unable to load data from NVS, giving up...\n"); 246 | return false; 247 | } 248 | 249 | /** 250 | * @brief Write the current in memory configuration to the non volatile storage 251 | * @return true on success 252 | * @return false on error with the NVS 253 | */ 254 | bool WIFIMANAGER::writeToNVS() { 255 | if (!preferences.begin(NVS, false)) { 256 | logMessage("[WIFI] Unable to write data to NVS, giving up..."); 257 | return false; 258 | } 259 | 260 | preferences.clear(); 261 | char tmpKey[10]; 262 | for(uint8_t i = 0; i < WIFIMANAGER_MAX_APS; i++) { 263 | if (apList[i].apName.isEmpty()) continue; 264 | 265 | snprintf(tmpKey, sizeof(tmpKey), "apName%d", i); 266 | preferences.putString(tmpKey, apList[i].apName); 267 | 268 | snprintf(tmpKey, sizeof(tmpKey), "apPass%d", i); 269 | preferences.putString(tmpKey, apList[i].apPass); 270 | } 271 | 272 | preferences.end(); 273 | return true; 274 | } 275 | 276 | /** 277 | * @brief Add a new WIFI SSID to the known credentials list 278 | * @param apName Name of the SSID to connect to 279 | * @param apPass Password (or empty) to connect to the SSID 280 | * @param updateNVS Write the new entry directly to NVS 281 | * @return true on success 282 | * @return false on failure 283 | */ 284 | bool WIFIMANAGER::addWifi(String apName, String apPass, bool updateNVS) { 285 | if(apName.length() < 1 || apName.length() > 31) { 286 | logMessage("[WIFI] No SSID given or ssid too long"); 287 | return false; 288 | } 289 | 290 | if(apPass.length() > 63) { 291 | logMessage("[WIFI] Passphrase too long"); 292 | return false; 293 | } 294 | 295 | for(uint8_t i=0; i 0) return writeToNVS(); 338 | return false; 339 | } 340 | 341 | String _wifiModeAsString(wifi_mode_t mode) { 342 | if (mode == WIFI_MODE_STA) return "WIFI_MODE_STA"; 343 | if (mode == WIFI_MODE_AP) return "WIFI_MODE_AP"; 344 | if (mode == WIFI_MODE_APSTA) return "WIFI_MODE_APSTA"; 345 | if (mode == WIFI_MODE_NULL) return "WIFI_MODE_NULL"; 346 | if (mode == WIFI_MODE_MAX) return "WIFI_MODE_MAX"; 347 | return "UNKNOWN"; 348 | } 349 | 350 | bool WIFIMANAGER::setMode(wifi_mode_t mode) { 351 | bool result = WiFi.mode(mode); 352 | if (!result) return false; 353 | 354 | unsigned long startTime = millis(); 355 | const unsigned long timeout = 10000; // 10 Sekunden 356 | 357 | logMessage("[WIFI] Switching WiFi mode to " + _wifiModeAsString(mode) + " ..."); 358 | while (WiFi.getMode() != mode && millis() - startTime < timeout) { 359 | delay(10); 360 | logMessage("."); 361 | } 362 | if (WiFi.getMode() == mode) { 363 | logMessage(" success\n"); 364 | } else { 365 | logMessage(" timeout\n"); 366 | } 367 | return true; 368 | } 369 | 370 | /** 371 | * @brief Provides information about the current configuration state 372 | * @details When at least 1 SSID is configured, the return value will be true, otherwise false 373 | * @return true if one or more SSIDs stored 374 | * @return false if no configuration is available 375 | */ 376 | bool WIFIMANAGER::configAvailable() { 377 | return configuredSSIDs != 0; 378 | } 379 | 380 | /** 381 | * @brief Set the TX power of the Wifi 382 | * @return true if memorized or correctly applied 383 | * @return false if not applied correctly 384 | */ 385 | bool WIFIMANAGER::setTxPower(wifi_power_t power, bool applyToRunningWifi) { 386 | wifiTxPower = power; 387 | if (applyToRunningWifi) { 388 | return WiFi.setTxPower(power); 389 | } 390 | return true; 391 | } 392 | 393 | /** 394 | * @brief get the configured or applied TX power setting 395 | * @return wifi_power_t from configuration if fromWifi is false 396 | * @return wifi_power_t from running Wifi if fromWifi is true 397 | */ 398 | wifi_power_t WIFIMANAGER::getTxPower(bool fromWifi) { 399 | if (fromWifi) { 400 | return WiFi.getTxPower(); 401 | } 402 | return wifiTxPower; 403 | } 404 | 405 | /** 406 | * @brief Provides the apList element id of the first configured slot 407 | * @details It's used to speed up connection by getting the first available configuration 408 | * @return uint8_t apList element id or WIFIMANAGER_MAX_APS on error 409 | */ 410 | uint8_t WIFIMANAGER::getApEntry() { 411 | for(uint8_t i=0; i 0.\n"); 416 | return WIFIMANAGER_MAX_APS; 417 | } 418 | 419 | /** 420 | * @brief Return the time in seconds until the SoftAP times out. 421 | * @return uint32_t time in seconds until timeout 422 | */ 423 | uint32_t WIFIMANAGER::getSoftApTimeRemaining() { 424 | auto time = (timeoutApMillis - (millis() - startApTimeMillis)) / 1000; 425 | if (time > timeoutApMillis) time = 0; 426 | return time; 427 | } 428 | 429 | /** 430 | * @brief Background loop function running inside the task 431 | * @details regulary check if the connection is up&running, try to reconnect or create a fallback AP 432 | */ 433 | void WIFIMANAGER::loop(bool force) { 434 | if (!force && millis() - lastWifiCheckMillis < intervalWifiCheckMillis) return; 435 | lastWifiCheckMillis = millis(); 436 | 437 | if (WiFi.getMode() == WIFI_AP) { 438 | logMessage("[WIFI] Operating in softAP (" + WiFi.softAPIP().toString() + ") mode with " + String(WiFi.softAPgetStationNum()) + " client(s). " 439 | + "Next connection attempt in " + String(getSoftApTimeRemaining()) + " seconds\n"); 440 | 441 | if (getSoftApTimeRemaining() == 0) { 442 | if (WiFi.softAPgetStationNum() > 0) { 443 | logMessage("[WIFI] SoftAP has " + String(WiFi.softAPgetStationNum()) + " clients connected! Resetting timeout\n"); 444 | startApTimeMillis = millis(); // reset timeout as someone is connected 445 | return; 446 | } 447 | logMessage("[WIFI] Running in softAP mode but timeout reached. Closing softAP!\n"); 448 | stopSoftAP(); 449 | delay(100); 450 | } 451 | } else if (WiFi.getMode() == WIFI_STA) { 452 | if (WiFi.waitForConnectResult() == WL_CONNECTED && !WiFi.SSID().isEmpty()) { 453 | // Check if we are connected to a well known SSID 454 | for(uint8_t i=0; i choosenRssi) { 522 | if(encryptionType == WIFI_AUTH_OPEN || apList[i].apPass.length() > 0) { // open wifi or we do know a password 523 | choosenAp = i; 524 | choosenRssi = rssi; 525 | } 526 | } // else lower wifi signal 527 | } 528 | } 529 | WiFi.scanDelete(); 530 | } 531 | 532 | if (choosenAp == INT_MIN) { 533 | logMessage("[WIFI][CONNECT] Unable to find an SSID to connect to!\n"); 534 | return false; 535 | } else { 536 | logMessage(String("[WIFI][CONNECT] Trying to connect to SSID ") + apList[choosenAp].apName 537 | + " " + (apList[choosenAp].apPass.length() > 0 ? "with password '***'" : "without password") + "\n" 538 | ); 539 | return tryConnectSpecific(choosenAp); 540 | } 541 | } 542 | 543 | /** 544 | * @brief Try to connect to a specific network ID 545 | * @param networkId The specific network ID to connect to 546 | * @return true on success, false on failure 547 | */ 548 | bool WIFIMANAGER::tryConnectSpecific(uint8_t networkId) { 549 | if (networkId >= WIFIMANAGER_MAX_APS) { 550 | logMessage("[WIFI][CONNECT] Invalid network ID: " + String(networkId) + "\n"); 551 | return false; 552 | } 553 | 554 | if (WiFi.getMode() == WIFI_AP) stopSoftAP(); 555 | 556 | setMode(WIFI_STA); 557 | WiFi.begin(apList[networkId].apName.c_str(), apList[networkId].apPass.c_str()); 558 | WiFi.setTxPower(wifiTxPower); 559 | wl_status_t status = (wl_status_t)WiFi.waitForConnectResult(5000UL); 560 | 561 | auto startTime = millis(); 562 | // wait for connection, fail, or timeout 563 | while(status != WL_CONNECTED && status != WL_NO_SSID_AVAIL && status != WL_CONNECT_FAILED && (millis() - startTime) <= 10000) { 564 | delay(10); 565 | status = (wl_status_t)WiFi.waitForConnectResult(5000UL); 566 | } 567 | switch(status) { 568 | case WL_IDLE_STATUS: 569 | logMessage("[WIFI][CONNECT] Connecting failed (0): Idle\n"); 570 | break; 571 | case WL_NO_SSID_AVAIL: 572 | logMessage("[WIFI][CONNECT] Connecting failed (1): The AP can't be found\n"); 573 | break; 574 | case WL_SCAN_COMPLETED: 575 | logMessage("[WIFI][CONNECT] Connecting failed (2): Scan completed\n"); 576 | break; 577 | case WL_CONNECTED: // 3 578 | logMessage("[WIFI][CONNECT] Connection successful\n"); 579 | logMessage("[WIFI][CONNECT] SSID : " + WiFi.SSID() + "\n"); 580 | logMessage("[WIFI][CONNECT] IP : " + WiFi.localIP().toString() + "\n"); 581 | logMessage("[WIFI][CONNECT] Gateway: " + WiFi.gatewayIP().toString() + "\n"); 582 | logMessage("[WIFI][CONNECT] Subnet : " + WiFi.subnetMask().toString() + "\n"); 583 | logMessage("[WIFI][CONNECT] WebServer should be accessible at http://" + WiFi.localIP().toString() + "/wifi\n"); 584 | return true; 585 | break; 586 | case WL_CONNECT_FAILED: 587 | logMessage("[WIFI][CONNECT] Connecting failed (4): Unknown reason\n"); 588 | break; 589 | case WL_CONNECTION_LOST: 590 | logMessage("[WIFI][CONNECT] Connecting failed (5): Connection lost\n"); 591 | break; 592 | case WL_DISCONNECTED: 593 | logMessage("[WIFI][CONNECT] Connecting failed (6): Disconnected\n"); 594 | break; 595 | case WL_NO_SHIELD: 596 | logMessage("[WIFI][CONNECT] Connecting failed (7): No Wifi shield found\n"); 597 | break; 598 | default: 599 | logMessage("[WIFI][CONNECT] Connecting failed (" + String(status) + "): Unknown status code\n"); 600 | break; 601 | } 602 | // clean up IP config after failed connection to avoid issues with softAp detection 603 | WiFi.disconnect(true); 604 | return false; 605 | } 606 | 607 | void WIFIMANAGER::configueSoftAp(String apName, String apPass) { 608 | this->softApName = apName; 609 | this->softApPass = apPass; 610 | } 611 | 612 | /** 613 | * @brief Start a SoftAP for direct client access 614 | * @param apName name of the AP to create (default is ESP_XXXXXXXX) 615 | * @return true on success 616 | * @return false o error or if a SoftAP already runs 617 | */ 618 | bool WIFIMANAGER::startSoftAP(String apName, String apPass) { 619 | if (apName.length()) this->softApName = apName; 620 | if (apPass.length()) this->softApPass = apPass; 621 | 622 | if (WiFi.getMode() == WIFI_AP) return true; // already running 623 | startApTimeMillis = millis(); 624 | 625 | if (this->softApName == "") this->softApName = "ESP_" + String((uint32_t)ESP.getEfuseMac()); 626 | logMessage("[WIFI] Starting configuration portal on AP SSID " + this->softApName + "\n"); 627 | 628 | // setMode(WIFI_AP); // done by WiFi.softAP 629 | bool state = WiFi.softAP(this->softApName.c_str(), (this->softApPass.length() ? this->softApPass.c_str() : NULL)); 630 | WiFi.setTxPower(wifiTxPower); 631 | if (state) { 632 | dnsServer.setErrorReplyCode(DNSReplyCode::NoError); 633 | dnsServer.setTTL(60); 634 | 635 | // Start DNS server with better error handling 636 | if (!dnsServer.start(53, "*", WiFi.softAPIP())) { 637 | logMessage("[WIFI] DNS server failed to start, retrying...\n"); 638 | delay(200); 639 | dnsServer.start(53, "*", WiFi.softAPIP()); 640 | } 641 | 642 | dnsServerActive = true; 643 | delay(100); 644 | 645 | attachCaptivePortal(); 646 | 647 | logMessage("[WIFI][SOFTAP] SoftAP successfully started\n"); 648 | logMessage("[WIFI][SOFTAP] SSID: " + this->softApName + "\n"); 649 | logMessage(String("[WIFI][SOFTAP] Password: ") + (this->softApPass.length() > 0 ? "***" : "OPEN") + "\n"); 650 | logMessage("[WIFI][SOFTAP] IP Address: " + WiFi.softAPIP().toString() + "\n"); 651 | logMessage("[WIFI][SOFTAP] IP Subnet: " + WiFi.softAPSubnetMask().toString() + "\n"); 652 | logMessage("[WIFI][SOFTAP] MAC Address: " + WiFi.softAPmacAddress() + "\n"); 653 | logMessage("[WIFI][SOFTAP] Channel: " + String(WiFi.channel()) + "\n"); 654 | logMessage(String("[WIFI][SOFTAP] Encryption: ") + (this->softApPass.length() > 0 ? "WPA2" : "OPEN") + "\n"); 655 | logMessage("[WIFI][SOFTAP] WiFi Power: " + String(WiFi.getTxPower()) + " dBm\n"); 656 | logMessage("[WIFI][SOFTAP] WiFi Mode: " + String(WiFi.getMode()) + " (1=STA, 2=AP, 3=AP_STA)\n"); 657 | 658 | if (configAvailable()) { 659 | logMessage("[WIFI][SOFTAP] Will timeout in " + String(timeoutApMillis/1000) + " seconds if no clients connect (saved networks available)\n"); 660 | } else { 661 | logMessage("[WIFI][SOFTAP] Will run indefinitely (no saved networks configured)\n"); 662 | } 663 | return true; 664 | } else { 665 | logMessage("[WIFI] Unable to create softAP!\n"); 666 | return false; 667 | } 668 | } 669 | 670 | /** 671 | * @brief Stop/Disconnect a current running SoftAP 672 | */ 673 | void WIFIMANAGER::stopSoftAP() { 674 | dnsServer.stop(); 675 | dnsServerActive = false; 676 | delay(100); 677 | 678 | detachCaptivePortal(); 679 | WiFi.softAPdisconnect(false); 680 | setMode(WIFI_OFF); 681 | 682 | delay(500); // Give more time for interface to shut down completely 683 | logMessage("[WIFI] SoftAP stopped and DNS server deactivated\n"); 684 | } 685 | 686 | /** 687 | * @brief Stop/Disconnect a current wifi connection 688 | */ 689 | void WIFIMANAGER::stopClient() { 690 | WiFi.disconnect(); 691 | setMode(WIFI_OFF); 692 | } 693 | 694 | /** 695 | * @brief Stop/Disconnect all running wifi activies and optionally kill the background task as well 696 | * @param killTask true to kill the background task to prevent reconnects 697 | */ 698 | void WIFIMANAGER::stopWifi(bool killTask) { 699 | 700 | dnsServerActive = false; 701 | 702 | if (killTask) { 703 | vTaskDelete(wifiTaskHandle); 704 | vTaskDelete(dnsTaskHandle); 705 | } 706 | 707 | stopSoftAP(); 708 | stopClient(); 709 | setMode(WIFI_OFF); 710 | } 711 | 712 | void WIFIMANAGER::attachCaptivePortal() { 713 | // Check if webServer is initialized before registering handlers 714 | if (webServer == nullptr) { 715 | logMessage("[WIFI][WARNING] WebServer not initialized yet, skipping captive portal registration\n"); 716 | return; 717 | } 718 | 719 | // Reset handler count to prevent overflow 720 | captivePortalWebHandlerCount = 0; 721 | 722 | // Android Captive Portal Detection - Multiple URLs for better compatibility 723 | if (captivePortalWebHandlerCount < CAPTIVEPORTAL_MAX_HANDLERS) { 724 | captivePortalWebHandlers[captivePortalWebHandlerCount++] = &webServer->on("/generate_204", HTTP_GET, [&](AsyncWebServerRequest * request) { 725 | String host = request->hasHeader("Host") ? request->getHeader("Host")->value() : "unknown"; 726 | String userAgent = request->hasHeader("User-Agent") ? request->getHeader("User-Agent")->value() : "unknown"; 727 | logMessage("[WIFI][CAPTIVE] Android captive portal detection: /generate_204 from host: " + host + ", User-Agent: " + userAgent + "\n"); 728 | 729 | // Check if this is an Android connectivity check - if so, redirect to trigger captive portal 730 | if (host.indexOf("connectivitycheck") >= 0 || 731 | host.indexOf("clients3.google.com") >= 0 || 732 | host.indexOf("clients1.google.com") >= 0 || 733 | host.indexOf("android.com") >= 0) { 734 | 735 | // Samsung devices need 200 + HTML meta-refresh instead of 302 redirect 736 | if (userAgent.indexOf("Samsung") >= 0 || userAgent.indexOf("SM-") >= 0 || userAgent.indexOf("GT-") >= 0) { 737 | logMessage("[WIFI][CAPTIVE] Samsung device detected - sending 200 + HTML meta-refresh\n"); 738 | String htmlResponse = "RedirectingPlease wait, redirecting to WiFi setup...
Click here if not redirected"; 739 | request->send(200, "text/html", htmlResponse); 740 | return; 741 | } else { 742 | logMessage("[WIFI][CAPTIVE] Standard Android device - sending 302 redirect\n"); 743 | request->redirect(uiPrefix.c_str()); 744 | return; 745 | } 746 | } else { 747 | logMessage("[WIFI][CAPTIVE] Android device using host (" + host + ") not detected - sending 204\n"); 748 | } 749 | 750 | // For other requests, send 204 (compatibility) 751 | request->send(204); 752 | }); 753 | } 754 | 755 | if (captivePortalWebHandlerCount < CAPTIVEPORTAL_MAX_HANDLERS) { 756 | captivePortalWebHandlers[captivePortalWebHandlerCount++] = &webServer->on("/gen_204", HTTP_GET, [&](AsyncWebServerRequest * request) { 757 | logMessage("[WIFI][CAPTIVE] Android captive portal detection: /gen_204\n"); 758 | request->send(204); // Alternative Android endpoint expects 204 No Content (Fallback URL of older devices) 759 | }); 760 | } 761 | 762 | // Microsoft Captive Portal Detection 763 | if (captivePortalWebHandlerCount < CAPTIVEPORTAL_MAX_HANDLERS) { 764 | captivePortalWebHandlers[captivePortalWebHandlerCount++] = &webServer->on("/fwlink", HTTP_GET, [&](AsyncWebServerRequest * request) { 765 | logMessage("[WIFI][CAPTIVE] Microsoft captive portal detection: /connecttest.txt\n"); 766 | request->redirect(uiPrefix.c_str()); 767 | }); 768 | } 769 | 770 | // Windows Captive Portal Detection 771 | if (captivePortalWebHandlerCount < CAPTIVEPORTAL_MAX_HANDLERS) { 772 | captivePortalWebHandlers[captivePortalWebHandlerCount++] = &webServer->on("/connecttest.txt", HTTP_GET, [&](AsyncWebServerRequest * request) { 773 | logMessage("[WIFI][CAPTIVE] Windows captive portal detection: /connecttest.txt\n"); 774 | request->redirect(uiPrefix.c_str()); 775 | }); 776 | } 777 | 778 | // iOS Captive Portal Detection 779 | if (captivePortalWebHandlerCount < CAPTIVEPORTAL_MAX_HANDLERS) { 780 | captivePortalWebHandlers[captivePortalWebHandlerCount++] = &webServer->on("/hotspot-detect.html", HTTP_GET, [&](AsyncWebServerRequest * request) { 781 | logMessage("[WIFI][CAPTIVE] iOS captive portal detection: /hotspot-detect.html\n"); 782 | request->redirect(uiPrefix.c_str()); 783 | }); 784 | } 785 | 786 | // Ubuntu/Linux Captive Portal Detection 787 | if (captivePortalWebHandlerCount < CAPTIVEPORTAL_MAX_HANDLERS) { 788 | captivePortalWebHandlers[captivePortalWebHandlerCount++] = &webServer->on("/connectivity-check", HTTP_GET, [&](AsyncWebServerRequest * request) { 789 | logMessage("[WIFI][CAPTIVE] Ubuntu captive portal detection: /connectivity-check\n"); 790 | request->redirect(uiPrefix.c_str()); 791 | }); 792 | } 793 | 794 | // Catch-all handler for any unmatched requests (most important for captive portal) 795 | webServer->onNotFound([&](AsyncWebServerRequest *request) { 796 | String url = request->url(); 797 | String host = request->hasHeader("Host") ? request->getHeader("Host")->value() : "unknown"; 798 | 799 | // Ignore favicon and other assets to reduce log spam 800 | if (url.endsWith("favicon.ico") || url.endsWith(".png") || url.endsWith(".jpg") || url.endsWith(".js") || url.endsWith(".css")) { 801 | request->send(404); 802 | return; 803 | } 804 | 805 | logMessage("[WIFI][CAPTIVE] Captive portal catch-all: " + host + url + "\n"); 806 | request->redirect("http://" + WiFi.softAPIP().toString() + "/" + uiPrefix.c_str(), 302); 807 | }); 808 | } 809 | 810 | 811 | void WIFIMANAGER::detachCaptivePortal() { 812 | // Only remove captive portal detection handlers, keep UI and API handlers 813 | for (int i = 0; i < captivePortalWebHandlerCount; i++) { 814 | logMessage("[WIFI] Removing Captive Portal handler: #" + String(i) + "\n"); 815 | webServer->removeHandler(captivePortalWebHandlers[i]); 816 | } 817 | captivePortalWebHandlerCount = 0; 818 | // Note: UI and API handlers remain active for WiFi-connected access 819 | logMessage("[WIFI] Captive Portal handlers removed, UI/API remain available\n"); 820 | } 821 | 822 | /** 823 | * @brief Remove all registered WebServer handlers for API, UI and DNS 824 | * @details This is used to detach the WebServer from the WifiManager 825 | * when the WifiManager is deleted 826 | */ 827 | void WIFIMANAGER::detachWebServer() { 828 | for (int i = 0; i < apiWebHandlerCount; i++) { 829 | logMessage("[WIFI] Removing WebServer handler: API#" + String(i) + "\n"); 830 | webServer->removeHandler(apiWebHandlers[i]); 831 | } 832 | apiWebHandlerCount = 0; 833 | 834 | detachUI(); 835 | detachCaptivePortal(); 836 | } 837 | 838 | // Rate limiting for scan endpoint - more permissive 839 | static uint64_t lastScanRequest = 0; 840 | static const uint32_t SCAN_COOLDOWN_MS = 2000; 841 | 842 | /** 843 | * @brief Attach the WebServer to the WifiManager to register the RESTful API 844 | * @param srv WebServer object 845 | */ 846 | void WIFIMANAGER::attachWebServer(AsyncWebServer * srv) { 847 | webServer = srv; // store it in the class for later use 848 | 849 | // If SoftAP is already running, register captive portal handlers now 850 | if (WiFi.getMode() == WIFI_AP && dnsServerActive) { 851 | logMessage("[WIFI] Registering captive portal handlers for existing SoftAP\n"); 852 | attachCaptivePortal(); 853 | } 854 | 855 | apiWebHandlers[apiWebHandlerCount++] = &webServer->on((apiPrefix + "/softap/start").c_str(), HTTP_POST, [&](AsyncWebServerRequest * request) { 856 | request->send(200, "application/json", "{\"message\":\"Soft AP stopped\"}"); 857 | yield(); 858 | delay(250); 859 | startSoftAP(); 860 | }); 861 | 862 | apiWebHandlers[apiWebHandlerCount++] = &webServer->on((apiPrefix + "/softap/stop").c_str(), HTTP_POST, [&](AsyncWebServerRequest * request) { 863 | request->send(200, "application/json", "{\"message\":\"Soft AP stopped\"}"); 864 | yield(); 865 | delay(250); // It's likely that this message won't go trough, but we give it a short time 866 | stopSoftAP(); 867 | }); 868 | 869 | apiWebHandlers[apiWebHandlerCount++] = &webServer->on((apiPrefix + "/client/stop").c_str(), HTTP_POST, [&](AsyncWebServerRequest * request) { 870 | request->send(200, "application/json", "{\"message\":\"Terminating current Wifi connection\"}"); 871 | yield(); 872 | delay(500); // It's likely that this message won't go trough, but we give it a short time 873 | stopClient(); 874 | }); 875 | 876 | apiWebHandlers[apiWebHandlerCount++] = &webServer->on((apiPrefix + "/add").c_str(), HTTP_POST, [&](AsyncWebServerRequest * request){}, NULL, 877 | [&](AsyncWebServerRequest * request, uint8_t *data, size_t len, size_t index, size_t total) { 878 | // Validate Content-Type header 879 | if (!request->hasHeader("Content-Type") || !request->getHeader("Content-Type")->value().startsWith("application/json")) { 880 | request->send(400, "application/json", "{\"error\":\"Content-Type must be application/json\"}"); 881 | return; 882 | } 883 | 884 | // Validate request size limits 885 | if (len == 0 || len > 512) { 886 | request->send(400, "application/json", "{\"error\":\"Invalid request size (max 512 bytes)\"}"); 887 | return; 888 | } 889 | 890 | JsonDocument jsonBuffer; 891 | DeserializationError error = deserializeJson(jsonBuffer, (const char*)data, len); 892 | 893 | if (error) { 894 | request->send(400, "application/json", "{\"error\":\"Invalid JSON format\"}"); 895 | return; 896 | } 897 | 898 | // Validate required fields exist and have correct types 899 | if (!jsonBuffer["apName"].is() || !jsonBuffer["apPass"].is()) { 900 | request->send(422, "application/json", "{\"error\":\"Missing or invalid required fields: apName, apPass\"}"); 901 | return; 902 | } 903 | 904 | String apName = jsonBuffer["apName"].as(); 905 | String apPass = jsonBuffer["apPass"].as(); 906 | 907 | // Validate SSID length (WiFi standard: 1-32 bytes, ESP32 uses 1-31) 908 | if (apName.length() < 1 || apName.length() > 31) { 909 | request->send(422, "application/json", "{\"error\":\"SSID must be 1-31 characters long\"}"); 910 | return; 911 | } 912 | 913 | // Validate password length (WiFi standard: max 63 characters) 914 | if (apPass.length() > 63) { 915 | request->send(422, "application/json", "{\"error\":\"Password must not exceed 63 characters\"}"); 916 | return; 917 | } 918 | 919 | // Input sanitization - remove dangerous characters 920 | apName.replace('\0', ' '); 921 | apPass.replace('\0', ' '); 922 | apName.trim(); 923 | apPass.trim(); 924 | 925 | // Final validation after sanitization 926 | if (apName.length() == 0) { 927 | request->send(422, "application/json", "{\"error\":\"SSID cannot be empty after sanitization\"}"); 928 | // Attempt to add WiFi with proper error handling 929 | return; 930 | } 931 | 932 | if (!addWifi(apName, apPass)) { 933 | request->send(500, "application/json", "{\"error\":\"Unable to add WiFi network - storage full or duplicate entry\"}"); 934 | } else { 935 | request->send(200, "application/json", "{\"message\":\"WiFi network added successfully\"}"); 936 | } 937 | }); 938 | 939 | apiWebHandlers[apiWebHandlerCount++] = &webServer->on((apiPrefix + "/id").c_str(), HTTP_DELETE, [&](AsyncWebServerRequest * request){}, NULL, 940 | [&](AsyncWebServerRequest * request, uint8_t *data, size_t len, size_t index, size_t total) { 941 | // Validate Content-Type 942 | if (!request->hasHeader("Content-Type") || !request->getHeader("Content-Type")->value().startsWith("application/json")) { 943 | request->send(400, "application/json", "{\"error\":\"Content-Type must be application/json\"}"); 944 | return; 945 | } 946 | 947 | // Validate request size 948 | if (len == 0 || len > 256) { 949 | request->send(400, "application/json", "{\"error\":\"Invalid request size (max 256 bytes)\"}"); 950 | return; 951 | } 952 | 953 | JsonDocument jsonBuffer; 954 | DeserializationError error = deserializeJson(jsonBuffer, (const char*)data, len); 955 | 956 | if (error) { 957 | request->send(400, "application/json", "{\"error\":\"Invalid JSON format\"}"); 958 | return; 959 | } 960 | 961 | // Validate required field exists and is valid integer 962 | if (!jsonBuffer["id"].is()) { 963 | request->send(422, "application/json", "{\"error\":\"Missing or invalid required field: id (must be integer)\"}"); 964 | return; 965 | } 966 | 967 | int id = jsonBuffer["id"].as(); 968 | 969 | // Validate bounds 970 | if (id < 0 || id >= WIFIMANAGER_MAX_APS) { 971 | request->send(422, "application/json", "{\"error\":\"ID out of valid range (0-" + String(WIFIMANAGER_MAX_APS-1) + ")\"}"); 972 | return; 973 | } 974 | 975 | if (apList[id].apName.isEmpty()) { 976 | request->send(404, "application/json", "{\"error\":\"No WiFi network found at specified ID\"}"); 977 | return; 978 | } 979 | 980 | if (!delWifi((uint8_t)id)) { 981 | request->send(500, "application/json", "{\"error\":\"Unable to delete network entry\"}"); 982 | } else { 983 | request->send(200, "application/json", "{\"message\":\"WiFi network deleted successfully\"}"); 984 | } 985 | }); 986 | 987 | apiWebHandlers[apiWebHandlerCount++] = &webServer->on((apiPrefix + "/apName").c_str(), HTTP_DELETE, [&](AsyncWebServerRequest * request){}, NULL, 988 | [&](AsyncWebServerRequest * request, uint8_t *data, size_t len, size_t index, size_t total) { 989 | JsonDocument jsonBuffer; 990 | deserializeJson(jsonBuffer, (const char*)data); 991 | auto resp = request; 992 | if (!jsonBuffer["apName"].is()) { 993 | resp->send(422, "application/json", "{\"message\":\"Invalid data\"}"); 994 | return; 995 | } 996 | if (!delWifi(jsonBuffer["apName"].as())) { 997 | resp->send(500, "application/json", "{\"message\":\"Unable to delete entry\"}"); 998 | } else resp->send(200, "application/json", "{\"message\":\"AP deleted\"}"); 999 | }); 1000 | 1001 | apiWebHandlers[apiWebHandlerCount++] = &webServer->on((apiPrefix + "/configlist").c_str(), HTTP_GET, [&](AsyncWebServerRequest *request) { 1002 | AsyncResponseStream *response = request->beginResponseStream("application/json"); 1003 | JsonDocument jsonDoc; 1004 | auto jsonArray = jsonDoc.to(); 1005 | for(uint8_t i=0; i 0) { 1007 | JsonObject wifiNet = jsonArray.add(); 1008 | wifiNet["id"] = i; 1009 | wifiNet["apName"] = apList[i].apName; 1010 | wifiNet["apPass"] = apList[i].apPass.length() > 0 ? true : false; 1011 | } 1012 | } 1013 | serializeJson(jsonArray, *response); 1014 | response->setCode(200); 1015 | response->setContentLength(measureJson(jsonDoc)); 1016 | request->send(response); 1017 | }); 1018 | 1019 | apiWebHandlers[apiWebHandlerCount++] = &webServer->on((apiPrefix + "/scan").c_str(), HTTP_GET, [&](AsyncWebServerRequest *request) { 1020 | // Rate limiting check 1021 | uint64_t currentTime = millis(); 1022 | if (currentTime - lastScanRequest < SCAN_COOLDOWN_MS) { 1023 | uint32_t remainingTime = SCAN_COOLDOWN_MS - (currentTime - lastScanRequest); 1024 | request->send(429, "application/json", 1025 | "{\"error\":\"Rate limit exceeded. Please wait " + String(remainingTime/1000) + " seconds before scanning again\"}"); 1026 | return; 1027 | } 1028 | lastScanRequest = currentTime; 1029 | 1030 | AsyncResponseStream *response = request->beginResponseStream("application/json"); 1031 | JsonDocument jsonDoc; 1032 | 1033 | int scanResult; 1034 | String ssid; 1035 | uint8_t encryptionType; 1036 | int32_t rssi; 1037 | uint8_t* bssid; 1038 | int32_t channel; 1039 | 1040 | scanResult = WiFi.scanComplete(); 1041 | if (scanResult == WIFI_SCAN_FAILED) { 1042 | scanResult = WiFi.scanNetworks(true, true); // FIXME: scanNetworks is disconnecting clients! 1043 | jsonDoc["status"] = "scanning"; 1044 | } else if (scanResult > 0) { 1045 | for (int8_t i = 0; i < scanResult; i++) { 1046 | WiFi.getNetworkInfo(i, ssid, encryptionType, rssi, bssid, channel); 1047 | 1048 | JsonObject wifiNet = jsonDoc.add(); 1049 | wifiNet["ssid"] = ssid; 1050 | wifiNet["encryptionType"] = encryptionType; 1051 | wifiNet["rssi"] = rssi; 1052 | wifiNet["channel"] = channel; 1053 | yield(); 1054 | } 1055 | WiFi.scanDelete(); 1056 | } 1057 | serializeJson(jsonDoc, *response); 1058 | response->setCode(200); 1059 | response->setContentLength(measureJson(jsonDoc)); 1060 | request->send(response); 1061 | }); 1062 | 1063 | apiWebHandlers[apiWebHandlerCount++] = &webServer->on((apiPrefix + "/status").c_str(), HTTP_GET, [&](AsyncWebServerRequest *request) { 1064 | AsyncResponseStream *response = request->beginResponseStream("application/json"); 1065 | JsonDocument jsonDoc; 1066 | 1067 | jsonDoc["ssid"] = WiFi.SSID(); 1068 | jsonDoc["signalStrengh"] = WiFi.RSSI(); 1069 | 1070 | jsonDoc["ip"] = WiFi.localIP().toString(); 1071 | jsonDoc["gw"] = WiFi.gatewayIP().toString(); 1072 | jsonDoc["nm"] = WiFi.subnetMask().toString(); 1073 | 1074 | jsonDoc["hostname"] = WiFi.getHostname(); 1075 | 1076 | jsonDoc["chipModel"] = ESP.getChipModel(); 1077 | jsonDoc["chipRevision"] = ESP.getChipRevision(); 1078 | jsonDoc["chipCores"] = ESP.getChipCores(); 1079 | 1080 | jsonDoc["getHeapSize"] = ESP.getHeapSize(); 1081 | jsonDoc["freeHeap"] = ESP.getFreeHeap(); 1082 | 1083 | serializeJson(jsonDoc, *response); 1084 | response->setCode(200); 1085 | response->setContentLength(measureJson(jsonDoc)); 1086 | request->send(response); 1087 | }); 1088 | 1089 | apiWebHandlers[apiWebHandlerCount++] = &webServer->on((apiPrefix + "/connect").c_str(), HTTP_POST, [&](AsyncWebServerRequest * request){}, NULL, 1090 | [&](AsyncWebServerRequest * request, uint8_t *data, size_t len, size_t index, size_t total) { 1091 | // Validate Content-Type 1092 | if (!request->hasHeader("Content-Type") || !request->getHeader("Content-Type")->value().startsWith("application/json")) { 1093 | request->send(400, "application/json", "{\"error\":\"Content-Type must be application/json\"}"); 1094 | return; 1095 | } 1096 | 1097 | if (len == 0 || len > 256) { 1098 | request->send(400, "application/json", "{\"error\":\"Invalid request size\"}"); 1099 | return; 1100 | } 1101 | 1102 | JsonDocument jsonBuffer; 1103 | DeserializationError error = deserializeJson(jsonBuffer, (const char*)data, len); 1104 | 1105 | if (error) { 1106 | request->send(400, "application/json", "{\"error\":\"Invalid JSON format\"}"); 1107 | return; 1108 | } 1109 | 1110 | if (!jsonBuffer["id"].is()) { 1111 | request->send(422, "application/json", "{\"error\":\"Missing or invalid field: id\"}"); 1112 | return; 1113 | } 1114 | 1115 | int networkId = jsonBuffer["id"].as(); 1116 | if (networkId < 0 || networkId >= WIFIMANAGER_MAX_APS) { 1117 | request->send(422, "application/json", "{\"error\":\"Invalid network ID\"}"); 1118 | return; 1119 | } 1120 | 1121 | // Get network name for logging 1122 | String networkName = "Unknown"; 1123 | if (!apList[networkId].apName.isEmpty()) networkName = apList[networkId].apName; 1124 | 1125 | request->send(200, "application/json", "{\"message\":\"Connecting to " + networkName + "\"}"); 1126 | yield(); 1127 | 1128 | logMessage("[WIFI][API] Starting direct specific connection attempt\n"); 1129 | bool connectionResult = tryConnectSpecific(networkId); 1130 | if (connectionResult) { 1131 | logMessage("[WIFI][API] Direct connection successful to " + networkName + "\n"); 1132 | } else { 1133 | logMessage("[WIFI][API] Direct connection to " + networkName + " failed, resuming normal WiFi management\n"); 1134 | } 1135 | }); 1136 | } 1137 | 1138 | /** 1139 | * @brief Detach all UI web handlers from the web server 1140 | * @details Iterates through the list of UI web handlers, removes each one from the web server, 1141 | * and resets the count of UI web handlers to zero. 1142 | */ 1143 | void WIFIMANAGER::detachUI() { 1144 | for (int i = 0; i < uiWebHandlerCount; i++) { 1145 | logMessage("[WIFI] Removing WebServer handler: UI#" + String(i) + "\n"); 1146 | webServer->removeHandler(uiWebHandlers[i]); 1147 | } 1148 | uiWebHandlerCount = 0; 1149 | } 1150 | 1151 | /** 1152 | * @brief Attach the WebServer to the WifiManager to register the RESTful API 1153 | * @param srv WebServer object 1154 | */ 1155 | void WIFIMANAGER::attachUI() { 1156 | uiWebHandlers[uiWebHandlerCount++] = &webServer->on((uiPrefix).c_str(), HTTP_GET, [](AsyncWebServerRequest* request) { 1157 | String html = R"html( 1158 | 1159 | 1160 | 1161 | 1162 | 1163 | ESP32 WiFi Manager 1164 | 1383 | 1384 | 1385 |
1386 |
1387 |

ESP32 WiFi Manager

1388 |
1389 | 1390 | 1391 |
1392 | 1393 | 1397 | 1398 |
1399 |

Saved Networks

1400 |
1401 |
1402 |
1403 | 1404 | 1424 | 1425 | 1692 | 1693 | 1694 | )html"; 1695 | request->send(200, "text/html", html); 1696 | }); 1697 | } --------------------------------------------------------------------------------