Merge pull request #318 from IoTManagerProject/ver4dev

кеширование
This commit is contained in:
IoT Manager
2023-10-02 12:36:07 +02:00
committed by GitHub
2 changed files with 262 additions and 383 deletions

View File

@@ -7,24 +7,21 @@ String unsupportedFiles = String();
static const char TEXT_PLAIN[] PROGMEM = "text/plain"; static const char TEXT_PLAIN[] PROGMEM = "text/plain";
static const char FS_INIT_ERROR[] PROGMEM = "FS INIT ERROR"; static const char FS_INIT_ERROR[] PROGMEM = "FS INIT ERROR";
static const char FILE_NOT_FOUND[] PROGMEM = "FileNotFound"; static const char FILE_NOT_FOUND[] PROGMEM = "FileNotFound";
//static bool fsOK; // static bool fsOK;
//const char* fsName = "LittleFS"; // const char* fsName = "LittleFS";
void standWebServerInit() void standWebServerInit() {
{
// Кэшировать файлы для быстрой работы // Кэшировать файлы для быстрой работы
HTTP.serveStatic("/bundle.js", FileFS, "/", "max-age=31536000"); // кеширование на 1 год HTTP.serveStatic("/build/bundle.js", FileFS, "/build/bundle.js.gz", "max-age=31536000"); // кеширование на 1 год
HTTP.serveStatic("/bundle.css", FileFS, "/", "max-age=31536000"); // кеширование на 1 год HTTP.serveStatic("/build/bundle.css", FileFS, "/build/bundle.css.gz", "max-age=31536000"); // кеширование на 1 год
HTTP.serveStatic("/bundle.js.gz", FileFS, "/", "max-age=31536000"); // кеширование на 1 год HTTP.serveStatic("/favicon.ico", FileFS, "/favicon.ico", "max-age=31536000"); // кеширование на 1 год
HTTP.serveStatic("/bundle.css.gz", FileFS, "/", "max-age=31536000"); // кеширование на 1 год
HTTP.serveStatic("/favicon.png", FileFS, "/", "max-age=31536000"); // кеширование на 1 год
// HTTP.on("/devicelist.json", HTTP_GET, []() { // HTTP.on("/devicelist.json", HTTP_GET, []() {
// HTTP.send(200, "application/json", devListHeapJson); // HTTP.send(200, "application/json", devListHeapJson);
// }); // });
HTTP.on("/settings.h.json", HTTP_GET, []() { // HTTP.on("/settings.h.json", HTTP_GET, []() {
HTTP.send(200, "application/json", settingsFlashJson); // HTTP.send(200, "application/json", settingsFlashJson);
}); //});
// HTTP.on("/settings.f.json", HTTP_GET, []() { // HTTP.on("/settings.f.json", HTTP_GET, []() {
// HTTP.send(200, "application/json", readFile(F("settings.json"), 20000)); // HTTP.send(200, "application/json", readFile(F("settings.json"), 20000));
// }); // });
@@ -46,21 +43,19 @@ void standWebServerInit()
// HTTP.send(200, "text/plain", "ok"); // HTTP.send(200, "text/plain", "ok");
// }); // });
HTTP.on("/set", HTTP_GET, []() { HTTP.on("/set", HTTP_GET, []() {
if (HTTP.hasArg(F("routerssid")) && WiFi.getMode() == WIFI_AP) { if (HTTP.hasArg(F("routerssid")) && WiFi.getMode() == WIFI_AP) {
jsonWriteStr(settingsFlashJson, F("routerssid"), HTTP.arg(F("routerssid"))); jsonWriteStr(settingsFlashJson, F("routerssid"), HTTP.arg(F("routerssid")));
syncSettingsFlashJson(); syncSettingsFlashJson();
HTTP.send(200, "text/plain", "ok"); HTTP.send(200, "text/plain", "ok");
} }
if (HTTP.hasArg(F("routerpass")) && WiFi.getMode() == WIFI_AP) { if (HTTP.hasArg(F("routerpass")) && WiFi.getMode() == WIFI_AP) {
jsonWriteStr(settingsFlashJson, F("routerpass"), HTTP.arg(F("routerpass"))); jsonWriteStr(settingsFlashJson, F("routerpass"), HTTP.arg(F("routerpass")));
syncSettingsFlashJson(); syncSettingsFlashJson();
HTTP.send(200, "text/plain", "ok"); HTTP.send(200, "text/plain", "ok");
} }
});
});
// Добавляем функцию Update для перезаписи прошивки по WiFi при 1М(256K FileFS) и выше // Добавляем функцию Update для перезаписи прошивки по WiFi при 1М(256K FileFS) и выше
// httpUpdater.setup(&HTTP); // httpUpdater.setup(&HTTP);
@@ -101,39 +96,33 @@ void standWebServerInit()
//////////////////////////////// ////////////////////////////////
// Utils to return HTTP codes, and determine content-type // Utils to return HTTP codes, and determine content-type
void replyOK() void replyOK() {
{
HTTP.send(200, FPSTR(TEXT_PLAIN), ""); HTTP.send(200, FPSTR(TEXT_PLAIN), "");
} }
void replyOKWithMsg(String msg) void replyOKWithMsg(String msg) {
{
HTTP.send(200, FPSTR(TEXT_PLAIN), msg); HTTP.send(200, FPSTR(TEXT_PLAIN), msg);
} }
void replyNotFound(String msg) void replyNotFound(String msg) {
{
HTTP.send(404, FPSTR(TEXT_PLAIN), msg); HTTP.send(404, FPSTR(TEXT_PLAIN), msg);
} }
void replyBadRequest(String msg) void replyBadRequest(String msg) {
{ // DBG_OUTPUT_PORT.println(msg);
// DBG_OUTPUT_PORT.println(msg);
HTTP.send(400, FPSTR(TEXT_PLAIN), msg + "\r\n"); HTTP.send(400, FPSTR(TEXT_PLAIN), msg + "\r\n");
} }
void replyServerError(String msg) void replyServerError(String msg) {
{ // DBG_OUTPUT_PORT.println(msg);
// DBG_OUTPUT_PORT.println(msg);
HTTP.send(500, FPSTR(TEXT_PLAIN), msg + "\r\n"); HTTP.send(500, FPSTR(TEXT_PLAIN), msg + "\r\n");
} }
/* /*
Return the FS type, status and size info Return the FS type, status and size info
*/ */
void handleStatus() void handleStatus() {
{ // DBG_OUTPUT_PORT.println("handleStatus");
// DBG_OUTPUT_PORT.println("handleStatus");
String json; String json;
json.reserve(128); json.reserve(128);
@@ -141,22 +130,22 @@ void handleStatus()
json += FS_NAME; json += FS_NAME;
json += "\", \"isOk\":"; json += "\", \"isOk\":";
#ifdef ESP8266 #ifdef ESP8266
FSInfo fs_info; FSInfo fs_info;
FileFS.info(fs_info); FileFS.info(fs_info);
json += F("\"true\", \"totalBytes\":\""); json += F("\"true\", \"totalBytes\":\"");
json += fs_info.totalBytes; json += fs_info.totalBytes;
json += F("\", \"usedBytes\":\""); json += F("\", \"usedBytes\":\"");
json += fs_info.usedBytes; json += fs_info.usedBytes;
json += "\""; json += "\"";
#endif #endif
#ifdef ESP32 #ifdef ESP32
json += F("\"true\", \"totalBytes\":\""); json += F("\"true\", \"totalBytes\":\"");
json += String(FileFS.totalBytes()); json += String(FileFS.totalBytes());
json += F("\", \"usedBytes\":\""); json += F("\", \"usedBytes\":\"");
json += String(FileFS.usedBytes()); json += String(FileFS.usedBytes());
json += "\""; json += "\"";
#endif #endif
json += F(",\"unsupportedFiles\":\""); json += F(",\"unsupportedFiles\":\"");
@@ -168,74 +157,66 @@ void handleStatus()
#ifdef ESP32 #ifdef ESP32
String getContentType(String filename) { String getContentType(String filename) {
if (HTTP.hasArg("download")) { if (HTTP.hasArg("download")) {
return "application/octet-stream"; return "application/octet-stream";
} else if (filename.endsWith(".htm")) { } else if (filename.endsWith(".htm")) {
return "text/html"; return "text/html";
} else if (filename.endsWith(".html")) { } else if (filename.endsWith(".html")) {
return "text/html"; return "text/html";
} else if (filename.endsWith(".css")) { } else if (filename.endsWith(".css")) {
return "text/css"; return "text/css";
} else if (filename.endsWith(".js")) { } else if (filename.endsWith(".js")) {
return "application/javascript"; return "application/javascript";
} else if (filename.endsWith(".png")) { } else if (filename.endsWith(".png")) {
return "image/png"; return "image/png";
} else if (filename.endsWith(".gif")) { } else if (filename.endsWith(".gif")) {
return "image/gif"; return "image/gif";
} else if (filename.endsWith(".jpg")) { } else if (filename.endsWith(".jpg")) {
return "image/jpeg"; return "image/jpeg";
} else if (filename.endsWith(".ico")) { } else if (filename.endsWith(".ico")) {
return "image/x-icon"; return "image/x-icon";
} else if (filename.endsWith(".xml")) { } else if (filename.endsWith(".xml")) {
return "text/xml"; return "text/xml";
} else if (filename.endsWith(".pdf")) { } else if (filename.endsWith(".pdf")) {
return "application/x-pdf"; return "application/x-pdf";
} else if (filename.endsWith(".zip")) { } else if (filename.endsWith(".zip")) {
return "application/x-zip"; return "application/x-zip";
} else if (filename.endsWith(".gz")) { } else if (filename.endsWith(".gz")) {
return "application/x-gzip"; return "application/x-gzip";
} }
return "text/plain"; return "text/plain";
} }
#endif #endif
/* /*
Read the given file from the filesystem and stream it back to the client Read the given file from the filesystem and stream it back to the client
*/ */
bool handleFileRead(String path) bool handleFileRead(String path) {
{ // DBG_OUTPUT_PORT.println(String("handleFileRead: ") + path);
// DBG_OUTPUT_PORT.println(String("handleFileRead: ") + path); if (path.endsWith("/")) {
if (path.endsWith("/"))
{
path += "index.html"; path += "index.html";
} }
String contentType; String contentType;
if (HTTP.hasArg("download")) if (HTTP.hasArg("download")) {
{
contentType = F("application/octet-stream"); contentType = F("application/octet-stream");
} } else {
else #ifdef ESP32
{
#ifdef ESP32
contentType = getContentType(path); contentType = getContentType(path);
#endif #endif
#ifdef ESP8266 #ifdef ESP8266
contentType = mime::getContentType(path); contentType = mime::getContentType(path);
#endif #endif
} }
if (!FileFS.exists(path)) if (!FileFS.exists(path)) {
{
// File not found, try gzip version // File not found, try gzip version
path = path + ".gz"; path = path + ".gz";
} }
if (FileFS.exists(path)) if (FileFS.exists(path)) {
{
File file = FileFS.open(path, "r"); File file = FileFS.open(path, "r");
if (HTTP.streamFile(file, contentType) != file.size()) if (HTTP.streamFile(file, contentType) != file.size()) {
{ // DBG_OUTPUT_PORT.println("Sent less data than expected!");
// DBG_OUTPUT_PORT.println("Sent less data than expected!");
} }
file.close(); file.close();
return true; return true;
@@ -248,90 +229,69 @@ bool handleFileRead(String path)
As some FS (e.g. LittleFS) delete the parent folder when the last child has been removed, As some FS (e.g. LittleFS) delete the parent folder when the last child has been removed,
return the path of the closest parent still existing return the path of the closest parent still existing
*/ */
String lastExistingParent(String path) String lastExistingParent(String path) {
{ while (!path.isEmpty() && !FileFS.exists(path)) {
while (!path.isEmpty() && !FileFS.exists(path)) if (path.lastIndexOf('/') > 0) {
{
if (path.lastIndexOf('/') > 0)
{
path = path.substring(0, path.lastIndexOf('/')); path = path.substring(0, path.lastIndexOf('/'));
} } else {
else path = String(); // No slash => the top folder does not exist
{
path = String(); // No slash => the top folder does not exist
} }
} }
// DBG_OUTPUT_PORT.println(String("Last existing parent: ") + path); // DBG_OUTPUT_PORT.println(String("Last existing parent: ") + path);
return path; return path;
} }
/* /*
Handle a file upload request Handle a file upload request
*/ */
void handleFileUpload() void handleFileUpload() {
{ if (HTTP.uri() != "/edit") {
if (HTTP.uri() != "/edit")
{
return; return;
} }
HTTPUpload &upload = HTTP.upload(); HTTPUpload &upload = HTTP.upload();
if (upload.status == UPLOAD_FILE_START) if (upload.status == UPLOAD_FILE_START) {
{
String filename = upload.filename; String filename = upload.filename;
// Make sure paths always start with "/" // Make sure paths always start with "/"
if (!filename.startsWith("/")) if (!filename.startsWith("/")) {
{
filename = "/" + filename; filename = "/" + filename;
} }
// DBG_OUTPUT_PORT.println(String("handleFileUpload Name: ") + filename); // DBG_OUTPUT_PORT.println(String("handleFileUpload Name: ") + filename);
uploadFile = FileFS.open(filename, "w"); uploadFile = FileFS.open(filename, "w");
if (!uploadFile) if (!uploadFile) {
{
return replyServerError(F("CREATE FAILED")); return replyServerError(F("CREATE FAILED"));
} }
// DBG_OUTPUT_PORT.println(String("Upload: START, filename: ") + filename); // DBG_OUTPUT_PORT.println(String("Upload: START, filename: ") + filename);
} } else if (upload.status == UPLOAD_FILE_WRITE) {
else if (upload.status == UPLOAD_FILE_WRITE) if (uploadFile) {
{
if (uploadFile)
{
size_t bytesWritten = uploadFile.write(upload.buf, upload.currentSize); size_t bytesWritten = uploadFile.write(upload.buf, upload.currentSize);
if (bytesWritten != upload.currentSize) if (bytesWritten != upload.currentSize) {
{
return replyServerError(F("WRITE FAILED")); return replyServerError(F("WRITE FAILED"));
} }
} }
// DBG_OUTPUT_PORT.println(String("Upload: WRITE, Bytes: ") + upload.currentSize); // DBG_OUTPUT_PORT.println(String("Upload: WRITE, Bytes: ") + upload.currentSize);
} } else if (upload.status == UPLOAD_FILE_END) {
else if (upload.status == UPLOAD_FILE_END) if (uploadFile) {
{
if (uploadFile)
{
uploadFile.close(); uploadFile.close();
} }
// DBG_OUTPUT_PORT.println(String("Upload: END, Size: ") + upload.totalSize); // DBG_OUTPUT_PORT.println(String("Upload: END, Size: ") + upload.totalSize);
} }
} }
#ifdef ESP8266 #ifdef ESP8266
void deleteRecursive(String path) void deleteRecursive(String path) {
{
File file = FileFS.open(path, "r"); File file = FileFS.open(path, "r");
bool isDir = file.isDirectory(); bool isDir = file.isDirectory();
file.close(); file.close();
// If it's a plain file, delete it // If it's a plain file, delete it
if (!isDir) if (!isDir) {
{
FileFS.remove(path); FileFS.remove(path);
return; return;
} }
Dir dir = FileFS.openDir(path); Dir dir = FileFS.openDir(path);
while (dir.next()) while (dir.next()) {
{
deleteRecursive(path + '/' + dir.fileName()); deleteRecursive(path + '/' + dir.fileName());
} }
// Then delete the folder itself // Then delete the folder itself
FileFS.rmdir(path); FileFS.rmdir(path);
@@ -339,41 +299,37 @@ void deleteRecursive(String path)
#endif #endif
#ifdef ESP32 #ifdef ESP32
struct treename{ struct treename {
uint8_t type; uint8_t type;
char *name; char *name;
}; };
void deleteRecursive(String path) {
fs::File dir = FileFS.open(path);
void deleteRecursive( String path ){ if (!dir.isDirectory()) {
fs::File dir = FileFS.open( path ); Serial.printf("%s is a file\n", path);
dir.close();
if(!dir.isDirectory()){ Serial.printf("result of removing file %s: %d\n", path, FileFS.remove(path));
Serial.printf("%s is a file\n", path); return;
dir.close();
Serial.printf( "result of removing file %s: %d\n", path, FileFS.remove( path ) );
return;
} }
Serial.printf("%s is a directory\n", path); Serial.printf("%s is a directory\n", path);
fs::File entry, nextentry; fs::File entry, nextentry;
while ( entry = dir.openNextFile() ){ while (entry = dir.openNextFile()) {
if (entry.isDirectory()) {
if ( entry.isDirectory() ){ deleteRecursive(entry.path());
deleteRecursive( entry.path() ); } else {
} else{ String tmpname = path + "/" + strdup(entry.name()); // buffer file name
String tmpname = path+"/"+strdup( entry.name() ); // buffer file name entry.close();
entry.close(); Serial.printf("result of removing file %s: %d\n", tmpname, FileFS.remove(tmpname));
Serial.printf( "result of removing file %s: %d\n", tmpname, FileFS.remove( tmpname ) ); }
}
} }
dir.close(); dir.close();
Serial.printf( "result of removing directory %s: %d\n", path, FileFS.rmdir( path ) ); Serial.printf("result of removing directory %s: %d\n", path, FileFS.rmdir(path));
} }
#endif #endif
/* /*
@@ -383,23 +339,18 @@ if ( entry.isDirectory() ){
Delete file | parent of deleted file, or remaining ancestor Delete file | parent of deleted file, or remaining ancestor
Delete folder | parent of deleted folder, or remaining ancestor Delete folder | parent of deleted folder, or remaining ancestor
*/ */
void handleFileDelete() void handleFileDelete() {
{
String path = HTTP.arg(0); String path = HTTP.arg(0);
if (path.isEmpty() || path == "/") if (path.isEmpty() || path == "/") {
{
return replyBadRequest("BAD PATH"); return replyBadRequest("BAD PATH");
} }
// DBG_OUTPUT_PORT.println(String("handleFileDelete: ") + path); // DBG_OUTPUT_PORT.println(String("handleFileDelete: ") + path);
if (!FileFS.exists(path)) if (!FileFS.exists(path)) {
{
return replyNotFound(FPSTR(FILE_NOT_FOUND)); return replyNotFound(FPSTR(FILE_NOT_FOUND));
} }
deleteRecursive(path); deleteRecursive(path);
replyOKWithMsg(lastExistingParent(path)); replyOKWithMsg(lastExistingParent(path));
} }
@@ -414,93 +365,72 @@ void handleFileDelete()
Rename folder | parent of source folder Rename folder | parent of source folder
Move folder | parent of source folder, or remaining ancestor Move folder | parent of source folder, or remaining ancestor
*/ */
void handleFileCreate() void handleFileCreate() {
{
String path = HTTP.arg("path"); String path = HTTP.arg("path");
if (path.isEmpty()) if (path.isEmpty()) {
{
return replyBadRequest(F("PATH ARG MISSING")); return replyBadRequest(F("PATH ARG MISSING"));
} }
#ifdef USE_SPIFFS #ifdef USE_SPIFFS
if (checkForUnsupportedPath(path).length() > 0) if (checkForUnsupportedPath(path).length() > 0) {
{
return replyServerError(F("INVALID FILENAME")); return replyServerError(F("INVALID FILENAME"));
} }
#endif #endif
if (path == "/") if (path == "/") {
{
return replyBadRequest("BAD PATH"); return replyBadRequest("BAD PATH");
} }
if (FileFS.exists(path)) if (FileFS.exists(path)) {
{
return replyBadRequest(F("PATH FILE EXISTS")); return replyBadRequest(F("PATH FILE EXISTS"));
} }
String src = HTTP.arg("src"); String src = HTTP.arg("src");
if (src.isEmpty()) if (src.isEmpty()) {
{
// No source specified: creation // No source specified: creation
// DBG_OUTPUT_PORT.println(String("handleFileCreate: ") + path); // DBG_OUTPUT_PORT.println(String("handleFileCreate: ") + path);
if (path.endsWith("/")) if (path.endsWith("/")) {
{
// Create a folder // Create a folder
path.remove(path.length() - 1); path.remove(path.length() - 1);
if (!FileFS.mkdir(path)) if (!FileFS.mkdir(path)) {
{
return replyServerError(F("MKDIR FAILED")); return replyServerError(F("MKDIR FAILED"));
} }
} } else {
else
{
// Create a file // Create a file
File file = FileFS.open(path, "w"); File file = FileFS.open(path, "w");
if (file) if (file) {
{ #ifdef ESP8266
#ifdef ESP8266
file.write((const char *)0); file.write((const char *)0);
#endif #endif
#ifdef ESP32 #ifdef ESP32
file.write(0); file.write(0);
#endif #endif
file.close(); file.close();
} } else {
else
{
return replyServerError(F("CREATE FAILED")); return replyServerError(F("CREATE FAILED"));
} }
} }
if (path.lastIndexOf('/') > -1) if (path.lastIndexOf('/') > -1) {
{
path = path.substring(0, path.lastIndexOf('/')); path = path.substring(0, path.lastIndexOf('/'));
} }
replyOKWithMsg(path); replyOKWithMsg(path);
} } else {
else
{
// Source specified: rename // Source specified: rename
if (src == "/") if (src == "/") {
{
return replyBadRequest("BAD SRC"); return replyBadRequest("BAD SRC");
} }
if (!FileFS.exists(src)) if (!FileFS.exists(src)) {
{
return replyBadRequest(F("SRC FILE NOT FOUND")); return replyBadRequest(F("SRC FILE NOT FOUND"));
} }
// DBG_OUTPUT_PORT.println(String("handleFileCreate: ") + path + " from " + src); // DBG_OUTPUT_PORT.println(String("handleFileCreate: ") + path + " from " + src);
if (path.endsWith("/")) if (path.endsWith("/")) {
{
path.remove(path.length() - 1); path.remove(path.length() - 1);
} }
if (src.endsWith("/")) if (src.endsWith("/")) {
{
src.remove(src.length() - 1); src.remove(src.length() - 1);
} }
if (!FileFS.rename(src, path)) if (!FileFS.rename(src, path)) {
{
return replyServerError(F("RENAME FAILED")); return replyServerError(F("RENAME FAILED"));
} }
replyOKWithMsg(lastExistingParent(src)); replyOKWithMsg(lastExistingParent(src));
@@ -512,26 +442,22 @@ void handleFileCreate()
Also demonstrates the use of chunked responses. Also demonstrates the use of chunked responses.
*/ */
#ifdef ESP8266 #ifdef ESP8266
void handleFileList() void handleFileList() {
{ if (!HTTP.hasArg("dir")) {
if (!HTTP.hasArg("dir"))
{
return replyBadRequest(F("DIR ARG MISSING")); return replyBadRequest(F("DIR ARG MISSING"));
} }
String path = HTTP.arg("dir"); String path = HTTP.arg("dir");
if (path != "/" && !FileFS.exists(path)) if (path != "/" && !FileFS.exists(path)) {
{
return replyBadRequest("BAD PATH"); return replyBadRequest("BAD PATH");
} }
// DBG_OUTPUT_PORT.println(String("handleFileList: ") + path); // DBG_OUTPUT_PORT.println(String("handleFileList: ") + path);
Dir dir = FileFS.openDir(path); Dir dir = FileFS.openDir(path);
path.clear(); path.clear();
// use HTTP/1.1 Chunked response to avoid building a huge temporary string // use HTTP/1.1 Chunked response to avoid building a huge temporary string
if (!HTTP.chunkedResponseModeStart(200, "text/json")) if (!HTTP.chunkedResponseModeStart(200, "text/json")) {
{
HTTP.send(505, F("text/html"), F("HTTP1.1 required")); HTTP.send(505, F("text/html"), F("HTTP1.1 required"));
return; return;
} }
@@ -539,47 +465,36 @@ void handleFileList()
// use the same string for every line // use the same string for every line
String output; String output;
output.reserve(64); output.reserve(64);
while (dir.next()) while (dir.next()) {
{
#ifdef USE_SPIFFS #ifdef USE_SPIFFS
String error = checkForUnsupportedPath(dir.fileName()); String error = checkForUnsupportedPath(dir.fileName());
if (error.length() > 0) if (error.length() > 0) {
{ // DBG_OUTPUT_PORT.println(String("Ignoring ") + error + dir.fileName());
// DBG_OUTPUT_PORT.println(String("Ignoring ") + error + dir.fileName());
continue; continue;
} }
#endif #endif
if (output.length()) if (output.length()) {
{
// send string from previous iteration // send string from previous iteration
// as an HTTP chunk // as an HTTP chunk
HTTP.sendContent(output); HTTP.sendContent(output);
output = ','; output = ',';
} } else {
else
{
output = '['; output = '[';
} }
output += "{\"type\":\""; output += "{\"type\":\"";
if (dir.isDirectory()) if (dir.isDirectory()) {
{
output += "dir"; output += "dir";
} } else {
else
{
output += F("file\",\"size\":\""); output += F("file\",\"size\":\"");
output += dir.fileSize(); output += dir.fileSize();
} }
output += F("\",\"name\":\""); output += F("\",\"name\":\"");
// Always return names without leading "/" // Always return names without leading "/"
if (dir.fileName()[0] == '/') if (dir.fileName()[0] == '/') {
{
output += &(dir.fileName()[1]); output += &(dir.fileName()[1]);
} } else {
else
{
output += dir.fileName(); output += dir.fileName();
} }
@@ -595,65 +510,57 @@ void handleFileList()
#ifdef ESP32 #ifdef ESP32
void handleFileList() { void handleFileList() {
if (!HTTP.hasArg("dir")) { if (!HTTP.hasArg("dir")) {
HTTP.send(500, "text/plain", "BAD ARGS"); HTTP.send(500, "text/plain", "BAD ARGS");
return; return;
} }
String path = HTTP.arg("dir"); String path = HTTP.arg("dir");
// DBG_OUTPUT_PORT.println("handleFileList: " + path); // DBG_OUTPUT_PORT.println("handleFileList: " + path);
File root = FileFS.open(path);
path = String();
File root = FileFS.open(path); String output = "[";
path = String(); if (root.isDirectory()) {
File file = root.openNextFile();
while (file) {
if (output != "[") {
output += ',';
}
output += "{\"type\":\"";
// output += (file.isDirectory()) ? "dir" : "file";
if (file.isDirectory()) {
output += "dir";
} else {
output += F("file\",\"size\":\"");
output += file.size();
}
String output = "["; output += "\",\"name\":\"";
if(root.isDirectory()){
File file = root.openNextFile();
while(file){
if (output != "[") {
output += ',';
}
output += "{\"type\":\"";
// output += (file.isDirectory()) ? "dir" : "file";
if (file.isDirectory())
{
output += "dir";
}
else
{
output += F("file\",\"size\":\"");
output += file.size();
}
output += "\",\"name\":\"";
output += String(file.name()); output += String(file.name());
output += "\"}"; output += "\"}";
file = root.openNextFile(); file = root.openNextFile();
} }
} }
output += "]"; output += "]";
HTTP.send(200, "text/json", output); HTTP.send(200, "text/json", output);
} }
#endif #endif
/* /*
The "Not Found" handler catches all URI not explicitly declared in code The "Not Found" handler catches all URI not explicitly declared in code
First try to find and return the requested file from the filesystem, First try to find and return the requested file from the filesystem,
and if it fails, return a 404 page with debug information and if it fails, return a 404 page with debug information
*/ */
void handleNotFound() void handleNotFound() {
{
#ifdef ESP8266 #ifdef ESP8266
String uri = ESP8266WebServer::urlDecode(HTTP.uri()); // required to read paths with blanks String uri = ESP8266WebServer::urlDecode(HTTP.uri()); // required to read paths with blanks
#endif #endif
#ifdef ESP32 #ifdef ESP32
String uri = WebServer::urlDecode(HTTP.uri()); // required to read paths with blanks String uri = WebServer::urlDecode(HTTP.uri()); // required to read paths with blanks
#endif #endif
if (handleFileRead(uri)) if (handleFileRead(uri)) {
{
return; return;
} }
@@ -667,8 +574,7 @@ void handleNotFound()
message += F("\nArguments: "); message += F("\nArguments: ");
message += HTTP.args(); message += HTTP.args();
message += '\n'; message += '\n';
for (uint8_t i = 0; i < HTTP.args(); i++) for (uint8_t i = 0; i < HTTP.args(); i++) {
{
message += F(" NAME:"); message += F(" NAME:");
message += HTTP.argName(i); message += HTTP.argName(i);
message += F("\n VALUE:"); message += F("\n VALUE:");
@@ -678,7 +584,7 @@ void handleNotFound()
message += "path="; message += "path=";
message += HTTP.arg("path"); message += HTTP.arg("path");
message += '\n'; message += '\n';
// DBG_OUTPUT_PORT.print(message); // DBG_OUTPUT_PORT.print(message);
return replyNotFound(message); return replyNotFound(message);
} }
@@ -689,10 +595,8 @@ void handleNotFound()
embedded in the program code. embedded in the program code.
Otherwise, fails with a 404 page with debug information Otherwise, fails with a 404 page with debug information
*/ */
void handleGetEdit() void handleGetEdit() {
{ if (handleFileRead(F("/edit.htm"))) {
if (handleFileRead(F("/edit.htm")))
{
return; return;
} }

View File

@@ -1,20 +1,15 @@
#include "Global.h" #include "Global.h"
#include "classes/IoTItem.h" #include "classes/IoTItem.h"
#include <map>
#include <GyverOLED.h> #include <GyverOLED.h>
//GyverOLED<SSD1306_128x32, OLED_BUFFER> oled;
//GyverOLED<SSD1306_128x32, OLED_NO_BUFFER> oled;
//GyverOLED<SSD1306_128x64, OLED_BUFFER> oled;
//GyverOLED<SSD1306_128x64, OLED_NO_BUFFER> oled;
//GyverOLED<SSD1306_128x64, OLED_BUFFER, OLED_SPI, 8, 7, 6> oled;
GyverOLED<SSH1106_128x64> oled;
GyverOLED<SSD1306_128x64, OLED_BUFFER> oled;
// GyverOLED<SSD1306_128x32, OLED_BUFFER> oled;
// GyverOLED<SSD1306_128x32, OLED_NO_BUFFER> oled;
// GyverOLED<SSD1306_128x64, OLED_NO_BUFFER> oled;
// GyverOLED<SSD1306_128x64, OLED_BUFFER, OLED_SPI, 8, 7, 6> oled;
// GyverOLED<SSH1106_128x64> oled;
class Oled128 : public IoTItem { class Oled128 : public IoTItem {
private: private:
@@ -28,28 +23,22 @@ class Oled128 : public IoTItem {
String _id2show; String _id2show;
String _descr; String _descr;
String _descr1; String _descr1;
int _prevStrSize; int _prevStrSize;
bool _isShow = true; // экран показывает bool _isShow = true; // экран показывает
public: public:
Oled128(String parameters) : IoTItem(parameters) { Oled128(String parameters) : IoTItem(parameters) {
String addr, size, xy, k;
String addr, size, xy, k ;
_prevStrSize = 0; _prevStrSize = 0;
jsonRead(parameters, "addr", addr); jsonRead(parameters, "addr", addr);
if (addr == "") { if (addr == "") {
//scanI2C(); // scanI2C();
return; return;
} }
jsonRead(parameters, "coord", xy); jsonRead(parameters, "coord", xy);
_x = selectFromMarkerToMarker(xy, ",", 0).toInt(); _x = selectFromMarkerToMarker(xy, ",", 0).toInt();
_y = selectFromMarkerToMarker(xy, ",", 1).toInt(); _y = selectFromMarkerToMarker(xy, ",", 1).toInt();
@@ -57,92 +46,80 @@ class Oled128 : public IoTItem {
jsonRead(parameters, "descr", _descr); jsonRead(parameters, "descr", _descr);
jsonRead(parameters, "id2show", _id2show); jsonRead(parameters, "id2show", _id2show);
jsonRead(parameters, "descr1", _descr1); jsonRead(parameters, "descr1", _descr1);
//jsonRead(parameters, "scale", _k); // jsonRead(parameters, "scale", _k);
jsonRead(parameters, "shrift", _shrift); jsonRead(parameters, "shrift", _shrift);
// Wire.begin(2,0); // Инициализация шины I2C для модуля E01 // Wire.begin(2,0); // Инициализация шины I2C для модуля E01
oled.init(); // инициализация экрана oled.init(); // инициализация экрана
} }
void doByInterval() { void doByInterval() {
printBlankStr(_prevStrSize);
String tmpStr = "";
printBlankStr(_prevStrSize); // if (_descr != "none") tmpStr = _descr + " " + getItemValue(_id2show);
if (_descr != "none")
tmpStr = _descr + " " + getItemValue(_id2show) + " " + _descr1;
String tmpStr = ""; else
tmpStr = getItemValue(_id2show);
//if (_descr != "none") tmpStr = _descr + " " + getItemValue(_id2show);
if (_descr != "none") tmpStr = _descr + " " + getItemValue(_id2show) + " " + _descr1;
else tmpStr = getItemValue(_id2show);
//oled.setScale(2); // oled.setScale(2);
oled.setScale(_shrift); oled.setScale(_shrift);
oled.setCursorXY(_x, _y); oled.setCursorXY(_x, _y);
oled.print(tmpStr); oled.print(tmpStr);
oled.update(); oled.update();
_prevStrSize = tmpStr.length(); _prevStrSize = tmpStr.length();
} }
IoTValue execute(String command, std::vector<IoTValue> &param) { // будет возможным использовать, когда сценарии запустятся IoTValue execute(String command, std::vector<IoTValue> &param) { // будет возможным использовать, когда сценарии запустятся
if (command == "scroll") { if (command == "scroll") {
String tmpStr = ""; String tmpStr = "";
oled.clear(); oled.clear();
uint32_t tmr = millis(); uint32_t tmr = millis();
oled.autoPrintln(false); oled.autoPrintln(false);
int val = 128; int val = 128;
for (;;) { for (;;) {
//oled.clear(); // ЗАКОММЕНТИРУЙ, ЕСЛИ ВКЛЮЧЕН БУФЕР // oled.clear(); // ЗАКОММЕНТИРУЙ, ЕСЛИ ВКЛЮЧЕН БУФЕР
//oled.setScale(2); // oled.setScale(2);
oled.setScale(_shrift); oled.setScale(_shrift);
oled.setCursor(val, _y); oled.setCursor(val, _y);
oled.print(tmpStr); oled.print(tmpStr);
oled.update(); oled.update();
val--; val--;
if (millis() - tmr > 5000);// return; if (millis() - tmr > 5000)
; // return;
_isShow = true;
}
_isShow = true;
}
} }
else if (command == "stopscroll") { else if (command == "stopscroll") {
_isShow = true; _isShow = true;
// display->backlight(); // display->backlight();
// else if (command == "noDisplay") { // else if (command == "noDisplay") {
// display->noDisplay(); // display->noDisplay();
// _isShow = false; // _isShow = false;
} } else if (command == "display") {
else if (command == "display") { // display.display();
// display.display();
_isShow = true; _isShow = true;
} else if (command == "toggle") { } else if (command == "toggle") {
if (_isShow) { if (_isShow) {
// display->noDisplay(); // display->noDisplay();
_isShow = false; _isShow = false;
} else { } else {
// display.display(); // display.display();
_isShow = true; _isShow = true;
} }
} else if (command == "x") { } else if (command == "x") {
@@ -160,7 +137,7 @@ class Oled128 : public IoTItem {
} else if (command == "descr1") { } else if (command == "descr1") {
if (param.size()) { if (param.size()) {
_descr1 = param[0].valS; _descr1 = param[0].valS;
} }
} else if (command == "id2show") { } else if (command == "id2show") {
if (param.size()) { if (param.size()) {
_id2show = param[0].valS; _id2show = param[0].valS;
@@ -169,24 +146,22 @@ class Oled128 : public IoTItem {
doByInterval(); doByInterval();
return {}; return {};
} }
//печать пустой строки нужной длинны для затирания предыдущего значения на экране // печать пустой строки нужной длинны для затирания предыдущего значения на экране
void printBlankStr(int strSize) { void printBlankStr(int strSize) {
String tmpStr = ""; String tmpStr = "";
for (int i = 0; i < strSize; i++) tmpStr += " "; for (int i = 0; i < strSize; i++) tmpStr += " ";
// oled.setScale(2); // oled.setScale(2);
oled.setScale(_shrift); oled.setScale(_shrift);
oled.setCursorXY(_x, _y); oled.setCursorXY(_x, _y);
oled.print(tmpStr); oled.print(tmpStr);
} }
~Oled128(){}; ~Oled128(){};
}; };