переписаны графики

This commit is contained in:
Dmitry Borisenko
2022-09-08 00:27:38 +02:00
parent 5acd080fe0
commit 12ef79c558
10 changed files with 240 additions and 139 deletions

View File

@@ -3,7 +3,7 @@
"name": "IoTmanagerVer4", "name": "IoTmanagerVer4",
"apssid": "IoTmanager", "apssid": "IoTmanager",
"appass": "", "appass": "",
"routerssid": "rise", "routerssid": "rise2",
"routerpass": "hostel3333", "routerpass": "hostel3333",
"timezone": 1, "timezone": 1,
"ntp": "pool.ntp.org", "ntp": "pool.ntp.org",

View File

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

View File

@@ -12,3 +12,4 @@ extern const String getTimeLocal_hhmm();
extern const String getTimeLocal_hhmmss(); extern const String getTimeLocal_hhmmss();
extern const String getDateTimeDotFormated(); extern const String getDateTimeDotFormated();
extern unsigned long strDateToUnix(String date); extern unsigned long strDateToUnix(String date);
const String getDateTimeDotFormatedFromUnix(unsigned long unixTime);

View File

@@ -25,6 +25,7 @@ class IoTItem {
String getSubtype(); String getSubtype();
virtual void sendChart(bool mqtt); virtual void sendChart(bool mqtt);
virtual void cleanData();
String getID(); String getID();
virtual String getValue(); virtual String getValue();

View File

@@ -4,7 +4,7 @@
"name": "IoTmanagerVer4", "name": "IoTmanagerVer4",
"apssid": "IoTmanager", "apssid": "IoTmanager",
"appass": "", "appass": "",
"routerssid": "rise", "routerssid": "rise2",
"routerpass": "hostel3333", "routerpass": "hostel3333",
"timezone": 1, "timezone": 1,
"ntp": "pool.ntp.org", "ntp": "pool.ntp.org",

View File

@@ -62,7 +62,7 @@ void setup() {
//запуск работы udp //запуск работы udp
asyncUdpInit(); asyncUdpInit();
//подготавливаем сценарии //подготавливаем сценарии
iotScen.loadScenario("/scenario.txt"); iotScen.loadScenario("/scenario.txt");
@@ -123,7 +123,7 @@ void loop() {
#endif #endif
#ifdef STANDARD_WEB_SERVER #ifdef STANDARD_WEB_SERVER
//обработка web сервера //обработка web сервера 1
HTTP.handleClient(); HTTP.handleClient();
#endif #endif
@@ -135,6 +135,11 @@ void loop() {
//обновление mqtt //обновление mqtt
mqttLoop(); mqttLoop();
#ifdef STANDARD_WEB_SERVER
//обработка web сервера 2
// HTTP.handleClient();
#endif
// передаем управление каждому элементу конфигурации для выполнения своих функций // передаем управление каждому элементу конфигурации для выполнения своих функций
for (std::list<IoTItem *>::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) { for (std::list<IoTItem *>::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) {
(*it)->loop(); (*it)->loop();
@@ -149,6 +154,11 @@ void loop() {
handleEvent(); handleEvent();
#ifdef STANDARD_WEB_SERVER
//обработка web сервера 3
// HTTP.handleClient();
#endif
// сохраняем значения IoTItems в файл каждую секунду, если были изменения (установлены маркеры на сохранение) // сохраняем значения IoTItems в файл каждую секунду, если были изменения (установлены маркеры на сохранение)
// currentMillis = millis(); // currentMillis = millis();
// if (currentMillis - prevMillis >= 1000) { // if (currentMillis - prevMillis >= 1000) {

View File

@@ -137,3 +137,11 @@ unsigned long strDateToUnix(String date) {
} }
return (day * secsInOneDay) + (numberOfDaysInPastMonths * secsInOneDay) + (totalNormalYears * daysInOneYear * secsInOneDay) + (numberOfLeepYears * daysInLeepYear * secsInOneDay); return (day * secsInOneDay) + (numberOfDaysInPastMonths * secsInOneDay) + (totalNormalYears * daysInOneYear * secsInOneDay) + (numberOfLeepYears * daysInLeepYear * secsInOneDay);
} }
const String getDateTimeDotFormatedFromUnix(unsigned long unixTime) {
Time_t time;
breakEpochToTime(unixTime, time);
char buf[32];
sprintf(buf, "%02d.%02d.%02d %02d:%02d:%02d", time.day_of_month, time.month, time.year, time.hour, time.minute, time.second);
return String(buf);
}

View File

@@ -33,7 +33,8 @@ IoTItem::IoTItem(String parameters) {
_map2 = selectFromMarkerToMarker(map, ",", 1).toInt(); _map2 = selectFromMarkerToMarker(map, ",", 1).toInt();
_map3 = selectFromMarkerToMarker(map, ",", 2).toInt(); _map3 = selectFromMarkerToMarker(map, ",", 2).toInt();
_map4 = selectFromMarkerToMarker(map, ",", 3).toInt(); _map4 = selectFromMarkerToMarker(map, ",", 3).toInt();
} else _map1 = _map2 = _map3 = _map4 = 0; } else
_map1 = _map2 = _map3 = _map4 = 0;
} }
//луп выполняющий переодическое дерганье //луп выполняющий переодическое дерганье
@@ -65,7 +66,8 @@ String IoTItem::getValue() {
return value.valS = buf; return value.valS = buf;
} else } else
return (String)value.valD; return (String)value.valD;
} else return value.valS; } else
return value.valS;
} }
//установить //установить
@@ -128,6 +130,8 @@ String IoTItem::getSubtype() {
void IoTItem::sendChart(bool mqtt) {} void IoTItem::sendChart(bool mqtt) {}
void IoTItem::cleanData() {}
String IoTItem::getID() { String IoTItem::getID() {
return _id; return _id;
}; };

View File

@@ -6,6 +6,8 @@ class Loging : public IoTItem {
private: private:
String logid; String logid;
String id; String id;
String filesList = "";
int points; int points;
int keepdays; int keepdays;
@@ -56,13 +58,13 @@ class Loging : public IoTItem {
//прочитаем путь к файлу последнего сохранения //прочитаем путь к файлу последнего сохранения
String filePath = readDataDB(id); String filePath = readDataDB(id);
// Serial.println("filePath " + filePath);
//если данные о файле отсутствуют, создадим новый //если данные о файле отсутствуют, создадим новый
if (filePath == "failed" || filePath == "") { 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;
} else {
// SerialPrint("i", F("Loging"), "'" + id + "' file path found " + filePath);
} }
//считаем количество строк //считаем количество строк
@@ -80,7 +82,7 @@ class Loging : public IoTItem {
} }
void createNewFileWithData(String &logData) { void createNewFileWithData(String &logData) {
String path = "/lg/" + id + "-" + String(unixTimeShort) + ".txt"; //создадим путь String path = "/lg/" + id + "/" + String(unixTimeShort) + ".txt"; //создадим путь вида /lg/id/133256622333.txt
addFileLn(path, logData); //запишем файл и данные в него addFileLn(path, logData); //запишем файл и данные в него
saveDataDB(id, path); //запишем путь к файлу в базу данных saveDataDB(id, path); //запишем путь к файлу в базу данных
SerialPrint("i", F("Loging"), "'" + id + "' file created http://" + WiFi.localIP().toString() + path); SerialPrint("i", F("Loging"), "'" + id + "' file created http://" + WiFi.localIP().toString() + path);
@@ -91,146 +93,216 @@ class Loging : public IoTItem {
SerialPrint("i", F("Loging"), "'" + id + "' loging in file http://" + WiFi.localIP().toString() + path); SerialPrint("i", F("Loging"), "'" + id + "' loging in file http://" + WiFi.localIP().toString() + path);
} }
void sendChart(bool mqtt) {
//отправка графика может происходить только если время синхронизированно
if (!isTimeSynch) {
SerialPrint("E", F("Loging"), "'" + id + "' Сant send chart - time not synchronized");
return;
}
SerialPrint("i", F("Loging"), "'" + id + "'----------------------------");
String reqUnixTimeStr = "27.08.2022"; //нужно получить эту дату из окна ввода под графиком.
unsigned long reqUnixTime = strDateToUnix(reqUnixTimeStr);
int i = 0;
#if defined(ESP8266) #if defined(ESP8266)
String directory = "lg"; void getFilesList8266() {
filesList = "";
String directory = "lg/" + id;
auto dir = FileFS.openDir(directory); auto dir = FileFS.openDir(directory);
while (dir.next()) { while (dir.next()) {
String fname = dir.fileName(); String fname = dir.fileName();
if (fname != "") filesList += directory + "/" + fname + ";";
}
}
#endif
#if defined(ESP32)
void getFilesList32() {
filesList = "";
String directory = "/lg/" + id;
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();
if (fname != "") filesList += directory + "/" + fname + ";";
}
}
}
#endif
void getFilesList() {
#if defined(ESP8266)
getFilesList8266();
#endif #endif
#if defined(ESP32) #if defined(ESP32)
String directory = "/lg"; getFilesList32();
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 + "'");
//выгрузка по частям, по одному файлу
createJson("/lg/" + fname, i, mqtt);
//}
//удаление старых файлов
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);
}
}
#if defined(ESP32)
}
#endif #endif
}
SerialPrint("i", F("Loging"), "'" + id + "'--------------'" + String(i) + "'--------------"); void sendChart(bool mqtt) {
} getFilesList();
int f = 0;
void createJson(String file, int &i, bool mqtt) { while (filesList.length()) {
File configFile = FileFS.open(file, "r"); String buf = selectToMarker(filesList, ";");
if (!configFile) {
SerialPrint("E", F("Loging"), "'" + id + "' open file error");
return;
}
configFile.seek(0, SeekSet);
String buf = "{}";
String oneSingleJson;
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 != "") {
oneSingleJson += buf + ",";
}
} while (psn < sz);
configFile.close(); f++;
int i = 0;
createJson(buf, i, mqtt);
unsigned long fileUnixTime = selectToMarkerLast(deleteToMarkerLast(buf, "."), "/").toInt() + START_DATETIME;
SerialPrint("i", F("Loging"), String(f) + ") path: " + buf + ", lines №: " + String(i) + ", creation time: " + getDateTimeDotFormatedFromUnix(fileUnixTime));
String topic = mqttRootDevice + "/" + id; filesList = deleteBeforeDelimiter(filesList, ";");
oneSingleJson = "{\"maxCount\":" + String(calculateMaxCount()) + ",\"topic\":\"" + topic + "\",\"status\":[" + oneSingleJson + "]}";
oneSingleJson.replace("},]}", "}]}");
publishJson(oneSingleJson, mqtt);
}
void publishJson(String & oneSingleJson, bool mqtt) {
if (mqtt) {
publishChart(id, oneSingleJson);
} else {
publishStatusWsJson(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 cleanData() {
// void createOneSingleJson(String &oneSingleJson, String file, int &maxCount, int &i) { getFilesList();
// File configFile = FileFS.open(file, "r"); int i = 0;
// if (!configFile) { while (filesList.length()) {
// return; String buf = selectToMarker(filesList, ";");
// }
// configFile.seek(0, SeekSet); i++;
// String buf = "{}"; removeFile(buf);
// String unix_time; SerialPrint("i", "Files", String(i) + ") " + buf + " => deleted");
// String value;
// unsigned int psn; filesList = deleteBeforeDelimiter(filesList, ";");
// unsigned int sz = configFile.size(); }
// do { }
// maxCount++;
// i++; // void sendChart2(bool mqtt) {
// psn = configFile.position(); // //отправка графика может происходить только если время синхронизированно
// String line = configFile.readStringUntil('\n'); // if (!isTimeSynch) {
// unix_time = selectToMarker(line, " "); // SerialPrint("E", F("Loging"), "'" + id + "' Сant send chart - time not synchronized");
// jsonWriteInt(buf, "x", unix_time.toInt() + START_DATETIME); // return;
// value = deleteBeforeDelimiter(line, " "); // }
// jsonWriteFloat(buf, "y1", value.toFloat()); // SerialPrint("i", F("Loging"), "'" + id + "'----------------------------");
// if (unix_time != "" || value != "") { // String reqUnixTimeStr = "27.08.2022"; //нужно получить эту дату из окна ввода под графиком.
// oneSingleJson += buf + ","; // unsigned long reqUnixTime = strDateToUnix(reqUnixTimeStr);
// }
// //
// } while (psn < sz); // int i = 0;
//#if defined(ESP8266)
// String directory = "lg";
// auto dir = FileFS.openDir(directory);
// while (dir.next()) {
// 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, "-");
// 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 + "'");
// //выгрузка по частям, по одному файлу
// createJson("/lg/" + fname, i, mqtt);
// //}
// //удаление старых файлов
// 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);
// }
// }
//#if defined(ESP32)
// }
//#endif
// //
// configFile.close(); // SerialPrint("i", F("Loging"), "'" + id + "'--------------'" + String(i) + "'--------------");
// } // }
void createJson(String file, int &i, bool mqtt) {
File configFile = FileFS.open(file, "r");
if (!configFile) {
SerialPrint("E", F("Loging"), "'" + id + "' open file error");
return;
}
configFile.seek(0, SeekSet);
String buf = "{}";
String oneSingleJson;
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 != "") {
oneSingleJson += buf + ",";
}
} while (psn < sz);
configFile.close();
String topic = mqttRootDevice + "/" + id;
oneSingleJson = "{\"maxCount\":" + String(calculateMaxCount()) + ",\"topic\":\"" + topic + "\",\"status\":[" + oneSingleJson + "]}";
oneSingleJson.replace("},]}", "}]}");
publishJson(oneSingleJson, mqtt);
}
void publishJson(String &oneSingleJson, bool mqtt) {
if (mqtt) {
publishChart(id, oneSingleJson);
} else {
publishStatusWsJson(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();
// }

View File

@@ -183,7 +183,7 @@ void removeFile(const String& filename) {
String path = filepath(filename); String path = filepath(filename);
if (FileFS.exists(path)) { if (FileFS.exists(path)) {
if (!FileFS.remove(path)) { if (!FileFS.remove(path)) {
SerialPrint("I", "Files", "remove " + path); // SerialPrint("i", "Files", "remove " + path);
} }
} else { } else {
SerialPrint("E", "Files", "not exist " + path); SerialPrint("E", "Files", "not exist " + path);
@@ -232,8 +232,13 @@ String readDataDB(String id) {
} }
void cleanLogs() { void cleanLogs() {
cleanDirectory("lg");
cleanDirectory("db"); cleanDirectory("db");
//очистка данных всех экземпляров графиков
for (std::list<IoTItem*>::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) {
if ((*it)->getSubtype() == "Loging") {
(*it)->cleanData();
}
}
} }
//счетчик количества записей на флешь за сеанс //счетчик количества записей на флешь за сеанс