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,
"logid": "tmp",
"num": 1,
"points": 255
"points": 300,
"keepdays": 2
},
{
"name": "2. Таймер",
@@ -442,16 +443,18 @@
"num": 33
},
{
"name": "34. PWM ESP8266",
"name": "34. PWM ESP32",
"type": "Writing",
"subtype": "Pwm8266",
"subtype": "Pwm32",
"id": "pwm",
"widget": "range",
"page": "Кнопки",
"descr": "PWM",
"int": 0,
"pin": 15,
"pin": 2,
"freq": 5000,
"ledChannel": 2,
"PWM_resolution": 10,
"val": 0,
"apin": -1,
"num": 34

View File

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

View File

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

View File

@@ -39,7 +39,7 @@ build_src_filter =
${env:esp32_4mb_fromitems.build_src_filter}
[platformio]
default_envs = esp8266_4mb
default_envs = esp32_4mb
data_dir = data_svelte
[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_Mcp23017(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_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_Mcp23017(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_Lcd2004(subtype, params)) != nullptr) return tmpAPI;
return nullptr;

View File

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

View File

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

View File

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