serve the webapp from esp8266

This commit is contained in:
2019-08-06 17:59:47 +03:00
parent ccde6e8ae5
commit fb1ed0515f
5 changed files with 51 additions and 1 deletions

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -4,6 +4,7 @@
#include <Arduino.h> #include <Arduino.h>
#include <ESP8266WebServer.h> #include <ESP8266WebServer.h>
#include <ArduinoJson.h> #include <ArduinoJson.h>
#include <FS.h>
class WebAPI { class WebAPI {
private: private:
@@ -11,6 +12,8 @@ class WebAPI {
void handlePutCommand(); void handlePutCommand();
void handleGetStatus(); void handleGetStatus();
void sendCORS(); void sendCORS();
bool getFile(String filename);
String getContentType(String filename);
String getStatusJson(); String getStatusJson();
public: public:

View File

@@ -24,6 +24,49 @@ String WebAPI::getStatusJson() {
return out; return out;
} }
String WebAPI::getContentType(String filename) {
if (server.hasArg("download")) {
return "application/octet-stream";
} else if (filename.endsWith(".html")) {
return "text/html";
} else if (filename.endsWith(".css")) {
return "text/css";
} else if (filename.endsWith(".js")) {
return "application/javascript";
} else if (filename.endsWith(".png")) {
return "image/png";
} else if (filename.endsWith(".gif")) {
return "image/gif";
} else if (filename.endsWith(".jpg")) {
return "image/jpeg";
} else if (filename.endsWith(".ico")) {
return "image/x-icon";
} else if (filename.endsWith(".xml")) {
return "text/xml";
} else if (filename.endsWith(".gz")) {
return "application/x-gzip";
}
return "text/plain";
}
bool WebAPI::getFile(String filename) {
if (filename.endsWith("/")) {
filename += "index.html";
}
String contentType = getContentType(filename);
String pathWithGz = filename + ".gz";
if (SPIFFS.exists(pathWithGz) || SPIFFS.exists(filename)) {
if (SPIFFS.exists(pathWithGz)) {
filename += ".gz";
}
File file = SPIFFS.open(filename, "r");
server.streamFile(file, contentType);
file.close();
return true;
}
return false;
}
void WebAPI::sendCORS() { void WebAPI::sendCORS() {
server.sendHeader("Access-Control-Allow-Origin", "*"); server.sendHeader("Access-Control-Allow-Origin", "*");
server.sendHeader("Access-Control-Max-Age", "10000"); server.sendHeader("Access-Control-Max-Age", "10000");
@@ -38,9 +81,11 @@ void WebAPI::handleNotFound() {
sendCORS(); sendCORS();
server.send(204); server.send(204);
} else { } else {
if (!getFile(server.uri())) {
server.send(404, "text/plain", ""); server.send(404, "text/plain", "");
} }
} }
}
void WebAPI::handlePutCommand() { void WebAPI::handlePutCommand() {
sendCORS(); sendCORS();
@@ -61,6 +106,8 @@ void WebAPI::init() {
std::bind(&WebAPI::handleGetStatus, this)); std::bind(&WebAPI::handleGetStatus, this));
server.onNotFound(std::bind(&WebAPI::handleNotFound, this)); server.onNotFound(std::bind(&WebAPI::handleNotFound, this));
SPIFFS.begin();
server.begin(); server.begin();
} }