Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
OTA tester with webserver
#include "Wire.h"
#include "RTClib.h"
// Load Wi-Fi library
#include <WiFiMulti.h>
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <Update.h>
//WiFiMulti WiFiMulti;
WiFiServer server1(80);
WebServer server2(80);
boolean upload_mode = 0; //use upload mode
boolean switch_mode = 0;
const int buttonPin = 32; // the number of the pushbutton pin
int buttonState = HIGH; // variable for reading the pushbutton status
int indicator = 2; //little blue light to signify something on the board
//int lamp = 5; //output for lamp relay
//int door = 4; //output for door relay
const char* host = "esp32";
const char* ssid = "*****"; // Your SSID (Name of your WiFi)
const char* password = "******"; //Your Wifi password
// Variable to store the HTTP request
String header;
/*
* Login page
*/
const char* loginIndex =
"<form name='loginForm'>"
"<table width='20%' bgcolor='A09F9F' align='center'>"
"<tr>"
"<td colspan=2>"
"<center><font size=4><b>ESP32 Login Page</b></font></center>"
"<br>"
"</td>"
"<br>"
"<br>"
"</tr>"
"<td>Username:</td>"
"<td><input type='text' size=25 name='userid'><br></td>"
"</tr>"
"<br>"
"<br>"
"<tr>"
"<td>Password:</td>"
"<td><input type='Password' size=25 name='pwd'><br></td>"
"<br>"
"<br>"
"</tr>"
"<tr>"
"<td><input type='submit' onclick='check(this.form)' value='Login'></td>"
"</tr>"
"</table>"
"</form>"
"<script>"
"function check(form)"
"{"
"if(form.userid.value=='admin' && form.pwd.value=='admin')"
"{"
"window.open('/serverIndex')"
"}"
"else"
"{"
" alert('Error Password or Username')/*displays error message*/"
"}"
"}"
"</script>";
/*
* Server Index Page
*/
const char* serverIndex =
"<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>"
"<form method='POST' action='#' enctype='multipart/form-data' id='upload_form'>"
"<input type='file' name='update'>"
"<input type='submit' value='Update'>"
"</form>"
"<div id='prg'>progress: 0%</div>"
"<script>"
"$('form').submit(function(e){"
"e.preventDefault();"
"var form = $('#upload_form')[0];"
"var data = new FormData(form);"
" $.ajax({"
"url: '/update',"
"type: 'POST',"
"data: data,"
"contentType: false,"
"processData:false,"
"xhr: function() {"
"var xhr = new window.XMLHttpRequest();"
"xhr.upload.addEventListener('progress', function(evt) {"
"if (evt.lengthComputable) {"
"var per = evt.loaded / evt.total;"
"$('#prg').html('progress: ' + Math.round(per*100) + '%');"
"}"
"}, false);"
"return xhr;"
"},"
"success:function(d, s) {"
"console.log('success!')"
"},"
"error: function (a, b, c) {"
"}"
"});"
"});"
"</script>";
//--------------------------------------------------------
void setup()
{
//Serial Port begin
Serial.begin (9600);
pinMode(indicator, OUTPUT);
pinMode(buttonPin, INPUT);
Connect_to_Wifi(); //set up wifi server
if(upload_mode) connect_upload_server(); //set up upload server
if(upload_mode) server2.begin();
else server1.begin();
}
void loop()
{
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
//if (buttonState == LOW) //state goes low when pressed
if(switch_mode == 1)
{
Serial.println("upload button pressed");
upload_mode = 1;
switch_mode = 0;
server1.stop();
delay(1000);
//WiFi.disconnect();
//Connect_to_Wifi();
server2.begin();
Serial.println("upload page active");
delay(1000);
connect_upload_server();
}
if(!upload_mode)
{
check_server();
}
if(upload_mode)
{
server2.handleClient();
delay(1);
}
}
//------------------------------------
void connect_upload_server()
{
//use mdns for host name resolution
if (!MDNS.begin(host)) { //http://esp32.local
Serial.println("Error setting up MDNS responder!");
while (1) {
delay(1000);
}
}
Serial.println("mDNS responder started");
//return index page which is stored in serverIndex
server2.on("/", HTTP_GET, []() {
server2.sendHeader("Connection", "close");
server2.send(200, "text/html", loginIndex);
});
server2.on("/serverIndex", HTTP_GET, []() {
server2.sendHeader("Connection", "close");
server2.send(200, "text/html", serverIndex);
});
//handling uploading firmware file
server2.on("/update", HTTP_POST, []() {
server2.sendHeader("Connection", "close");
server2.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
ESP.restart();
}, []() {
HTTPUpload& upload = server2.upload();
if (upload.status == UPLOAD_FILE_START) {
Serial.printf("Update: %s\n", upload.filename.c_str());
if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size
Update.printError(Serial);
}
} else if (upload.status == UPLOAD_FILE_WRITE) {
// flashing firmware to ESP
if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
Update.printError(Serial);
}
} else if (upload.status == UPLOAD_FILE_END) {
if (Update.end(true)) { //true to set the size to the current progress
Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize);
} else {
Update.printError(Serial);
}
}
});
}
//------------------------------------
void Connect_to_Wifi()
{
// We start by connecting to a WiFi network
//WiFiMulti.addAP(ssid, password);
// Connect to WiFi network
WiFi.begin(ssid, password);
Serial.println();
Serial.println();
Serial.print("Waiting for WiFi... ");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
digitalWrite(indicator, HIGH);
}
//------------------------------------
void check_server() //check web server and update
{
WiFiClient client = server1.available(); // Listen for incoming clients
if (client) { // If a new client connects,
Serial.println("New Client."); // print a message out in the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected())
{ // loop while the client's connected
if (client.available())
{ // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
header += c;
if (c == '\n')
{ // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println();
if (header.indexOf("GET /Upload/on") >= 0)
{
switch_mode = 1;
}
else if (header.indexOf("GET /Upload/off") >= 0)
{
switch_mode = 0;
}
// Display the HTML web page
client.println("<!DOCTYPE html><html>");
client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
client.println("<link rel=\"icon\" href=\"data:,\">");
// client.println("<meta http-equiv=\"refresh\" content=\"2\">");
// CSS to style the on/off buttons
// Feel free to change the background-color and font-size attributes to fit your preferences
client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
client.println(".button { background-color: #4CAF50; border: none; color: white; padding: 16px 40px;");
client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
client.println(".button2 {background-color: #555555;}</style></head>");
// Web Page Heading
client.println("<body><h1>TEST PAGE</h1>");
//client.println("<p>Upload Mode " + String(switch_mode) + "</p>");
if(!upload_mode)
client.println("<p><a href=\"/Upload/on\"><button class=\"button\">Upload on</button></a></p>");
else
//client.println("<p><a href=\"/Upload/off\"><button class=\"button button2\">Upload off</button></a></p>");
client.println("</body></html>");
// The HTTP response ends with another blank line
client.println();
// Break out of the while loop
break;
}
else // if you got a newline, then clear currentLine
currentLine = "";
}
else if (c != '\r') // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
// Clear the header variable
header = "";
// Close the connection
client.stop();
Serial.println("Client disconnected.");
Serial.println("");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment