web123456

arduino+ESP32 web distribution demo code

  • #include <>
  • #include <>
  • #include <>
  • #include <> // for device domain name ("esp32")
  • #include <esp_wifi.h> //used for esp_wifi_restore() to delete saved wifi information
  • const int baudRate = 115200; //Set the baud rate
  • const byte DNS_PORT = 53; //Set the DNS port number
  • const int webPort = 80; //Set the Web port number
  • const int resetPin = 0; //Set reset button pin for deleting WiFi information.
  • const int LED = 2; //Set LED pins
  • const char* AP_SSID = "NodeMCU-ESP32"; //Set the AP hotspot name
  • //const char* AP_PASS = ""; //set the AP hotspot password
  • const char* HOST_NAME = "MY_ESP32S"; //Set the device name
  • String scanNetworksID = ""; // for storing scanned WiFi IDs
  • int connectTimeOut_s = 15; //WiFi connection timeout in seconds
  • IPAddress apIP(192, 168, 4, 1); // Set the IP address of the AP
  • String wifi_ssid = ""; //Temporary storage of wifi account passwords
  • String wifi_pass = ""; //Temporary storage of wifi account passwords
  • // Define the HTML source code for the home page of the root directory.
  • #define ROOT_HTML "<!DOCTYPE html><html><head><title>WIFI Config by lwang</title><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"></head><style type=\"text/css\">.input{display: block; margin-top: 10px;}.input span{width: 100px; float: left; float: left; height: 36px; line-height: 36px;}.input input{height: 30px;width: 200px;}.btn{width: 120px; height: 35px; background-color: #000000; border:0px; color:#ffffff; margin-top:15px; margin-left:100px;}</style><body><form method=\"POST\" action=\"configwifi\"><label class=\"input\"><span>WiFi SSID</span><input type=\"text\" name=\"ssid\" value=\"\"></label><label class=\"input\"><span>WiFi PASS</span><input type=\"text\" name=\"pass\"></label><input class=\"btn\" type=\"submit\" name=\"submit\" value=\"Submie\"> <p><span> Nearby wifi:</P></form>"
  • // Define the HTML source code of the success page.
  • #define SUCCESS_HTML "<html><body><font size=\"10\">successd,wifi connecting...<br />Please close this page manually.</font></body></html>"
  • DNSServer dnsServer; // Create a dnsServer instance
  • WebServer server(webPort); //Enable web service, create TCP SERVER, parameters: port number, maximum number of connections.
  • //Initialize AP mode
  • void initSoftAP(){
  • (WIFI_AP); // Configure for AP mode
  • (apIP, apIP, IPAddress(255, 255, 255, 0)); //Set the AP hotspot IP and subnet mask
  • if((AP_SSID)){ //Enable AP hotspot, add the second parameter if you need password.
  • //Print related information
  • ("ESP-32S SoftAP is right.");
  • ("Soft-AP IP address = ");
  • (());
  • (String("MAC address = ") + ().c_str());
  • }else{ // Failed to turn on hotspot
  • ("WiFiAP Failed");
  • delay(1000);
  • ("restart now...");
  • (); //restart reset esp32
  • }
  • }
  • //Initialize DNS servers
  • void initDNS(){
  • // Determine if mapping all addresses to esp32's ip was successful or not
  • if((DNS_PORT, "*", apIP)){
  • ("start dnsserver success.");
  • }else{
  • ("start dnsserver failed.");
  • }
  • }
  • //Initialize WebServer
  • void initWebServer(){
  • // Set the domain name esp32 for the device, the full domain name is ????
  • if(("esp32")){
  • ("MDNS responder started");
  • }
  • //Must add a second parameter HTTP_GET in the following format, otherwise the portal will not be forced.
  • ("/", HTTP_GET, handleRoot); // When the browser requests the server root (home page) call the custom function handleRoot processing, set the home page callback function, you must add the second parameter HTTP_GET, otherwise you can not force the portal
  • ("/configwifi", HTTP_POST, handleConfigWifi); // Call the custom function handleConfigWifi when the browser requests the server/configwifi (form field) directory.
  • (handleNotFound); // Call the custom function handleNotFound when the web resource requested by the browser cannot be found on the server.
  • //Tells the server to begin listening for incoming None
  • (); //Start TCP SERVER
  • //(true); // disable delayed sending
  • ("WebServer started!");
  • }
  • //Scanning WiFi
  • bool scanWiFi(){
  • ("scan start");
  • // Scan for nearby WiFi
  • int n = ();
  • ("scan done");
  • if (n == 0) {
  • ("no networks found");
  • scanNetworksID = "no networks found";
  • return false;
  • }else{
  • (n);
  • (" networks found");
  • for (int i = 0; i < n; ++i) {
  • // Print SSID and RSSI for each network found
  • (i + 1);
  • (": ");
  • ((i));
  • (" (");
  • ((i));
  • (")");
  • (((i) == WIFI_AUTH_OPEN) ? " " : "*");
  • scanNetworksID += "<P>" + (i) + "</P>";
  • delay(10);
  • }
  • return true;
  • }
  • }
  • void connectToWiFi(int timeOut_s){
  • ("Enter the connectToWiFi() function.");
  • // Set to STA mode and connect to WIFI
  • (WIFI_STA);
  • (true);//Set up automatic connection
  • / / with the string member function c_str () to generate a const char * pointer to the null character to the end of the array, that is, to obtain the pointer to the string.
  • if(wifi_ssid !=""){
  • ("Connect with web configuration information...");
  • (wifi_ssid.c_str(), wifi_pass.c_str());
  • wifi_ssid = "";
  • wifi_pass = "";
  • }else{
  • ("Connect with information saved by nvs...");
  • ();//Connect to the last successfully connected wifi
  • }
  • //(wifi_ssid.c_str(), wifi_pass.c_str());
  • int Connect_time = 0; // Used for connection timing, reset the device if the connection is unsuccessful for a long time
  • while (() != WL_CONNECTED) { //Wait for the WIFI connection to be successful
  • (".");
  • digitalWrite(LED,!digitalRead(LED));
  • delay(500);
  • Connect_time ++;
  • if (Connect_time > 2*timeOut_s) { //Long time not connected, re-enter the matching page
  • digitalWrite(LED,LOW);
  • ("");
  • ("WIFI autoconnect fail, start AP for webconfig now...");
  • wifiConfig(); // Go to the web side to manually configure wifi
  • return; //Skip out Prevent infinite initialization
  • //break; //jump to prevent infinite initialization
  • }
  • }
  • if(() == WL_CONNECTED){
  • ("WIFI connect Success");
  • ("SSID:%s", ().c_str());
  • (", PSW:%s\r\n", ().c_str());
  • ("LocalIP:");
  • (());
  • (" ,GateIP:");
  • (());
  • ("WIFI status is:");
  • (());
  • digitalWrite(LED,HIGH);
  • ();
  • }
  • }
  • // for configuring WiFi
  • void wifiConfig(){
  • initSoftAP();
  • initDNS();
  • initWebServer();
  • scanWiFi();
  • }
  • //Process the access request from the root directory "/" (home page), will display the HTML page for configuring wifi.
  • void handleRoot(){
  • if (("selectSSID")){
  • (200, "text/html", ROOT_HTML + scanNetworksID + "</body></html>");
  • }else{
  • (200, "text/html", ROOT_HTML + scanNetworksID + "</body></html>");
  • }
  • }
  • void handleConfigWifi(){
  • //return http status
  • //(200, "text/html", SUCCESS_HTML);
  • if (("ssid")) {// Determine if there is an account parameter
  • ("got ssid:");
  • wifi_ssid = ("ssid"); //Get the content of the html form input box with name "ssid".
  • // strcpy(sta_ssid, ("ssid").c_str());// copy account parameters into sta_ssid
  • (wifi_ssid);
  • }else{//No parameters
  • ("error, not found ssid");
  • (200, "text/html", "<meta charset='UTF-8'>error, not found ssid");// Return to the error page
  • return;
  • }
  • //Password is the same as account number
  • if (("pass")) {
  • ("got password:");
  • wifi_pass = ("pass"); //Get the content of the html form input box with name "pwd".
  • //strcpy(sta_pass, ("pass").c_str());
  • (wifi_pass);
  • }else{
  • ("error, not found password");
  • (200, "text/html", "<meta charset='UTF-8'>error, not found password");
  • return;
  • }
  • (200, "text/html", "<meta charset='UTF-8'>SSID:"+wifi_ssid+"<br />password:"+wifi_pass+"<br /> WiFi information has been obtained and is trying to connect, please close this page manually.");//Return to the save success page
  • delay(2000);
  • (true); With the //Parameter set to true, the device will directly turn off the access point mode, i.e. turn off the WiFi network established by the device.
  • (); //Shut down the web service
  • (); // Calling this function without inputting parameters will turn off the access point mode and set the currently configured AP hotspot network name and password to null values.
  • ("WiFi Connect SSID:" + wifi_ssid + " PASS:" + wifi_pass);
  • if(() != WL_CONNECTED){
  • ("Start calling the connect function connectToWiFi()...");
  • connectToWiFi(connectTimeOut_s);
  • }else{
  • ("Submitted configuration information auto-connected successfully...");
  • }
  • }
  • // Set the function 'handleNotFound' to handle 404 cases.
  • void handleNotFound(){ // This custom function handles when the browser requests a web resource that can't be found on the server.
  • handleRoot(); // Return to the configuration page if you access a directory that does not exist.
  • // (404, "text/plain", "404: Not found");
  • }
  • //LED blinking, led for the foot number, n for the number of times, t for the time interval ms
  • void blinkLED(int led,int n,int t){
  • for(int i=0;i<2*n;i++){
  • digitalWrite(led,!digitalRead(led));
  • delay(t);
  • }
  • }
  • //Delete the saved wifi information and make the LED blink 5 times.
  • void restoreWiFi(){
  • delay(500);
  • esp_wifi_restore(); //Delete saved wifi information
  • ("Connection information cleared, preparing to reboot device...");
  • delay(10);
  • blinkLED(LED,5,500); //LED blinks 5 times
  • digitalWrite(LED,LOW);
  • }
  • void checkConnect(bool reConnect){
  • if(() != WL_CONNECTED){
  • // ("WIFI not connected.") ;)
  • // (());
  • if(digitalRead(LED) != LOW){
  • digitalWrite(LED,LOW);
  • }
  • if(reConnect == true && () != WIFI_AP && () != WIFI_AP_STA ){
  • ("WIFI not connected.");
  • ("WiFi Mode:");
  • (());
  • ("Connecting to WiFi...");
  • connectToWiFi(connectTimeOut_s);
  • }
  • }else if(digitalRead(LED) != HIGH){
  • digitalWrite(LED,HIGH);
  • }
  • }
  • void setup() {
  • pinMode(LED,OUTPUT); //Configure the LED port as an output port
  • digitalWrite(LED,LOW); //Initial light off
  • pinMode(resetPin, INPUT_PULLUP); // Key pull-up input mode (default high level input, pull-down to low level when pressed)
  • (baudRate);
  • (HOST_NAME); //Set the device name
  • connectToWiFi(connectTimeOut_s);
  • }
  • void loop() {
  • //Press and hold for 5 seconds (P0) to clear network configuration information
  • if(!digitalRead(resetPin)){
  • delay(5000);
  • if(!digitalRead(resetPin)){
  • ("\n button has been pressed for 5 seconds, clearing the network connection.");
  • restoreWiFi(); //Delete saved wifi information
  • (); //restart reset esp32
  • ("The device has been rebooted.");
  • }
  • }
  • (); // Check client DNS requests
  • (); //check client (browser) http requests
  • checkConnect(true); //Detect network connection status, the parameter true means reconnect if disconnected.
  • delay(30);
  • }