Merge branch 'IoTManagerProject:ver4dev' into ver4dev

This commit is contained in:
2022-08-30 13:43:06 +03:00
committed by GitHub
9 changed files with 174 additions and 118 deletions

6
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,6 @@
{
"files.associations": {
"*.tcc": "cpp",
"fstream": "cpp"
}
}

View File

@@ -17,7 +17,8 @@
"int": 60, "int": 60,
"logid": "tmp", "logid": "tmp",
"num": 1, "num": 1,
"points": 255 "points": 300,
"keepdays": 2
}, },
{ {
"name": "2. Таймер", "name": "2. Таймер",
@@ -442,16 +443,18 @@
"num": 33 "num": 33
}, },
{ {
"name": "34. PWM ESP8266", "name": "34. 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": 34 "num": 34

View File

@@ -1,7 +1,7 @@
#pragma once #pragma once
//Версия прошивки //Версия прошивки
#define FIRMWARE_VERSION 412 #define FIRMWARE_VERSION 413
//Поблочная загрузка сценариев =1 грузим блоками, =0 грузим и держим в памяти весь сценарий //Поблочная загрузка сценариев =1 грузим блоками, =0 грузим и держим в памяти весь сценарий
#define SCENARIO_BLOCK_LOAD 1 #define SCENARIO_BLOCK_LOAD 1
@@ -35,7 +35,7 @@
#endif #endif
#ifdef esp32_4mb #ifdef esp32_4mb
#define USE_LITTLEFS true #define USE_LITTLEFS false
#endif #endif
#define START_DATETIME 1640995200 // 01.01.2022 00:00:00 константа для сокращения unix time #define START_DATETIME 1640995200 // 01.01.2022 00:00:00 константа для сокращения unix time

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

@@ -39,7 +39,7 @@ 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]

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_SysExt(String subtype, String params); void* getAPI_SysExt(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_SysExt(subtype, params)) != nullptr) return tmpAPI; if ((tmpAPI = getAPI_SysExt(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

@@ -7,6 +7,7 @@ class Loging : public IoTItem {
String logid; String logid;
String id; String id;
int points; int points;
int keepdays;
int interval; int interval;
bool firstTime = true; bool firstTime = true;
@@ -16,7 +17,12 @@ class Loging : public IoTItem {
jsonRead(parameters, F("logid"), logid); jsonRead(parameters, F("logid"), logid);
jsonRead(parameters, F("id"), id); jsonRead(parameters, F("id"), id);
jsonRead(parameters, F("points"), points); jsonRead(parameters, F("points"), points);
if (points >= 300) {
points = 300;
SerialPrint("E", F("Loging"), "'" + id + "' user set more points than allowed, value reset to 300");
}
jsonRead(parameters, F("int"), interval); jsonRead(parameters, F("int"), interval);
jsonRead(parameters, F("keepdays"), keepdays);
} }
String getValue() { String getValue() {
@@ -50,10 +56,10 @@ class Loging : public IoTItem {
//прочитаем путь к файлу последнего сохранения //прочитаем путь к файлу последнего сохранения
String filePath = readDataDB(id); String filePath = readDataDB(id);
Serial.println("filePath " + filePath); // Serial.println("filePath " + filePath);
//если данные о файле отсутствуют, создадим новый //если данные о файле отсутствуют, создадим новый
if (filePath == "failed") { if (filePath == "failed" || filePath == "") {
SerialPrint("E", F("Loging"), "'" + id + "' file path not found"); SerialPrint("E", F("Loging"), "'" + id + "' file path not found");
createNewFileWithData(logData); createNewFileWithData(logData);
return; return;
@@ -74,15 +80,15 @@ class Loging : public IoTItem {
} }
void createNewFileWithData(String &logData) { void createNewFileWithData(String &logData) {
String filePath = "/lg/" + id + "-" + String(unixTimeShort) + ".txt"; //создадим путь String path = "/lg/" + id + "-" + String(unixTimeShort) + ".txt"; //создадим путь
addFileLn(filePath, logData); //запишем файл и данные в него addFileLn(path, logData); //запишем файл и данные в него
saveDataDB(id, filePath); //запишем путь к файлу в базу данных saveDataDB(id, path); //запишем путь к файлу в базу данных
SerialPrint("i", F("Loging"), "'" + id + "' file created http://" + WiFi.localIP().toString() + filePath); SerialPrint("i", F("Loging"), "'" + id + "' file created http://" + WiFi.localIP().toString() + path);
} }
void addNewDataToExistingFile(String &filePath, String &logData) { void addNewDataToExistingFile(String &path, String &logData) {
addFileLn(filePath, logData); addFileLn(path, logData);
SerialPrint("i", F("Loging"), "'" + id + "' loging in file http://" + WiFi.localIP().toString() + filePath); SerialPrint("i", F("Loging"), "'" + id + "' loging in file http://" + WiFi.localIP().toString() + path);
} }
void sendChart() { void sendChart() {
@@ -90,24 +96,40 @@ class Loging : public IoTItem {
String reqUnixTimeStr = "27.08.2022"; //нужно получить эту дату из окна ввода под графиком. String reqUnixTimeStr = "27.08.2022"; //нужно получить эту дату из окна ввода под графиком.
unsigned long reqUnixTime = strDateToUnix(reqUnixTimeStr); unsigned long reqUnixTime = strDateToUnix(reqUnixTimeStr);
String directory = "lg";
// SerialPrint("i", F("Loging"), "'" + id + "' in directory '" + directory + "' files:");
auto dir = FileFS.openDir(directory);
String oneSingleJson; String oneSingleJson;
int i = 0; int i = 0;
#if defined(ESP8266)
String directory = "lg";
auto dir = FileFS.openDir(directory);
while (dir.next()) { while (dir.next()) {
String fname = dir.fileName(); String fname = dir.fileName();
#endif
#if defined(ESP32)
String directory = "/lg";
File root = FileFS.open(directory);
directory = String();
if (root.isDirectory()) {
File file = root.openNextFile();
while (file) {
String fname = file.name();
fname = selectToMarkerLast(fname, "/");
file = root.openNextFile();
#endif
String idInFileName = selectToMarker(fname, "-"); String idInFileName = selectToMarker(fname, "-");
unsigned long fileUnixTime = deleteBeforeDelimiter(deleteToMarkerLast(fname, "."), "-").toInt() + START_DATETIME; unsigned long fileUnixTime = deleteBeforeDelimiter(deleteToMarkerLast(fname, "."), "-").toInt() + START_DATETIME;
if (isItemExist(id)) { if (isItemExist(id)) {
//если id в имени файла совпадает с id данного экземпляра, пусть каждый экземпляр класса шлет только свое //если id в имени файла совпадает с id данного экземпляра, пусть каждый экземпляр класса шлет только свое
if (idInFileName == id) { if (idInFileName == id) {
//выбираем только те файлы которые входят в выбранные пользователем сутки //выбираем только те файлы которые входят в выбранные пользователем сутки
if (fileUnixTime > reqUnixTime && fileUnixTime < reqUnixTime + 86400) { // if (fileUnixTime > reqUnixTime && fileUnixTime < reqUnixTime + 86400) {
SerialPrint("i", F("Loging"), "'" + id + "' matching file found '" + fname + "'"); SerialPrint("i", F("Loging"), "'" + id + "' matching file found '" + fname + "'");
//выгрузка по частям, по одному файлу //выгрузка по частям, по одному файлу
publishJsonPartly("/lg/" + fname, calculateMaxCount(), i); publishJsonPartly("/lg/" + fname, calculateMaxCount(), i);
//}
//удаление старых файлов
if ((fileUnixTime + (points * interval)) < (unixTime - (keepdays * 86400))) {
SerialPrint("i", F("Loging"), "'" + id + "' file '" + fname + "' too old, deleted");
removeFile(directory + "/" + fname);
} }
} }
} else { } else {
@@ -115,12 +137,17 @@ class Loging : public IoTItem {
removeFile(directory + "/" + fname); removeFile(directory + "/" + fname);
} }
} }
#if defined(ESP32)
}
#endif
SerialPrint("i", F("Loging"), "'" + id + "'--------------'" + String(i) + "'--------------"); SerialPrint("i", F("Loging"), "'" + id + "'--------------'" + String(i) + "'--------------");
} }
void publishJsonPartly(String file, int maxCount, int &i) { void publishJsonPartly(String file, int maxCount, int &i) {
File configFile = FileFS.open(file, "r"); File configFile = FileFS.open(file, "r");
if (!configFile) { if (!configFile) {
SerialPrint("E", F("Loging"), "'" + id + "' open file error");
return; return;
} }
configFile.seek(0, SeekSet); configFile.seek(0, SeekSet);
@@ -147,52 +174,54 @@ class Loging : public IoTItem {
publishJson(dividedJson, maxCount); publishJson(dividedJson, maxCount);
} }
void publishJson(String &oneSingleJson, int &maxCount) { void publishJson(String & oneSingleJson, int &maxCount) {
oneSingleJson = "{\"maxCount\":" + String(maxCount) + ",\"status\":[" + oneSingleJson + "]}"; oneSingleJson = "{\"maxCount\":" + String(maxCount) + ",\"status\":[" + oneSingleJson + "]}";
oneSingleJson.replace("},]}", "}]}"); oneSingleJson.replace("},]}", "}]}");
publishChart(id, oneSingleJson); if (!publishChart(id, oneSingleJson)) {
SerialPrint("E", F("Loging"), "'" + id + "' mqtt publish error");
}
} }
//примерный подсчет максимального количества точек //примерный подсчет максимального количества точек
int calculateMaxCount() { int calculateMaxCount() {
return 86400 / interval; return 86400 / interval;
} }
}; };
void *getAPI_Loging(String subtype, String param) { void *getAPI_Loging(String subtype, String param) {
if (subtype == F("Loging")) { if (subtype == F("Loging")) {
return new Loging(param); return new Loging(param);
} else { } else {
return nullptr; return nullptr;
} }
} }
//то что не пригодилось но пригодится потом может быть //то что не пригодилось но пригодится потом может быть
// void createOneSingleJson(String &oneSingleJson, String file, int &maxCount, int &i) { // void createOneSingleJson(String &oneSingleJson, String file, int &maxCount, int &i) {
// File configFile = FileFS.open(file, "r"); // File configFile = FileFS.open(file, "r");
// if (!configFile) { // if (!configFile) {
// return; // return;
// } // }
// configFile.seek(0, SeekSet); // configFile.seek(0, SeekSet);
// String buf = "{}"; // String buf = "{}";
// String unix_time; // String unix_time;
// String value; // String value;
// unsigned int psn; // unsigned int psn;
// unsigned int sz = configFile.size(); // unsigned int sz = configFile.size();
// do { // do {
// maxCount++; // maxCount++;
// i++; // i++;
// psn = configFile.position(); // psn = configFile.position();
// String line = configFile.readStringUntil('\n'); // String line = configFile.readStringUntil('\n');
// unix_time = selectToMarker(line, " "); // unix_time = selectToMarker(line, " ");
// jsonWriteInt(buf, "x", unix_time.toInt() + START_DATETIME); // jsonWriteInt(buf, "x", unix_time.toInt() + START_DATETIME);
// value = deleteBeforeDelimiter(line, " "); // value = deleteBeforeDelimiter(line, " ");
// jsonWriteFloat(buf, "y1", value.toFloat()); // jsonWriteFloat(buf, "y1", value.toFloat());
// if (unix_time != "" || value != "") { // if (unix_time != "" || value != "") {
// oneSingleJson += buf + ","; // oneSingleJson += buf + ",";
// } // }
// //
// } while (psn < sz); // } while (psn < sz);
// //
// configFile.close(); // configFile.close();
// } // }

View File

@@ -12,7 +12,8 @@
"int": 60, "int": 60,
"logid": "tmp", "logid": "tmp",
"num": 1, "num": 1,
"points": 255 "points": 300,
"keepdays": 2
} }
], ],
"about": { "about": {
@@ -22,11 +23,12 @@
"specialThanks": "", "specialThanks": "",
"moduleName": "Loging", "moduleName": "Loging",
"moduleVersion": "1.0", "moduleVersion": "1.0",
"moduleDesc": "Расширение позволяющее логгировать любую величину в график", "moduleDesc": "Расширение позволяющее логировать любую величину в график",
"propInfo": { "propInfo": {
"int": "Интервал", "int": "Интервал логирования",
"logid": "ID величины которую будем логгировать", "logid": "ID величины которую будем логировать",
"points": "Максимальное количество точек в одном файле" "points": "Максимальное количество точек в одном файле, может быть не более 300",
"keepdays": "Количество дней за которое необходимо хранить историю. Данные старее будут удалены автоматически"
} }
}, },
"defActive": true, "defActive": true,

View File

@@ -192,6 +192,7 @@ void removeFile(const String& filename) {
//очищаем директорию с файлами //очищаем директорию с файлами
void cleanDirectory(String path) { void cleanDirectory(String path) {
#if defined(ESP8266)
auto dir = FileFS.openDir(path); auto dir = FileFS.openDir(path);
while (dir.next()) { while (dir.next()) {
String fname = dir.fileName(); String fname = dir.fileName();
@@ -199,6 +200,21 @@ void cleanDirectory(String path) {
SerialPrint("I", "Files", path + "/" + fname + " => deleted"); SerialPrint("I", "Files", path + "/" + fname + " => deleted");
} }
onFlashWrite(); onFlashWrite();
#endif
#if defined(ESP32)
path = "/" + path;
File root = FileFS.open(path);
path = String();
if (root.isDirectory()) {
File file = root.openNextFile();
while (file) {
String fname = file.name();
removeFile(fname);
SerialPrint("I", "Files", fname + " => deleted");
file = root.openNextFile();
}
}
#endif
} }
void saveDataDB(String id, String data) { void saveDataDB(String id, String data) {
@@ -252,7 +268,7 @@ String FileList(String path) {
output += "{\"type\":\""; output += "{\"type\":\"";
output += (file.isDirectory()) ? "dir" : "file"; output += (file.isDirectory()) ? "dir" : "file";
output += "\",\"name\":\""; output += "\",\"name\":\"";
output += String(file.path()).substring(1); // output += String(file.path()).substring(1);
output += "\"}"; output += "\"}";
file = root.openNextFile(); file = root.openNextFile();
} }