1
0
mirror of https://github.com/esp8266/Arduino.git synced 2025-06-12 01:53:07 +03:00

Migrate from astyle to clang-format (#8464)

This commit is contained in:
Maxim Prokhorov
2022-02-20 19:23:33 +03:00
committed by Max Prokhorov
parent 46190b61f1
commit 19b7a29720
241 changed files with 15925 additions and 16197 deletions

View File

@ -35,7 +35,7 @@
#ifndef STASSID
#define STASSID "your-ssid"
#define STAPSK "your-password"
#define STAPSK "your-password"
#endif
const char *ssid = STASSID;
@ -69,8 +69,7 @@ void handleRoot() {
</body>\
</html>",
hr, min % 60, sec % 60
);
hr, min % 60, sec % 60);
server.send(200, "text/html", temp);
digitalWrite(led, 0);
}
@ -86,9 +85,7 @@ void handleNotFound() {
message += server.args();
message += "\n";
for (uint8_t i = 0; i < server.args(); i++) {
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
for (uint8_t i = 0; i < server.args(); i++) { message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; }
server.send(404, "text/plain", message);
digitalWrite(led, 0);
@ -133,9 +130,7 @@ void setup(void) {
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
if (MDNS.begin("esp8266")) { Serial.println("MDNS responder started"); }
server.on("/", handleRoot);
server.on("/test.svg", drawGraph);
@ -151,4 +146,3 @@ void loop(void) {
server.handleClient();
MDNS.update();
}

View File

@ -72,7 +72,7 @@ SDFSConfig fileSystemConfig = SDFSConfig();
#ifndef STASSID
#define STASSID "your-ssid"
#define STAPSK "your-password"
#define STAPSK "your-password"
#endif
const char* ssid = STASSID;
@ -122,15 +122,9 @@ void replyServerError(String msg) {
*/
String checkForUnsupportedPath(String filename) {
String error = String();
if (!filename.startsWith("/")) {
error += F("!NO_LEADING_SLASH! ");
}
if (filename.indexOf("//") != -1) {
error += F("!DOUBLE_SLASH! ");
}
if (filename.endsWith("/")) {
error += F("!TRAILING_SLASH! ");
}
if (!filename.startsWith("/")) { error += F("!NO_LEADING_SLASH! "); }
if (filename.indexOf("//") != -1) { error += F("!DOUBLE_SLASH! "); }
if (filename.endsWith("/")) { error += F("!TRAILING_SLASH! "); }
return error;
}
#endif
@ -174,18 +168,12 @@ void handleStatus() {
Also demonstrates the use of chunked responses.
*/
void handleFileList() {
if (!fsOK) {
return replyServerError(FPSTR(FS_INIT_ERROR));
}
if (!fsOK) { return replyServerError(FPSTR(FS_INIT_ERROR)); }
if (!server.hasArg("dir")) {
return replyBadRequest(F("DIR ARG MISSING"));
}
if (!server.hasArg("dir")) { return replyBadRequest(F("DIR ARG MISSING")); }
String path = server.arg("dir");
if (path != "/" && !fileSystem->exists(path)) {
return replyBadRequest("BAD PATH");
}
if (path != "/" && !fileSystem->exists(path)) { return replyBadRequest("BAD PATH"); }
DBG_OUTPUT_PORT.println(String("handleFileList: ") + path);
Dir dir = fileSystem->openDir(path);
@ -253,9 +241,7 @@ bool handleFileRead(String path) {
return true;
}
if (path.endsWith("/")) {
path += "index.htm";
}
if (path.endsWith("/")) { path += "index.htm"; }
String contentType;
if (server.hasArg("download")) {
@ -270,9 +256,7 @@ bool handleFileRead(String path) {
}
if (fileSystem->exists(path)) {
File file = fileSystem->open(path, "r");
if (server.streamFile(file, contentType) != file.size()) {
DBG_OUTPUT_PORT.println("Sent less data than expected!");
}
if (server.streamFile(file, contentType) != file.size()) { DBG_OUTPUT_PORT.println("Sent less data than expected!"); }
file.close();
return true;
}
@ -309,27 +293,17 @@ String lastExistingParent(String path) {
Move folder | parent of source folder, or remaining ancestor
*/
void handleFileCreate() {
if (!fsOK) {
return replyServerError(FPSTR(FS_INIT_ERROR));
}
if (!fsOK) { return replyServerError(FPSTR(FS_INIT_ERROR)); }
String path = server.arg("path");
if (path.isEmpty()) {
return replyBadRequest(F("PATH ARG MISSING"));
}
if (path.isEmpty()) { return replyBadRequest(F("PATH ARG MISSING")); }
#ifdef USE_SPIFFS
if (checkForUnsupportedPath(path).length() > 0) {
return replyServerError(F("INVALID FILENAME"));
}
if (checkForUnsupportedPath(path).length() > 0) { return replyServerError(F("INVALID FILENAME")); }
#endif
if (path == "/") {
return replyBadRequest("BAD PATH");
}
if (fileSystem->exists(path)) {
return replyBadRequest(F("PATH FILE EXISTS"));
}
if (path == "/") { return replyBadRequest("BAD PATH"); }
if (fileSystem->exists(path)) { return replyBadRequest(F("PATH FILE EXISTS")); }
String src = server.arg("src");
if (src.isEmpty()) {
@ -338,43 +312,29 @@ void handleFileCreate() {
if (path.endsWith("/")) {
// Create a folder
path.remove(path.length() - 1);
if (!fileSystem->mkdir(path)) {
return replyServerError(F("MKDIR FAILED"));
}
if (!fileSystem->mkdir(path)) { return replyServerError(F("MKDIR FAILED")); }
} else {
// Create a file
File file = fileSystem->open(path, "w");
if (file) {
file.write((const char *)0);
file.write((const char*)0);
file.close();
} else {
return replyServerError(F("CREATE FAILED"));
}
}
if (path.lastIndexOf('/') > -1) {
path = path.substring(0, path.lastIndexOf('/'));
}
if (path.lastIndexOf('/') > -1) { path = path.substring(0, path.lastIndexOf('/')); }
replyOKWithMsg(path);
} else {
// Source specified: rename
if (src == "/") {
return replyBadRequest("BAD SRC");
}
if (!fileSystem->exists(src)) {
return replyBadRequest(F("SRC FILE NOT FOUND"));
}
if (src == "/") { return replyBadRequest("BAD SRC"); }
if (!fileSystem->exists(src)) { return replyBadRequest(F("SRC FILE NOT FOUND")); }
DBG_OUTPUT_PORT.println(String("handleFileCreate: ") + path + " from " + src);
if (path.endsWith("/")) {
path.remove(path.length() - 1);
}
if (src.endsWith("/")) {
src.remove(src.length() - 1);
}
if (!fileSystem->rename(src, path)) {
return replyServerError(F("RENAME FAILED"));
}
if (path.endsWith("/")) { path.remove(path.length() - 1); }
if (src.endsWith("/")) { src.remove(src.length() - 1); }
if (!fileSystem->rename(src, path)) { return replyServerError(F("RENAME FAILED")); }
replyOKWithMsg(lastExistingParent(src));
}
}
@ -403,9 +363,7 @@ void deleteRecursive(String path) {
// Otherwise delete its contents first
Dir dir = fileSystem->openDir(path);
while (dir.next()) {
deleteRecursive(path + '/' + dir.fileName());
}
while (dir.next()) { deleteRecursive(path + '/' + dir.fileName()); }
// Then delete the folder itself
fileSystem->rmdir(path);
@ -420,19 +378,13 @@ void deleteRecursive(String path) {
Delete folder | parent of deleted folder, or remaining ancestor
*/
void handleFileDelete() {
if (!fsOK) {
return replyServerError(FPSTR(FS_INIT_ERROR));
}
if (!fsOK) { return replyServerError(FPSTR(FS_INIT_ERROR)); }
String path = server.arg(0);
if (path.isEmpty() || path == "/") {
return replyBadRequest("BAD PATH");
}
if (path.isEmpty() || path == "/") { return replyBadRequest("BAD PATH"); }
DBG_OUTPUT_PORT.println(String("handleFileDelete: ") + path);
if (!fileSystem->exists(path)) {
return replyNotFound(FPSTR(FILE_NOT_FOUND));
}
if (!fileSystem->exists(path)) { return replyNotFound(FPSTR(FILE_NOT_FOUND)); }
deleteRecursive(path);
replyOKWithMsg(lastExistingParent(path));
@ -442,37 +394,25 @@ void handleFileDelete() {
Handle a file upload request
*/
void handleFileUpload() {
if (!fsOK) {
return replyServerError(FPSTR(FS_INIT_ERROR));
}
if (server.uri() != "/edit") {
return;
}
if (!fsOK) { return replyServerError(FPSTR(FS_INIT_ERROR)); }
if (server.uri() != "/edit") { return; }
HTTPUpload& upload = server.upload();
if (upload.status == UPLOAD_FILE_START) {
String filename = upload.filename;
// Make sure paths always start with "/"
if (!filename.startsWith("/")) {
filename = "/" + filename;
}
if (!filename.startsWith("/")) { filename = "/" + filename; }
DBG_OUTPUT_PORT.println(String("handleFileUpload Name: ") + filename);
uploadFile = fileSystem->open(filename, "w");
if (!uploadFile) {
return replyServerError(F("CREATE FAILED"));
}
if (!uploadFile) { return replyServerError(F("CREATE FAILED")); }
DBG_OUTPUT_PORT.println(String("Upload: START, filename: ") + filename);
} else if (upload.status == UPLOAD_FILE_WRITE) {
if (uploadFile) {
size_t bytesWritten = uploadFile.write(upload.buf, upload.currentSize);
if (bytesWritten != upload.currentSize) {
return replyServerError(F("WRITE FAILED"));
}
if (bytesWritten != upload.currentSize) { return replyServerError(F("WRITE FAILED")); }
}
DBG_OUTPUT_PORT.println(String("Upload: WRITE, Bytes: ") + upload.currentSize);
} else if (upload.status == UPLOAD_FILE_END) {
if (uploadFile) {
uploadFile.close();
}
if (uploadFile) { uploadFile.close(); }
DBG_OUTPUT_PORT.println(String("Upload: END, Size: ") + upload.totalSize);
}
}
@ -484,15 +424,11 @@ void handleFileUpload() {
and if it fails, return a 404 page with debug information
*/
void handleNotFound() {
if (!fsOK) {
return replyServerError(FPSTR(FS_INIT_ERROR));
}
if (!fsOK) { return replyServerError(FPSTR(FS_INIT_ERROR)); }
String uri = ESP8266WebServer::urlDecode(server.uri()); // required to read paths with blanks
String uri = ESP8266WebServer::urlDecode(server.uri()); // required to read paths with blanks
if (handleFileRead(uri)) {
return;
}
if (handleFileRead(uri)) { return; }
// Dump debug data
String message;
@ -526,9 +462,7 @@ void handleNotFound() {
Otherwise, fails with a 404 page with debug information
*/
void handleGetEdit() {
if (handleFileRead(F("/edit/index.htm"))) {
return;
}
if (handleFileRead(F("/edit/index.htm"))) { return; }
#ifdef INCLUDE_FALLBACK_INDEX_HTM
server.sendHeader(F("Content-Encoding"), "gzip");
@ -536,7 +470,6 @@ void handleGetEdit() {
#else
replyNotFound(FPSTR(FILE_NOT_FOUND));
#endif
}
void setup(void) {
@ -562,9 +495,7 @@ void setup(void) {
String error = checkForUnsupportedPath(dir.fileName());
String fileInfo = dir.fileName() + (dir.isDirectory() ? " [DIR]" : String(" (") + dir.fileSize() + "b)");
DBG_OUTPUT_PORT.println(error + fileInfo);
if (error.length() > 0) {
unsupportedFiles += error + fileInfo + '\n';
}
if (error.length() > 0) { unsupportedFiles += error + fileInfo + '\n'; }
}
DBG_OUTPUT_PORT.println();
@ -609,15 +540,15 @@ void setup(void) {
server.on("/edit", HTTP_GET, handleGetEdit);
// Create file
server.on("/edit", HTTP_PUT, handleFileCreate);
server.on("/edit", HTTP_PUT, handleFileCreate);
// Delete file
server.on("/edit", HTTP_DELETE, handleFileDelete);
server.on("/edit", HTTP_DELETE, handleFileDelete);
// Upload file
// - first callback is called after the request has ended with all parsed arguments
// - second callback handles file upload at that location
server.on("/edit", HTTP_POST, replyOK, handleFileUpload);
server.on("/edit", HTTP_POST, replyOK, handleFileUpload);
// Default handler for all URIs not defined above
// Use it to read files from filesystem

View File

@ -58,7 +58,7 @@ SDFSConfig fileSystemConfig = SDFSConfig();
#ifndef STASSID
#define STASSID "your-ssid"
#define STAPSK "your-password"
#define STAPSK "your-password"
#endif
// Indicate which digital I/Os should be displayed on the chart.
@ -110,9 +110,7 @@ void replyServerError(String msg) {
bool handleFileRead(String path) {
DBG_OUTPUT_PORT.println(String("handleFileRead: ") + path);
if (path.endsWith("/")) {
path += "index.htm";
}
if (path.endsWith("/")) { path += "index.htm"; }
String contentType = mime::getContentType(path);
@ -122,9 +120,7 @@ bool handleFileRead(String path) {
}
if (fileSystem->exists(path)) {
File file = fileSystem->open(path, "r");
if (server.streamFile(file, contentType) != file.size()) {
DBG_OUTPUT_PORT.println("Sent less data than expected!");
}
if (server.streamFile(file, contentType) != file.size()) { DBG_OUTPUT_PORT.println("Sent less data than expected!"); }
file.close();
return true;
}
@ -139,11 +135,9 @@ bool handleFileRead(String path) {
and if it fails, return a 404 page with debug information
*/
void handleNotFound() {
String uri = ESP8266WebServer::urlDecode(server.uri()); // required to read paths with blanks
String uri = ESP8266WebServer::urlDecode(server.uri()); // required to read paths with blanks
if (handleFileRead(uri)) {
return;
}
if (handleFileRead(uri)) { return; }
// Dump debug data
String message;
@ -218,7 +212,7 @@ void setup(void) {
////////////////////////////////
// WEB SERVER INIT
//get heap status, analog input value and all GPIO statuses in one json call
// get heap status, analog input value and all GPIO statuses in one json call
server.on("/espData", HTTP_GET, []() {
String json;
json.reserve(88);
@ -249,21 +243,18 @@ void setup(void) {
DBG_OUTPUT_PORT.println(" 0 (OFF): outputs are off and hidden from chart");
DBG_OUTPUT_PORT.println(" 1 (AUTO): outputs are rotated automatically every second");
DBG_OUTPUT_PORT.println(" 2 (MANUAL): outputs can be toggled from the web page");
}
// Return default GPIO mask, that is all I/Os except SD card ones
unsigned int defaultMask() {
unsigned int mask = 0b11111111111111111;
for (auto pin = 0; pin <= 16; pin++) {
if (isFlashInterfacePin(pin)) {
mask &= ~(1 << pin);
}
if (isFlashInterfacePin(pin)) { mask &= ~(1 << pin); }
}
return mask;
}
int rgbMode = 1; // 0=off - 1=auto - 2=manual
int rgbMode = 1; // 0=off - 1=auto - 2=manual
int rgbValue = 0;
esp8266::polledTimeout::periodicMs timeToChange(1000);
bool modeChangeRequested = false;
@ -278,28 +269,24 @@ void loop(void) {
}
// see if one second has passed since last change, otherwise stop here
if (!timeToChange) {
return;
}
if (!timeToChange) { return; }
// see if a mode change was requested
if (modeChangeRequested) {
// increment mode (reset after 2)
rgbMode++;
if (rgbMode > 2) {
rgbMode = 0;
}
if (rgbMode > 2) { rgbMode = 0; }
modeChangeRequested = false;
}
// act according to mode
switch (rgbMode) {
case 0: // off
case 0: // off
gpioMask = defaultMask();
gpioMask &= ~(1 << 12); // Hide GPIO 12
gpioMask &= ~(1 << 13); // Hide GPIO 13
gpioMask &= ~(1 << 15); // Hide GPIO 15
gpioMask &= ~(1 << 12); // Hide GPIO 12
gpioMask &= ~(1 << 13); // Hide GPIO 13
gpioMask &= ~(1 << 15); // Hide GPIO 15
// reset outputs
digitalWrite(12, 0);
@ -307,14 +294,12 @@ void loop(void) {
digitalWrite(15, 0);
break;
case 1: // auto
case 1: // auto
gpioMask = defaultMask();
// increment value (reset after 7)
rgbValue++;
if (rgbValue > 7) {
rgbValue = 0;
}
if (rgbValue > 7) { rgbValue = 0; }
// output new values
digitalWrite(12, rgbValue & 0b001);
@ -322,11 +307,10 @@ void loop(void) {
digitalWrite(15, rgbValue & 0b100);
break;
case 2: // manual
case 2: // manual
gpioMask = defaultMask();
// keep outputs unchanged
break;
}
}

View File

@ -5,7 +5,7 @@
#ifndef STASSID
#define STASSID "your-ssid"
#define STAPSK "your-password"
#define STAPSK "your-password"
#endif
const char* ssid = STASSID;
@ -31,9 +31,7 @@ void handleNotFound() {
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i = 0; i < server.args(); i++) {
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
for (uint8_t i = 0; i < server.args(); i++) { message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; }
server.send(404, "text/plain", message);
digitalWrite(led, 0);
}
@ -57,9 +55,7 @@ void setup(void) {
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
if (MDNS.begin("esp8266")) { Serial.println("MDNS responder started"); }
server.on("/", handleRoot);
@ -89,17 +85,17 @@ void setup(void) {
/////////////////////////////////////////////////////////
// Hook examples
server.addHook([](const String & method, const String & url, WiFiClient * client, ESP8266WebServer::ContentTypeFunction contentType) {
(void)method; // GET, PUT, ...
(void)url; // example: /root/myfile.html
(void)client; // the webserver tcp client connection
(void)contentType; // contentType(".html") => "text/html"
server.addHook([](const String& method, const String& url, WiFiClient* client, ESP8266WebServer::ContentTypeFunction contentType) {
(void)method; // GET, PUT, ...
(void)url; // example: /root/myfile.html
(void)client; // the webserver tcp client connection
(void)contentType; // contentType(".html") => "text/html"
Serial.printf("A useless web hook has passed\n");
Serial.printf("(this hook is in 0x%08x area (401x=IRAM 402x=FLASH))\n", esp_get_program_counter());
return ESP8266WebServer::CLIENT_REQUEST_CAN_CONTINUE;
});
server.addHook([](const String&, const String & url, WiFiClient*, ESP8266WebServer::ContentTypeFunction) {
server.addHook([](const String&, const String& url, WiFiClient*, ESP8266WebServer::ContentTypeFunction) {
if (url.startsWith("/fail")) {
Serial.printf("An always failing web hook has been triggered\n");
return ESP8266WebServer::CLIENT_MUST_STOP;
@ -107,7 +103,7 @@ void setup(void) {
return ESP8266WebServer::CLIENT_REQUEST_CAN_CONTINUE;
});
server.addHook([](const String&, const String & url, WiFiClient * client, ESP8266WebServer::ContentTypeFunction) {
server.addHook([](const String&, const String& url, WiFiClient* client, ESP8266WebServer::ContentTypeFunction) {
if (url.startsWith("/dump")) {
Serial.printf("The dumper web hook is on the run\n");
@ -137,7 +133,7 @@ void setup(void) {
// check the client connection: it should not immediately be closed
// (make another '/dump' one to close the first)
Serial.printf("\nTelling server to forget this connection\n");
static WiFiClient forgetme = *client; // stop previous one if present and transfer client refcounter
static WiFiClient forgetme = *client; // stop previous one if present and transfer client refcounter
return ESP8266WebServer::CLIENT_IS_GIVEN;
}
return ESP8266WebServer::CLIENT_REQUEST_CAN_CONTINUE;

View File

@ -18,7 +18,7 @@
#ifndef STASSID
#define STASSID "your-ssid"
#define STAPSK "your-password"
#define STAPSK "your-password"
#endif
const char* ssid = STASSID;
@ -50,7 +50,7 @@ JfUvYadSYxh3nblvA4OL+iEZiW8NE3hbW6WPXxvS7Euge0uWMPc4uEcnsE0ZVG3m
-----END CERTIFICATE-----
)EOF";
static const char serverKey[] PROGMEM = R"EOF(
static const char serverKey[] PROGMEM = R"EOF(
-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEA9UoHBtn4oNKXjRgIOQ/rLxK/iI0a8Q5mDxhfuwa9//FkftSI
IFY8UhGk2YNJpnfKOyYWqbqwuJhIZJ2sEIWp2301OnavuGBrpKOgBJJljgH2l/4Z
@ -89,24 +89,22 @@ void handleRoot() {
digitalWrite(led, 0);
}
void handleNotFound(){
void handleNotFound() {
digitalWrite(led, 1);
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET)?"GET":"POST";
message += (server.method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i=0; i<server.args(); i++){
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
for (uint8_t i = 0; i < server.args(); i++) { message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; }
server.send(404, "text/plain", message);
digitalWrite(led, 0);
}
void setup(void){
void setup(void) {
pinMode(led, OUTPUT);
digitalWrite(led, 0);
Serial.begin(115200);
@ -127,9 +125,7 @@ void setup(void){
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
if (MDNS.begin("esp8266")) { Serial.println("MDNS responder started"); }
server.getServer().setRSACert(new BearSSL::X509List(serverCert), new BearSSL::PrivateKey(serverKey));
@ -138,7 +134,7 @@ void setup(void){
server.on("/", handleRoot);
server.on("/inline", [](){
server.on("/inline", []() {
server.send(200, "text/plain", "this works as well");
});
@ -152,17 +148,20 @@ extern "C" void stack_thunk_dump_stack();
void processKey(Print& out, int hotKey) {
switch (hotKey) {
case 'd': {
case 'd':
{
HeapSelectDram ephemeral;
umm_info(NULL, true);
break;
}
case 'i': {
case 'i':
{
HeapSelectIram ephemeral;
umm_info(NULL, true);
break;
}
case 'h': {
case 'h':
{
{
HeapSelectIram ephemeral;
Serial.printf(PSTR("IRAM ESP.getFreeHeap: %u\n"), ESP.getFreeHeap());
@ -185,10 +184,8 @@ void processKey(Print& out, int hotKey) {
out.printf_P(PSTR("Restart, ESP.restart(); ...\r\n"));
ESP.restart();
break;
case '\r':
out.println();
case '\n':
break;
case '\r': out.println();
case '\n': break;
case '?':
out.println();
out.println(F("Press a key + <enter>"));
@ -211,7 +208,7 @@ void processKey(Print& out, int hotKey) {
}
void loop(void){
void loop(void) {
server.handleClient();
MDNS.update();
if (Serial.available() > 0) {

View File

@ -11,7 +11,7 @@
#ifndef STASSID
#define STASSID "your-ssid"
#define STAPSK "your-password"
#define STAPSK "your-password"
#endif
const char* ssid = STASSID;
@ -39,13 +39,13 @@ void setup() {
server.on("/", []() {
if (!server.authenticate(www_username, www_password))
//Basic Auth Method with Custom realm and Failure Response
//return server.requestAuthentication(BASIC_AUTH, www_realm, authFailResponse);
//Digest Auth Method with realm="Login Required" and empty Failure Response
//return server.requestAuthentication(DIGEST_AUTH);
//Digest Auth Method with Custom realm and empty Failure Response
//return server.requestAuthentication(DIGEST_AUTH, www_realm);
//Digest Auth Method with Custom realm and Failure Response
// Basic Auth Method with Custom realm and Failure Response
// return server.requestAuthentication(BASIC_AUTH, www_realm, authFailResponse);
// Digest Auth Method with realm="Login Required" and empty Failure Response
// return server.requestAuthentication(DIGEST_AUTH);
// Digest Auth Method with Custom realm and empty Failure Response
// return server.requestAuthentication(DIGEST_AUTH, www_realm);
// Digest Auth Method with Custom realm and Failure Response
{
return server.requestAuthentication(DIGEST_AUTH, www_realm, authFailResponse);
}

View File

@ -5,7 +5,7 @@
#ifndef STASSID
#define STASSID "your-ssid"
#define STAPSK "your-password"
#define STAPSK "your-password"
#endif
const char* ssid = STASSID;

View File

@ -15,21 +15,21 @@
#include <ESP8266WiFi.h>
#include <ESP8266WebServerSecure.h>
//Unfortunately it is not possible to have persistent WiFi credentials stored as anything but plain text. Obfuscation would be the only feasible barrier.
// Unfortunately it is not possible to have persistent WiFi credentials stored as anything but plain text. Obfuscation would be the only feasible barrier.
#ifndef STASSID
#define STASSID "your-ssid"
#define STAPSK "your-password"
#define STAPSK "your-password"
#endif
const char* ssid = STASSID;
const char* wifi_pw = STAPSK;
const String file_credentials = R"(/credentials.txt)"; // LittleFS file name for the saved credentials
const String change_creds = "changecreds"; // Address for a credential change
const String file_credentials = R"(/credentials.txt)"; // LittleFS file name for the saved credentials
const String change_creds = "changecreds"; // Address for a credential change
//The ESP8266WebServerSecure requires an encryption certificate and matching key.
//These can generated with the bash script available in the ESP8266 Arduino repository.
//These values can be used for testing but are available publicly so should not be used in production.
// The ESP8266WebServerSecure requires an encryption certificate and matching key.
// These can generated with the bash script available in the ESP8266 Arduino repository.
// These values can be used for testing but are available publicly so should not be used in production.
static const char serverCert[] PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
MIIDSzCCAjMCCQD2ahcfZAwXxDANBgkqhkiG9w0BAQsFADCBiTELMAkGA1UEBhMC
@ -52,7 +52,7 @@ JfUvYadSYxh3nblvA4OL+iEZiW8NE3hbW6WPXxvS7Euge0uWMPc4uEcnsE0ZVG3m
5tAF1D5vAAwA8nfPysumlLsIjohJZo4lgnhB++AlOg==
-----END CERTIFICATE-----
)EOF";
static const char serverKey[] PROGMEM = R"EOF(
static const char serverKey[] PROGMEM = R"EOF(
-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEA9UoHBtn4oNKXjRgIOQ/rLxK/iI0a8Q5mDxhfuwa9//FkftSI
IFY8UhGk2YNJpnfKOyYWqbqwuJhIZJ2sEIWp2301OnavuGBrpKOgBJJljgH2l/4Z
@ -84,7 +84,7 @@ gz5JWYhbD6c38khSzJb0pNXCo3EuYAVa36kDM96k1BtWuhRS10Q1VXk=
ESP8266WebServerSecure server(443);
//These are temporary credentials that will only be used if none are found saved in LittleFS.
// These are temporary credentials that will only be used if none are found saved in LittleFS.
String login = "admin";
const String realm = "global";
String H1 = "";
@ -93,16 +93,16 @@ String authentication_failed = "User authentication has failed.";
void setup() {
Serial.begin(115200);
//Initialize LittleFS to save credentials
if(!LittleFS.begin()){
Serial.println("LittleFS initialization error, programmer flash configured?");
// Initialize LittleFS to save credentials
if (!LittleFS.begin()) {
Serial.println("LittleFS initialization error, programmer flash configured?");
ESP.restart();
}
}
//Attempt to load credentials. If the file does not yet exist, they will be set to the default values above
// Attempt to load credentials. If the file does not yet exist, they will be set to the default values above
loadcredentials();
//Initialize wifi
// Initialize wifi
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, wifi_pw);
if (WiFi.waitForConnectResult() != WL_CONNECTED) {
@ -112,8 +112,8 @@ void setup() {
}
server.getServer().setRSACert(new BearSSL::X509List(serverCert), new BearSSL::PrivateKey(serverKey));
server.on("/",showcredentialpage); //for this simple example, just show a simple page for changing credentials at the root
server.on("/" + change_creds,handlecredentialchange); //handles submission of credentials from the client
server.on("/", showcredentialpage); // for this simple example, just show a simple page for changing credentials at the root
server.on("/" + change_creds, handlecredentialchange); // handles submission of credentials from the client
server.onNotFound(redirect);
server.begin();
@ -127,49 +127,48 @@ void loop() {
server.handleClient();
}
//This function redirects home
void redirect(){
// This function redirects home
void redirect() {
String url = "https://" + WiFi.localIP().toString();
Serial.println("Redirect called. Redirecting to " + url);
server.sendHeader("Location", url, true);
Serial.println("Header sent.");
server.send( 302, "text/plain", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves.
server.send(302, "text/plain", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves.
Serial.println("Empty page sent.");
server.client().stop(); // Stop is needed because we sent no content length
server.client().stop(); // Stop is needed because we sent no content length
Serial.println("Client stopped.");
}
//This function checks whether the current session has been authenticated. If not, a request for credentials is sent.
// This function checks whether the current session has been authenticated. If not, a request for credentials is sent.
bool session_authenticated() {
Serial.println("Checking authentication.");
if (server.authenticateDigest(login,H1)) {
if (server.authenticateDigest(login, H1)) {
Serial.println("Authentication confirmed.");
return true;
} else {
} else {
Serial.println("Not authenticated. Requesting credentials.");
server.requestAuthentication(DIGEST_AUTH,realm.c_str(),authentication_failed);
server.requestAuthentication(DIGEST_AUTH, realm.c_str(), authentication_failed);
redirect();
return false;
}
}
//This function sends a simple webpage for changing login credentials to the client
void showcredentialpage(){
// This function sends a simple webpage for changing login credentials to the client
void showcredentialpage() {
Serial.println("Show credential page called.");
if(!session_authenticated()){
return;
}
if (!session_authenticated()) { return; }
Serial.println("Forming credential modification page.");
String page;
page = R"(<html>)";
page+=
R"(
page +=
R"(
<h2>Login Credentials</h2><br>
<form action=")" + change_creds + R"(" method="post">
<form action=")"
+ change_creds + R"(" method="post">
Login:<br>
<input type="text" name="login"><br>
Password:<br>
@ -178,8 +177,7 @@ void showcredentialpage(){
<input type="password" name="password_duplicate"><br>
<p><button type="submit" name="newcredentials">Change Credentials</button></p>
</form><br>
)"
;
)";
page += R"(</html>)";
@ -188,17 +186,16 @@ void showcredentialpage(){
server.send(200, "text/html", page);
}
//Saves credentials to LittleFS
void savecredentials(String new_login, String new_password)
{
//Set global variables to new values
login=new_login;
H1=ESP8266WebServer::credentialHash(new_login,realm,new_password);
// Saves credentials to LittleFS
void savecredentials(String new_login, String new_password) {
// Set global variables to new values
login = new_login;
H1 = ESP8266WebServer::credentialHash(new_login, realm, new_password);
//Save new values to LittleFS for loading on next reboot
// Save new values to LittleFS for loading on next reboot
Serial.println("Saving credentials.");
File f=LittleFS.open(file_credentials,"w"); //open as a brand new file, discard old contents
if(f){
File f = LittleFS.open(file_credentials, "w"); // open as a brand new file, discard old contents
if (f) {
Serial.println("Modifying credentials in file system.");
f.println(login);
f.println(H1);
@ -209,19 +206,18 @@ void savecredentials(String new_login, String new_password)
Serial.println("Credentials saved.");
}
//loads credentials from LittleFS
void loadcredentials()
{
// loads credentials from LittleFS
void loadcredentials() {
Serial.println("Searching for credentials.");
File f;
f=LittleFS.open(file_credentials,"r");
if(f){
f = LittleFS.open(file_credentials, "r");
if (f) {
Serial.println("Loading credentials from file system.");
String mod=f.readString(); //read the file to a String
int index_1=mod.indexOf('\n',0); //locate the first line break
int index_2=mod.indexOf('\n',index_1+1); //locate the second line break
login=mod.substring(0,index_1-1); //get the first line (excluding the line break)
H1=mod.substring(index_1+1,index_2-1); //get the second line (excluding the line break)
String mod = f.readString(); // read the file to a String
int index_1 = mod.indexOf('\n', 0); // locate the first line break
int index_2 = mod.indexOf('\n', index_1 + 1); // locate the second line break
login = mod.substring(0, index_1 - 1); // get the first line (excluding the line break)
H1 = mod.substring(index_1 + 1, index_2 - 1); // get the second line (excluding the line break)
f.close();
} else {
String default_login = "admin";
@ -229,17 +225,15 @@ void loadcredentials()
Serial.println("None found. Setting to default credentials.");
Serial.println("user:" + default_login);
Serial.println("password:" + default_password);
login=default_login;
H1=ESP8266WebServer::credentialHash(default_login,realm,default_password);
login = default_login;
H1 = ESP8266WebServer::credentialHash(default_login, realm, default_password);
}
}
//This function handles a credential change from a client.
// This function handles a credential change from a client.
void handlecredentialchange() {
Serial.println("Handle credential change called.");
if(!session_authenticated()){
return;
}
if (!session_authenticated()) { return; }
Serial.println("Handling credential change request from client.");
@ -247,9 +241,9 @@ void handlecredentialchange() {
String pw1 = server.arg("password");
String pw2 = server.arg("password_duplicate");
if(login != "" && pw1 != "" && pw1 == pw2){
if (login != "" && pw1 != "" && pw1 == pw2) {
savecredentials(login,pw1);
savecredentials(login, pw1);
server.send(200, "text/plain", "Credentials updated");
redirect();
} else {

View File

@ -8,7 +8,7 @@
#ifndef STASSID
#define STASSID "your-ssid"
#define STAPSK "your-password"
#define STAPSK "your-password"
#endif
const char *ssid = STASSID;
@ -33,9 +33,7 @@ void setup(void) {
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
if (MDNS.begin("esp8266")) { Serial.println("MDNS responder started"); }
server.on(F("/"), []() {
server.send(200, "text/plain", "hello from esp8266!");

View File

@ -5,10 +5,10 @@
#ifndef STASSID
#define STASSID "your-ssid"
#define STAPSK "your-password"
#define STAPSK "your-password"
#endif
const char* ssid = STASSID;
const char* ssid = STASSID;
const char* password = STAPSK;
ESP8266WebServer server(80);
@ -62,9 +62,7 @@ void handleForm() {
} else {
digitalWrite(led, 1);
String message = "POST form was:\n";
for (uint8_t i = 0; i < server.args(); i++) {
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
for (uint8_t i = 0; i < server.args(); i++) { message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; }
server.send(200, "text/plain", message);
digitalWrite(led, 0);
}
@ -80,9 +78,7 @@ void handleNotFound() {
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i = 0; i < server.args(); i++) {
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
for (uint8_t i = 0; i < server.args(); i++) { message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; }
server.send(404, "text/plain", message);
digitalWrite(led, 0);
}
@ -105,9 +101,7 @@ void setup(void) {
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
if (MDNS.begin("esp8266")) { Serial.println("MDNS responder started"); }
server.on("/", handleRoot);

View File

@ -42,11 +42,11 @@ extern "C" {
#ifndef STASSID
#define STASSID "your-ssid"
#define STAPSK "your-password"
#define STAPSK "your-password"
#endif
const char* ssid = STASSID;
const char* password = STAPSK;
const char *ssid = STASSID;
const char *password = STAPSK;
const unsigned int port = 80;
ESP8266WebServer server(port);
@ -76,20 +76,16 @@ void handleNotFound() {
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i = 0; i < server.args(); i++) {
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
for (uint8_t i = 0; i < server.args(); i++) { message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; }
server.send(404, "text/plain", message);
}
void SSEKeepAlive() {
for (uint8_t i = 0; i < SSE_MAX_CHANNELS; i++) {
if (!(subscription[i].clientIP)) {
continue;
}
if (!(subscription[i].clientIP)) { continue; }
if (subscription[i].client.connected()) {
Serial.printf_P(PSTR("SSEKeepAlive - client is still listening on channel %d\n"), i);
subscription[i].client.println(F("event: event\ndata: { \"TYPE\":\"KEEP-ALIVE\" }\n")); // Extra newline required by SSE standard
subscription[i].client.println(F("event: event\ndata: { \"TYPE\":\"KEEP-ALIVE\" }\n")); // Extra newline required by SSE standard
} else {
Serial.printf_P(PSTR("SSEKeepAlive - client not listening on channel %d, remove subscription\n"), i);
subscription[i].keepAliveTimer.detach();
@ -106,15 +102,15 @@ void SSEKeepAlive() {
void SSEHandler(uint8_t channel) {
WiFiClient client = server.client();
SSESubscription &s = subscription[channel];
if (s.clientIP != client.remoteIP()) { // IP addresses don't match, reject this client
if (s.clientIP != client.remoteIP()) { // IP addresses don't match, reject this client
Serial.printf_P(PSTR("SSEHandler - unregistered client with IP %s tries to listen\n"), server.client().remoteIP().toString().c_str());
return handleNotFound();
}
client.setNoDelay(true);
client.setSync(true);
Serial.printf_P(PSTR("SSEHandler - registered client with IP %s is listening\n"), IPAddress(s.clientIP).toString().c_str());
s.client = client; // capture SSE server client connection
server.setContentLength(CONTENT_LENGTH_UNKNOWN); // the payload can go on forever
s.client = client; // capture SSE server client connection
server.setContentLength(CONTENT_LENGTH_UNKNOWN); // the payload can go on forever
server.sendContent_P(PSTR("HTTP/1.1 200 OK\nContent-Type: text/event-stream;\nConnection: keep-alive\nCache-Control: no-cache\nAccess-Control-Allow-Origin: *\n\n"));
s.keepAliveTimer.attach_scheduled(30.0, SSEKeepAlive); // Refresh time every 30s for demo
}
@ -122,28 +118,20 @@ void SSEHandler(uint8_t channel) {
void handleAll() {
const char *uri = server.uri().c_str();
const char *restEvents = PSTR("/rest/events/");
if (strncmp_P(uri, restEvents, strlen_P(restEvents))) {
return handleNotFound();
}
uri += strlen_P(restEvents); // Skip the "/rest/events/" and get to the channel number
if (strncmp_P(uri, restEvents, strlen_P(restEvents))) { return handleNotFound(); }
uri += strlen_P(restEvents); // Skip the "/rest/events/" and get to the channel number
unsigned int channel = atoi(uri);
if (channel < SSE_MAX_CHANNELS) {
return SSEHandler(channel);
}
if (channel < SSE_MAX_CHANNELS) { return SSEHandler(channel); }
handleNotFound();
};
void SSEBroadcastState(const char *sensorName, unsigned short prevSensorValue, unsigned short sensorValue) {
for (uint8_t i = 0; i < SSE_MAX_CHANNELS; i++) {
if (!(subscription[i].clientIP)) {
continue;
}
if (!(subscription[i].clientIP)) { continue; }
String IPaddrstr = IPAddress(subscription[i].clientIP).toString();
if (subscription[i].client.connected()) {
Serial.printf_P(PSTR("broadcast status change to client IP %s on channel %d for %s with new state %d\n"),
IPaddrstr.c_str(), i, sensorName, sensorValue);
subscription[i].client.printf_P(PSTR("event: event\ndata: {\"TYPE\":\"STATE\", \"%s\":{\"state\":%d, \"prevState\":%d}}\n\n"),
sensorName, sensorValue, prevSensorValue);
Serial.printf_P(PSTR("broadcast status change to client IP %s on channel %d for %s with new state %d\n"), IPaddrstr.c_str(), i, sensorName, sensorValue);
subscription[i].client.printf_P(PSTR("event: event\ndata: {\"TYPE\":\"STATE\", \"%s\":{\"state\":%d, \"prevState\":%d}}\n\n"), sensorName, sensorValue, prevSensorValue);
} else {
Serial.printf_P(PSTR("SSEBroadcastState - client %s registered on channel %d but not listening\n"), IPaddrstr.c_str(), i);
}
@ -152,7 +140,7 @@ void SSEBroadcastState(const char *sensorName, unsigned short prevSensorValue, u
// Simulate sensors
void updateSensor(sensorType &sensor) {
unsigned short newVal = (unsigned short)RANDOM_REG32; // (not so good) random value for the sensor
unsigned short newVal = (unsigned short)RANDOM_REG32; // (not so good) random value for the sensor
Serial.printf_P(PSTR("update sensor %s - previous state: %d, new state: %d\n"), sensor.name, sensor.value, newVal);
if (sensor.value != newVal) {
SSEBroadcastState(sensor.name, sensor.value, newVal); // only broadcast if state is different
@ -167,7 +155,7 @@ void handleSubscribe() {
}
uint8_t channel;
IPAddress clientIP = server.client().remoteIP(); // get IP address of client
IPAddress clientIP = server.client().remoteIP(); // get IP address of client
String SSEurl = F("http://");
SSEurl += WiFi.localIP().toString();
SSEurl += F(":");
@ -176,14 +164,12 @@ void handleSubscribe() {
SSEurl += F("/rest/events/");
++subscriptionCount;
for (channel = 0; channel < SSE_MAX_CHANNELS; channel++) // Find first free slot
if (!subscription[channel].clientIP) {
break;
}
subscription[channel] = {clientIP, server.client(), Ticker()};
for (channel = 0; channel < SSE_MAX_CHANNELS; channel++) // Find first free slot
if (!subscription[channel].clientIP) { break; }
subscription[channel] = { clientIP, server.client(), Ticker() };
SSEurl += channel;
Serial.printf_P(PSTR("Allocated channel %d, on uri %s\n"), channel, SSEurl.substring(offset).c_str());
//server.on(SSEurl.substring(offset), std::bind(SSEHandler, &(subscription[channel])));
// server.on(SSEurl.substring(offset), std::bind(SSEHandler, &(subscription[channel])));
Serial.printf_P(PSTR("subscription for client IP %s: event bus location: %s\n"), clientIP.toString().c_str(), SSEurl.c_str());
server.send_P(200, "text/plain", SSEurl.c_str());
}
@ -200,16 +186,14 @@ void setup(void) {
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("");
while (WiFi.status() != WL_CONNECTED) { // Wait for connection
while (WiFi.status() != WL_CONNECTED) { // Wait for connection
delay(500);
Serial.print(".");
}
Serial.printf_P(PSTR("\nConnected to %s with IP address: %s\n"), ssid, WiFi.localIP().toString().c_str());
if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}
if (MDNS.begin("esp8266")) { Serial.println("MDNS responder started"); }
startServers(); // start web and SSE servers
startServers(); // start web and SSE servers
sensor[0].name = "sensorA";
sensor[1].name = "sensorB";
updateSensor(sensor[0]);

View File

@ -4,7 +4,7 @@
#ifndef STASSID
#define STASSID "your-ssid"
#define STAPSK "your-password"
#define STAPSK "your-password"
#endif
const char* ssid = STASSID;
@ -12,7 +12,7 @@ const char* password = STAPSK;
ESP8266WebServer server(80);
//Check if header is present and correct
// Check if header is present and correct
bool is_authenticated() {
Serial.println("Enter is_authenticated");
if (server.hasHeader("Cookie")) {
@ -28,7 +28,7 @@ bool is_authenticated() {
return false;
}
//login page, also called for disconnect
// login page, also called for disconnect
void handleLogin() {
String msg;
if (server.hasHeader("Cookie")) {
@ -45,7 +45,7 @@ void handleLogin() {
return;
}
if (server.hasArg("USERNAME") && server.hasArg("PASSWORD")) {
if (server.arg("USERNAME") == "admin" && server.arg("PASSWORD") == "admin") {
if (server.arg("USERNAME") == "admin" && server.arg("PASSWORD") == "admin") {
server.sendHeader("Location", "/");
server.sendHeader("Cache-Control", "no-cache");
server.sendHeader("Set-Cookie", "ESPSESSIONID=1");
@ -64,7 +64,7 @@ void handleLogin() {
server.send(200, "text/html", content);
}
//root page can be accessed only if authentication is ok
// root page can be accessed only if authentication is ok
void handleRoot() {
Serial.println("Enter handleRoot");
String header;
@ -75,14 +75,12 @@ void handleRoot() {
return;
}
String content = "<html><body><H2>hello, you successfully connected to esp8266!</H2><br>";
if (server.hasHeader("User-Agent")) {
content += "the user agent used is : " + server.header("User-Agent") + "<br><br>";
}
if (server.hasHeader("User-Agent")) { content += "the user agent used is : " + server.header("User-Agent") + "<br><br>"; }
content += "You can access this page until you <a href=\"/login?DISCONNECT=YES\">disconnect</a></body></html>";
server.send(200, "text/html", content);
}
//no need authentication
// no need authentication
void handleNotFound() {
String message = "File Not Found\n\n";
message += "URI: ";
@ -92,9 +90,7 @@ void handleNotFound() {
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i = 0; i < server.args(); i++) {
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
for (uint8_t i = 0; i < server.args(); i++) { message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; }
server.send(404, "text/plain", message);
}
@ -123,7 +119,7 @@ void setup(void) {
});
server.onNotFound(handleNotFound);
//ask server to track these headers
// ask server to track these headers
server.collectHeaders("User-Agent", "Cookie");
server.begin();
Serial.println("HTTP server started");

View File

@ -9,10 +9,10 @@
#include <Arduino.h>
#include <ESP8266WebServer.h>
#include "secrets.h" // add WLAN Credentials in here.
#include "secrets.h" // add WLAN Credentials in here.
#include <FS.h> // File System for Web Server Files
#include <LittleFS.h> // This file system is used.
#include <FS.h> // File System for Web Server Files
#include <LittleFS.h> // This file system is used.
// mark parameters not used in example
#define UNUSED __attribute__((unused))
@ -41,13 +41,11 @@ void handleRedirect() {
TRACE("Redirect...");
String url = "/index.htm";
if (!LittleFS.exists(url)) {
url = "/$update.htm";
}
if (!LittleFS.exists(url)) { url = "/$update.htm"; }
server.sendHeader("Location", url, true);
server.send(302);
} // handleRedirect()
} // handleRedirect()
// This function is called when the WebServer was requested to list all existing files in the filesystem.
@ -58,20 +56,18 @@ void handleListFiles() {
result += "[\n";
while (dir.next()) {
if (result.length() > 4) {
result += ",";
}
if (result.length() > 4) { result += ","; }
result += " {";
result += " \"name\": \"" + dir.fileName() + "\", ";
result += " \"size\": " + String(dir.fileSize()) + ", ";
result += " \"time\": " + String(dir.fileTime());
result += " }\n";
// jc.addProperty("size", dir.fileSize());
} // while
} // while
result += "]";
server.sendHeader("Cache-Control", "no-cache");
server.send(200, "text/javascript; charset=utf-8", result);
} // handleListFiles()
} // handleListFiles()
// This function is called when the sysInfo service was requested.
@ -90,96 +86,84 @@ void handleSysInfo() {
server.sendHeader("Cache-Control", "no-cache");
server.send(200, "text/javascript; charset=utf-8", result);
} // handleSysInfo()
} // handleSysInfo()
// ===== Request Handler class used to answer more complex requests =====
// The FileServerHandler is registered to the web server to support DELETE and UPLOAD of files into the filesystem.
class FileServerHandler : public RequestHandler {
public:
// @brief Construct a new File Server Handler object
// @param fs The file system to be used.
// @param path Path to the root folder in the file system that is used for serving static data down and upload.
// @param cache_header Cache Header to be used in replies.
FileServerHandler() {
TRACE("FileServerHandler is registered\n");
}
public:
// @brief Construct a new File Server Handler object
// @param fs The file system to be used.
// @param path Path to the root folder in the file system that is used for serving static data down and upload.
// @param cache_header Cache Header to be used in replies.
FileServerHandler() {
TRACE("FileServerHandler is registered\n");
}
// @brief check incoming request. Can handle POST for uploads and DELETE.
// @param requestMethod method of the http request line.
// @param requestUri request ressource from the http request line.
// @return true when method can be handled.
bool canHandle(HTTPMethod requestMethod, const String UNUSED &_uri) override {
return ((requestMethod == HTTP_POST) || (requestMethod == HTTP_DELETE));
} // canHandle()
// @brief check incoming request. Can handle POST for uploads and DELETE.
// @param requestMethod method of the http request line.
// @param requestUri request ressource from the http request line.
// @return true when method can be handled.
bool canHandle(HTTPMethod requestMethod, const String UNUSED &_uri) override {
return ((requestMethod == HTTP_POST) || (requestMethod == HTTP_DELETE));
} // canHandle()
bool canUpload(const String &uri) override {
// only allow upload on root fs level.
return (uri == "/");
} // canUpload()
bool canUpload(const String &uri) override {
// only allow upload on root fs level.
return (uri == "/");
} // canUpload()
bool handle(ESP8266WebServer &server, HTTPMethod requestMethod, const String &requestUri) override {
// ensure that filename starts with '/'
String fName = requestUri;
if (!fName.startsWith("/")) {
fName = "/" + fName;
}
bool handle(ESP8266WebServer &server, HTTPMethod requestMethod, const String &requestUri) override {
// ensure that filename starts with '/'
String fName = requestUri;
if (!fName.startsWith("/")) { fName = "/" + fName; }
if (requestMethod == HTTP_POST) {
// all done in upload. no other forms.
if (requestMethod == HTTP_POST) {
// all done in upload. no other forms.
} else if (requestMethod == HTTP_DELETE) {
if (LittleFS.exists(fName)) {
LittleFS.remove(fName);
}
} // if
} else if (requestMethod == HTTP_DELETE) {
if (LittleFS.exists(fName)) { LittleFS.remove(fName); }
} // if
server.send(200); // all done.
return (true);
} // handle()
server.send(200); // all done.
return (true);
} // handle()
// uploading process
void upload(ESP8266WebServer UNUSED &server, const String UNUSED &_requestUri, HTTPUpload &upload) override {
// ensure that filename starts with '/'
String fName = upload.filename;
if (!fName.startsWith("/")) {
fName = "/" + fName;
}
// uploading process
void upload(ESP8266WebServer UNUSED &server, const String UNUSED &_requestUri, HTTPUpload &upload) override {
// ensure that filename starts with '/'
String fName = upload.filename;
if (!fName.startsWith("/")) { fName = "/" + fName; }
if (upload.status == UPLOAD_FILE_START) {
// Open the file
if (LittleFS.exists(fName)) {
LittleFS.remove(fName);
} // if
_fsUploadFile = LittleFS.open(fName, "w");
if (upload.status == UPLOAD_FILE_START) {
// Open the file
if (LittleFS.exists(fName)) { LittleFS.remove(fName); } // if
_fsUploadFile = LittleFS.open(fName, "w");
} else if (upload.status == UPLOAD_FILE_WRITE) {
// Write received bytes
if (_fsUploadFile) {
_fsUploadFile.write(upload.buf, upload.currentSize);
}
} else if (upload.status == UPLOAD_FILE_WRITE) {
// Write received bytes
if (_fsUploadFile) { _fsUploadFile.write(upload.buf, upload.currentSize); }
} else if (upload.status == UPLOAD_FILE_END) {
// Close the file
if (_fsUploadFile) {
_fsUploadFile.close();
}
} // if
} // upload()
} else if (upload.status == UPLOAD_FILE_END) {
// Close the file
if (_fsUploadFile) { _fsUploadFile.close(); }
} // if
} // upload()
protected:
File _fsUploadFile;
protected:
File _fsUploadFile;
};
// Setup everything to make the webserver work.
void setup(void) {
delay(3000); // wait for serial monitor to start completely.
delay(3000); // wait for serial monitor to start completely.
// Use Serial port for some trace information from the example
Serial.begin(115200);
@ -250,12 +234,12 @@ void setup(void) {
server.begin();
TRACE("hostname=%s\n", WiFi.getHostname());
} // setup
} // setup
// run the server...
void loop(void) {
server.handleClient();
} // loop()
} // loop()
// end.

View File

@ -9,7 +9,7 @@
#ifndef STASSID
#define STASSID "your-ssid"
#define STAPSK "your-password"
#define STAPSK "your-password"
#endif
const char* host = "esp8266-webupdate";
@ -31,34 +31,36 @@ void setup(void) {
server.sendHeader("Connection", "close");
server.send(200, "text/html", serverIndex);
});
server.on("/update", HTTP_POST, []() {
server.sendHeader("Connection", "close");
server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
ESP.restart();
}, []() {
HTTPUpload& upload = server.upload();
if (upload.status == UPLOAD_FILE_START) {
Serial.setDebugOutput(true);
WiFiUDP::stopAll();
Serial.printf("Update: %s\n", upload.filename.c_str());
uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
if (!Update.begin(maxSketchSpace)) { //start with max available size
Update.printError(Serial);
server.on(
"/update", HTTP_POST, []() {
server.sendHeader("Connection", "close");
server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
ESP.restart();
},
[]() {
HTTPUpload& upload = server.upload();
if (upload.status == UPLOAD_FILE_START) {
Serial.setDebugOutput(true);
WiFiUDP::stopAll();
Serial.printf("Update: %s\n", upload.filename.c_str());
uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
if (!Update.begin(maxSketchSpace)) { // start with max available size
Update.printError(Serial);
}
} else if (upload.status == UPLOAD_FILE_WRITE) {
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);
}
Serial.setDebugOutput(false);
}
} else if (upload.status == UPLOAD_FILE_WRITE) {
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);
}
Serial.setDebugOutput(false);
}
yield();
});
yield();
});
server.begin();
MDNS.addService("http", "tcp", 80);