запуск little fs на esp32

This commit is contained in:
Dmitry Borisenko
2022-09-15 14:02:24 +02:00
parent d78e03176f
commit aae21f4a78
15 changed files with 87 additions and 74 deletions

10
.vscode/extensions.json vendored Normal file
View File

@@ -0,0 +1,10 @@
{
// See http://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": [
"platformio.platformio-ide"
],
"unwantedRecommendations": [
"ms-vscode.cpptools-extension-pack"
]
}

15
.vscode/settings.json vendored
View File

@@ -1,15 +0,0 @@
{
"files.associations": {
"system_error": "cpp",
"xlocale": "cpp",
"deque": "cpp",
"initializer_list": "cpp",
"list": "cpp",
"vector": "cpp",
"xhash": "cpp",
"xiosbase": "cpp",
"xstring": "cpp",
"xtree": "cpp",
"xutility": "cpp"
}
}

View File

@@ -455,16 +455,18 @@
"num": 34 "num": 34
}, },
{ {
"name": "35. PWM ESP8266", "name": "35. PWM ESP32",
"type": "Writing", "type": "Writing",
"subtype": "Pwm8266", "subtype": "Pwm32",
"id": "pwm", "id": "pwm",
"widget": "range", "widget": "range",
"page": "Кнопки", "page": "Кнопки",
"descr": "PWM", "descr": "PWM",
"int": 0, "int": 0,
"pin": 15, "pin": 2,
"freq": 5000, "freq": 5000,
"ledChannel": 2,
"PWM_resolution": 10,
"val": 0, "val": 0,
"apin": -1, "apin": -1,
"num": 35 "num": 35

View File

@@ -1,7 +1,7 @@
#pragma once #pragma once
//Версия прошивки //Версия прошивки
#define FIRMWARE_VERSION 420 #define FIRMWARE_VERSION 421
#ifdef esp8266_4mb #ifdef esp8266_4mb
#define FIRMWARE_NAME "esp8266_4mb" #define FIRMWARE_NAME "esp8266_4mb"

View File

@@ -1,11 +1,16 @@
#pragma once #pragma once
#include "Global.h" #include "Global.h"
#ifdef ESP32 #ifdef ESP32
#if USE_LITTLEFS
#include <LITTLEFS.h>
#define FileFS LittleFS
#define FS_NAME "LittleFS_32"
#else
#include <SPIFFS.h> #include <SPIFFS.h>
extern FS* filesystem; extern FS* filesystem;
#define FileFS SPIFFS #define FileFS SPIFFS
#define FS_NAME "SPIFFS" #define FS_NAME "SPIFFS_32"
#endif
#endif #endif
#ifdef ESP8266 #ifdef ESP8266
@@ -15,11 +20,11 @@ extern FS LittleFS;
using littlefs_impl::LittleFSConfig; using littlefs_impl::LittleFSConfig;
extern FS* filesystem; extern FS* filesystem;
#define FileFS LittleFS #define FileFS LittleFS
#define FS_NAME "LittleFS" #define FS_NAME "LittleFS_8266"
#else #else
extern FS* filesystem; extern FS* filesystem;
#define FileFS SPIFFS #define FileFS SPIFFS
#define FS_NAME "SPIFFS" #define FS_NAME "SPIFFS_8266"
#endif #endif
#endif #endif

View File

@@ -14,8 +14,7 @@ extern size_t countLines(const String filename);
void removeFile(const String& filename); void removeFile(const String& filename);
void removeDirectory(const String& dir); void removeDirectory(const String& dir);
void cleanDirectory(String path); void cleanDirectory(String path);
void cleanLogs1(); void cleanLogs();
void cleanLogs2();
void saveDataDB(String id, String data); void saveDataDB(String id, String data);
String readDataDB(String id); String readDataDB(String id);
extern void onFlashWrite(); extern void onFlashWrite();
@@ -23,7 +22,13 @@ extern void onFlashWrite();
String getFilesList8266(String& directory); String getFilesList8266(String& directory);
String getFilesList32(String& directory); String getFilesList32(String& directory);
String getFilesList(String& directory); String getFilesList(String& directory);
extern void getFSInfo();
struct IoTFSInfo {
size_t totalBytes;
float freePer;
};
extern IoTFSInfo getFSInfo();
#ifdef ESP8266 #ifdef ESP8266
extern bool getInfo(FSInfo& info); extern bool getInfo(FSInfo& info);
#endif #endif

View File

@@ -21,7 +21,7 @@
}, },
"projectProp": { "projectProp": {
"platformio": { "platformio": {
"default_envs": "esp8266_4mb", "default_envs": "esp32_4mb",
"data_dir": "data_svelte" "data_dir": "data_svelte"
} }
}, },

View File

@@ -27,7 +27,7 @@ lib_deps =
build_flags = -Desp32_4mb="esp32_4mb" build_flags = -Desp32_4mb="esp32_4mb"
framework = arduino framework = arduino
board = esp32dev board = esp32dev
platform = espressif32 platform = espressif32 @5.1.1
monitor_filters = esp32_exception_decoder monitor_filters = esp32_exception_decoder
upload_speed = 921600 upload_speed = 921600
monitor_speed = 115200 monitor_speed = 115200
@@ -41,10 +41,11 @@ build_src_filter =
${env:esp32_4mb_fromitems.build_src_filter} ${env:esp32_4mb_fromitems.build_src_filter}
[platformio] [platformio]
default_envs = esp8266_4mb default_envs = esp32_4mb
data_dir = data_svelte data_dir = data_svelte
[common_env_data] [common_env_data]
upload_port = COM4
lib_deps_external = lib_deps_external =
bblanchon/ArduinoJson @6.18.0 bblanchon/ArduinoJson @6.18.0
Links2004/WebSockets Links2004/WebSockets

View File

@@ -1,4 +1,5 @@
#include "EspFileSystem.h" #include "EspFileSystem.h"
#include "Global.h"
bool fileSystemInit() { bool fileSystemInit() {
if (!FileFS.begin()) { if (!FileFS.begin()) {

View File

@@ -196,12 +196,8 @@ void webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length)
} }
//команда очистки всех логов esp //команда очистки всех логов esp
if (headerStr == "/clean1|") { if (headerStr == "/clean|") {
cleanLogs1(); cleanLogs();
}
if (headerStr == "/clean2|") {
cleanLogs2();
} }
//команда обновления прошивки esp //команда обновления прошивки esp

View File

@@ -1,4 +1,3 @@
#pragma once
#include "Global.h" #include "Global.h"
#include "classes/IoTItem.h" #include "classes/IoTItem.h"
#include "classes/IoTScenario.h" #include "classes/IoTScenario.h"

View File

@@ -22,7 +22,7 @@ void* getAPI_ButtonOut(String subtype, String params);
void* getAPI_IoTServo(String subtype, String params); void* getAPI_IoTServo(String subtype, String params);
void* getAPI_Mcp23017(String subtype, String params); void* getAPI_Mcp23017(String subtype, String params);
void* getAPI_Mp3(String subtype, String params); void* getAPI_Mp3(String subtype, String params);
void* getAPI_Pwm8266(String subtype, String params); void* getAPI_Pwm32(String subtype, String params);
void* getAPI_TelegramLT(String subtype, String params); void* getAPI_TelegramLT(String subtype, String params);
void* getAPI_Lcd2004(String subtype, String params); void* getAPI_Lcd2004(String subtype, String params);
@@ -50,7 +50,7 @@ if ((tmpAPI = getAPI_ButtonOut(subtype, params)) != nullptr) return tmpAPI;
if ((tmpAPI = getAPI_IoTServo(subtype, params)) != nullptr) return tmpAPI; if ((tmpAPI = getAPI_IoTServo(subtype, params)) != nullptr) return tmpAPI;
if ((tmpAPI = getAPI_Mcp23017(subtype, params)) != nullptr) return tmpAPI; if ((tmpAPI = getAPI_Mcp23017(subtype, params)) != nullptr) return tmpAPI;
if ((tmpAPI = getAPI_Mp3(subtype, params)) != nullptr) return tmpAPI; if ((tmpAPI = getAPI_Mp3(subtype, params)) != nullptr) return tmpAPI;
if ((tmpAPI = getAPI_Pwm8266(subtype, params)) != nullptr) return tmpAPI; if ((tmpAPI = getAPI_Pwm32(subtype, params)) != nullptr) return tmpAPI;
if ((tmpAPI = getAPI_TelegramLT(subtype, params)) != nullptr) return tmpAPI; if ((tmpAPI = getAPI_TelegramLT(subtype, params)) != nullptr) return tmpAPI;
if ((tmpAPI = getAPI_Lcd2004(subtype, params)) != nullptr) return tmpAPI; if ((tmpAPI = getAPI_Lcd2004(subtype, params)) != nullptr) return tmpAPI;
return nullptr; return nullptr;

View File

@@ -38,7 +38,7 @@ class Loging : public IoTItem {
jsonRead(parameters, F("keepdays"), keepdays); jsonRead(parameters, F("keepdays"), keepdays);
//создадим экземпляр класса даты //создадим экземпляр класса даты
dateIoTItem = (IoTItem *)getAPI_Date("{\"id\": \"" + id + "-date\",\"int\":\"20\"}"); dateIoTItem = (IoTItem *)getAPI_Date("{\"id\": \"" + id + "-date\",\"int\":\"20\",\"subtype\":\"date\"}");
IoTItems.push_back(dateIoTItem); IoTItems.push_back(dateIoTItem);
SerialPrint("E", F("Loging"), "created date instance " + id); SerialPrint("E", F("Loging"), "created date instance " + id);
} }
@@ -75,8 +75,6 @@ class Loging : public IoTItem {
SerialPrint("E", F("Loging"), "'" + id + "' file path not found"); SerialPrint("E", F("Loging"), "'" + id + "' file path not found");
createNewFileWithData(logData); createNewFileWithData(logData);
return; return;
} else {
// SerialPrint("i", F("Loging"), "'" + id + "' file path found " + filePath);
} }
//считаем количество строк //считаем количество строк
@@ -91,6 +89,8 @@ class Loging : public IoTItem {
} else { } else {
createNewFileWithData(logData); createNewFileWithData(logData);
} }
//запускаем процедуру удаления старых файлов если память переполняется
deleteLastFile();
} }
void createNewFileWithData(String &logData) { void createNewFileWithData(String &logData) {
@@ -135,11 +135,6 @@ class Loging : public IoTItem {
unsigned long fileUnixTimeGMT = selectToMarkerLast(deleteToMarkerLast(buf, "."), "/").toInt() + START_DATETIME; unsigned long fileUnixTimeGMT = selectToMarkerLast(deleteToMarkerLast(buf, "."), "/").toInt() + START_DATETIME;
unsigned long fileUnixTimeLocal = gmtTimeToLocal(fileUnixTimeGMT); unsigned long fileUnixTimeLocal = gmtTimeToLocal(fileUnixTimeGMT);
//удаление старых файлов
// if ((fileUnixTimeLocal + (points * (interval / 1000))) < (unixTime - (keepdays * 86400))) {
// SerialPrint("i", F("Loging"), "file '" + buf + "' too old, deleted");
// removeFile(buf);
//} else {
unsigned long reqUnixTime = strDateToUnix(getItemValue(id + "-date")); unsigned long reqUnixTime = strDateToUnix(getItemValue(id + "-date"));
if (fileUnixTimeLocal > reqUnixTime && fileUnixTimeLocal < reqUnixTime + 86400) { if (fileUnixTimeLocal > reqUnixTime && fileUnixTimeLocal < reqUnixTime + 86400) {
noData = false; noData = false;
@@ -148,7 +143,6 @@ class Loging : public IoTItem {
} else { } else {
SerialPrint("i", F("Loging"), String(f) + ") " + buf + ", nil, " + getDateTimeDotFormatedFromUnix(fileUnixTimeLocal) + ", skipped"); SerialPrint("i", F("Loging"), String(f) + ") " + buf + ", nil, " + getDateTimeDotFormatedFromUnix(fileUnixTimeLocal) + ", skipped");
} }
//}
filesList = deleteBeforeDelimiter(filesList, ";"); filesList = deleteBeforeDelimiter(filesList, ";");
} }
@@ -179,6 +173,28 @@ class Loging : public IoTItem {
} }
} }
void deleteLastFile() {
IoTFSInfo tmp = getFSInfo();
SerialPrint("i", "Loging", String(tmp.freePer) + " % free flash remaining");
if (tmp.freePer <= 10.00) {
String dir = "lg/" + id;
filesList = getFilesList(dir);
int i = 0;
while (filesList.length()) {
String buf = selectToMarker(filesList, ";");
i++;
if (i == 1) {
removeFile(buf);
SerialPrint("!", "Loging", String(i) + ") " + buf + " => oldest files been deleted");
return;
}
filesList = deleteBeforeDelimiter(filesList, ";");
}
}
}
void createJson(String file, int &i) { void createJson(String file, int &i) {
File configFile = FileFS.open(file, "r"); File configFile = FileFS.open(file, "r");
if (!configFile) { if (!configFile) {

View File

@@ -171,7 +171,8 @@ size_t countLines(const String filename) {
size_t psn; size_t psn;
do { do {
cnt++; cnt++;
file.readStringUntil('\r\n'); // или /n тут один знак
file.readStringUntil('\r');
psn = file.position(); psn = file.position();
} while (psn < size); } while (psn < size);
file.close(); file.close();
@@ -226,8 +227,8 @@ String readDataDB(String id) {
return readFile(path, 2000); return readFile(path, 2000);
} }
void cleanLogs1() { void cleanLogs() {
SerialPrint("i", "Files", "cleanLogs1"); SerialPrint("i", "Files", "cleanLogs");
cleanDirectory("db"); cleanDirectory("db");
//очистка данных всех экземпляров графиков //очистка данных всех экземпляров графиков
for (std::list<IoTItem*>::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) { for (std::list<IoTItem*>::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) {
@@ -237,20 +238,6 @@ void cleanLogs1() {
} }
} }
void cleanLogs2() {
SerialPrint("i", "Files", "cleanLogs2");
String dir1 = "db";
SerialPrint("i", "", getFilesList(dir1));
removeDirectory(dir1);
SerialPrint("i", "", getFilesList(dir1));
String dir2 = "lg";
SerialPrint("i", "", getFilesList(dir2));
removeDirectory(dir2);
SerialPrint("i", "", getFilesList(dir2));
}
//счетчик количества записей на флешь за сеанс //счетчик количества записей на флешь за сеанс
void onFlashWrite() { void onFlashWrite() {
flashWriteNumber++; flashWriteNumber++;
@@ -273,7 +260,7 @@ String getFilesList8266(String& directory) {
#if defined(ESP32) #if defined(ESP32)
String getFilesList32(String& directory) { String getFilesList32(String& directory) {
String filesList = ""; String filesList = "";
String directory = "/" + directory; directory = "/" + directory;
File root = FileFS.open(directory); File root = FileFS.open(directory);
directory = String(); directory = String();
if (root.isDirectory()) { if (root.isDirectory()) {
@@ -301,31 +288,37 @@ String getFilesList(String& directory) {
bool getInfo(FSInfo& info) { bool getInfo(FSInfo& info) {
return FileFS.info(info); return FileFS.info(info);
} }
// Информация о ФС // Информация о ФС
void getFSInfo() { IoTFSInfo getFSInfo() {
IoTFSInfo myFSInfo;
FSInfo buf; FSInfo buf;
if (getInfo(buf)) { if (getInfo(buf)) {
size_t totalBytes = buf.totalBytes; // всего size_t totalBytes = myFSInfo.totalBytes = buf.totalBytes; // всего
size_t usedBytes = buf.usedBytes; // использовано size_t usedBytes = buf.usedBytes; // использовано
// size_t maxOpenFiles = buf.maxOpenFiles; // лимит на открые файлы // size_t maxOpenFiles = buf.maxOpenFiles; // лимит на открые файлы
// size_t blockSize = buf.blockSize; // size_t blockSize = buf.blockSize;
// size_t pageSize = buf.pageSize; // size_t pageSize = buf.pageSize;
// size_t maxPathLength = buf.maxPathLength; // лимит на пути и имена файлов // size_t maxPathLength = buf.maxPathLength; // лимит на пути и имена файлов
size_t freeBytes = totalBytes - usedBytes; size_t freeBytes = totalBytes - usedBytes;
float freePer = ((float)freeBytes / totalBytes) * 100; float freePer = myFSInfo.freePer = ((float)freeBytes / totalBytes) * 100;
jsonWriteStr(errorsHeapJson, F("freeBytes"), String(freePer) + "% (" + prettyBytes(freeBytes) + ")"); jsonWriteStr(errorsHeapJson, F("freeBytes"), String(freePer) + "% (" + prettyBytes(freeBytes) + ")");
} else { } else {
SerialPrint("E", F("FS"), F("FS info error")); SerialPrint("E", F("FS"), F("FS info error"));
} }
return myFSInfo;
} }
#endif #endif
#if defined(ESP32) #if defined(ESP32)
void getFSInfo() { IoTFSInfo getFSInfo() {
size_t totalBytes = FileFS.totalBytes(); // всего IoTFSInfo myFSInfo;
size_t usedBytes = FileFS.usedBytes(); // использовано size_t totalBytes = myFSInfo.totalBytes = FileFS.totalBytes(); // всего
size_t usedBytes = FileFS.usedBytes(); // использовано
size_t freeBytes = totalBytes - usedBytes; size_t freeBytes = totalBytes - usedBytes;
float freePer = ((float)freeBytes / totalBytes) * 100; float freePer = myFSInfo.freePer = ((float)freeBytes / totalBytes) * 100;
jsonWriteStr(errorsHeapJson, F("freeBytes"), String(freePer) + "% (" + prettyBytes(freeBytes) + ")"); jsonWriteStr(errorsHeapJson, F("freeBytes"), String(freePer) + "% (" + prettyBytes(freeBytes) + ")");
return myFSInfo;
} }
#endif #endif

View File

@@ -23,7 +23,7 @@ bool jsonRead(String& json, String key, unsigned long& value, bool e) {
ret = false; ret = false;
} else if (!doc.containsKey(key)) { } else if (!doc.containsKey(key)) {
if (e) { if (e) {
SerialPrint("EE", F("jsonRead"), key + " missing"); SerialPrint("EE", F("jsonRead"), "json key '" + key + "' missing");
jsonErrorDetected(); jsonErrorDetected();
} }
ret = false; ret = false;