Files
IoTManager/src/modules/virtual/Loging2/Loging2.cpp

496 lines
16 KiB
C++
Raw Normal View History

2025-03-28 20:43:10 +03:00
#include "Global.h"
#include "classes/IoTItem.h"
#include "ESPConfiguration.h"
#include "NTP.h"
void *getAPI_Date2(String params);
2025-03-28 22:47:10 +03:00
class Loging2 : public IoTItem
{
private:
2025-03-28 20:43:10 +03:00
String logid1;
String logid2;
String id;
String tmpValue;
String filesList = "";
int _publishType = -2;
int _wsNum = -1;
int points;
2025-03-28 22:47:10 +03:00
// int keepdays;
2025-03-28 20:43:10 +03:00
IoTItem *dateIoTItem;
String prevDate = "";
bool firstTimeInit = true;
2025-03-28 22:47:10 +03:00
// long interval;
2025-03-28 20:43:10 +03:00
2025-03-28 22:47:10 +03:00
public:
Loging2(String parameters) : IoTItem(parameters)
{
2025-03-28 20:43:10 +03:00
jsonRead(parameters, F("logid1"), logid1);
jsonRead(parameters, F("logid2"), logid2);
jsonRead(parameters, F("id"), id);
jsonRead(parameters, F("points"), points);
2025-03-28 22:47:10 +03:00
if (points > 300)
{
2025-03-28 20:43:10 +03:00
points = 300;
SerialPrint("E", F("Loging2"), "'" + id + "' user set more points than allowed, value reset to 300");
}
long interval;
2025-03-28 22:47:10 +03:00
jsonRead(parameters, F("int"), interval); // в минутах
setInterval(interval * 60);
// jsonRead(parameters, F("keepdays"), keepdays, false);
2025-03-28 20:43:10 +03:00
// создадим экземпляр класса даты
dateIoTItem = (IoTItem *)getAPI_Date2("{\"id\": \"" + id + "-date\",\"int\":\"20\",\"subtype\":\"date\"}");
IoTItems.push_back(dateIoTItem);
SerialPrint("I", F("Loging2"), "created date instance " + id);
}
2025-03-28 22:47:10 +03:00
void doByInterval()
{
2025-03-28 20:43:10 +03:00
// если объект логгирования не был создан
2025-03-28 22:47:10 +03:00
if (!isItemExist(logid1))
{
2025-03-28 20:43:10 +03:00
SerialPrint("E", F("Loging2"), "'" + id + "' loging object not exist, return");
return;
}
String value = getItemValue(logid1);
// если значение логгирования пустое
2025-03-28 22:47:10 +03:00
if (value == "")
{
2025-03-28 20:43:10 +03:00
SerialPrint("E", F("Loging2"), "'" + id + "' loging value is empty, return");
return;
}
2025-03-28 22:47:10 +03:00
String value2 = getItemValue(logid2);
2025-03-28 20:43:10 +03:00
// если значение логгирования пустое
2025-03-28 22:47:10 +03:00
if (value == "")
{
2025-03-28 20:43:10 +03:00
SerialPrint("E", F("Loging2"), "'" + id + "' loging value is empty, return");
return;
}
// если время не было получено из интернета
2025-03-28 22:47:10 +03:00
if (!isTimeSynch)
{
2025-03-28 20:43:10 +03:00
SerialPrint("E", F("Loging2"), "'" + id + "' Сant loging - time not synchronized, return");
return;
}
regEvent(value, F("Loging2"));
String logData2;
jsonWriteInt(logData2, "x", unixTime, false);
jsonWriteFloat(logData2, "y1", value.toFloat(), false);
jsonWriteFloat(logData2, "y2", value2.toFloat(), false);
// прочитаем путь к файлу последнего сохранения
String filePath = readDataDB(id);
// если данные о файле отсутствуют, создадим новый
2025-03-28 22:47:10 +03:00
if (filePath == "failed" || filePath == "")
{
2025-03-28 20:43:10 +03:00
SerialPrint("E", F("Loging2"), "'" + id + "' file path not found, start create new file");
createNewFileWithData(logData2);
return;
2025-03-28 22:47:10 +03:00
}
else
{
2025-03-28 20:43:10 +03:00
// если файл все же есть но был создан не сегодня, то создаем сегодняшний
2025-03-28 22:47:10 +03:00
if (getTodayDateDotFormated() != getDateDotFormatedFromUnix(getFileUnixLocalTime(filePath)))
{
2025-03-28 20:43:10 +03:00
SerialPrint("E", F("Loging2"), "'" + id + "' file too old, start create new file");
createNewFileWithData(logData2);
return;
}
}
// считаем количество строк и определяем размер файла
size_t size = 0;
int lines = countJsonObj(filePath, size);
SerialPrint("i", F("Loging2"), "'" + id + "' " + "lines = " + String(lines) + ", size = " + String(size));
// если количество строк до заданной величины и дата не менялась
2025-03-28 22:47:10 +03:00
if (lines <= points && !hasDayChanged())
{
2025-03-28 20:43:10 +03:00
// просто добавим в существующий файл новые данные
addNewDataToExistingFile(filePath, logData2);
// если больше или поменялась дата то создадим следующий файл
2025-03-28 22:47:10 +03:00
}
else
{
2025-03-28 20:43:10 +03:00
createNewFileWithData(logData2);
}
// запускаем процедуру удаления старых файлов если память переполняется
deleteLastFile();
}
2025-03-28 22:47:10 +03:00
/*
void SetDoByInterval(String valse)
{
2025-03-28 20:43:10 +03:00
String value = valse;
// если значение логгирования пустое
2025-03-28 22:47:10 +03:00
if (value == "")
{
2025-03-28 20:43:10 +03:00
SerialPrint("E", F("Loging2Event"), "'" + id + "' loging value is empty, return");
return;
}
// если время не было получено из интернета
2025-03-28 22:47:10 +03:00
if (!isTimeSynch)
{
2025-03-28 20:43:10 +03:00
SerialPrint("E", F("Loging2Event"), "'" + id + "' Сant loging - time not synchronized, return");
return;
}
regEvent(value, F("Loging2Event"));
String logData2;
jsonWriteInt(logData2, "x", unixTime, false);
jsonWriteFloat(logData2, "y1", value.toFloat(), false);
jsonWriteFloat(logData2, "y2", value.toFloat(), false);
// прочитаем путь к файлу последнего сохранения
String filePath = readDataDB(id);
// если данные о файле отсутствуют, создадим новый
2025-03-28 22:47:10 +03:00
if (filePath == "failed" || filePath == "")
{
2025-03-28 20:43:10 +03:00
SerialPrint("E", F("Loging2Event"), "'" + id + "' file path not found, start create new file");
createNewFileWithData(logData2);
return;
2025-03-28 22:47:10 +03:00
}
else
{
2025-03-28 20:43:10 +03:00
// если файл все же есть но был создан не сегодня, то создаем сегодняшний
2025-03-28 22:47:10 +03:00
if (getTodayDateDotFormated() != getDateDotFormatedFromUnix(getFileUnixLocalTime(filePath)))
{
2025-03-28 20:43:10 +03:00
SerialPrint("E", F("Loging2Event"), "'" + id + "' file too old, start create new file");
createNewFileWithData(logData2);
return;
}
}
// считаем количество строк и определяем размер файла
size_t size = 0;
int lines = countJsonObj(filePath, size);
SerialPrint("i", F("Loging2Event"), "'" + id + "' " + "lines = " + String(lines) + ", size = " + String(size));
// если количество строк до заданной величины и дата не менялась
2025-03-28 22:47:10 +03:00
if (lines <= points && !hasDayChanged())
{
2025-03-28 20:43:10 +03:00
// просто добавим в существующий файл новые данные
addNewDataToExistingFile(filePath, logData2);
// если больше или поменялась дата то создадим следующий файл
2025-03-28 22:47:10 +03:00
}
else
{
2025-03-28 20:43:10 +03:00
createNewFileWithData(logData2);
}
// запускаем процедуру удаления старых файлов если память переполняется
deleteLastFile();
}
2025-03-28 22:47:10 +03:00
*/
void createNewFileWithData(String &logData)
{
2025-03-28 20:43:10 +03:00
logData = logData + ",";
2025-03-28 22:47:10 +03:00
String path = "/lg2/" + id + "/" + String(unixTimeShort) + ".txt"; // создадим путь вида /lg/id/133256622333.txt
2025-03-28 20:43:10 +03:00
// создадим пустой файл
2025-03-28 22:47:10 +03:00
if (writeEmptyFile(path) != "success")
{
2025-03-28 20:43:10 +03:00
SerialPrint("E", F("Loging2"), "'" + id + "' file writing error, return");
return;
}
// запишем в него данные
2025-03-28 22:47:10 +03:00
if (addFile(path, logData) != "success")
{
2025-03-28 20:43:10 +03:00
SerialPrint("E", F("Loging2"), "'" + id + "' data writing error, return");
return;
}
// запишем путь к нему в базу данных
2025-03-28 22:47:10 +03:00
if (saveDataDB(id, path) != "success")
{
2025-03-28 20:43:10 +03:00
SerialPrint("E", F("Loging2"), "'" + id + "' db file writing error, return");
return;
}
SerialPrint("i", F("Loging2"), "'" + id + "' file created http://" + WiFi.localIP().toString() + path);
}
2025-03-28 22:47:10 +03:00
void addNewDataToExistingFile(String &path, String &logData)
{
2025-03-28 20:43:10 +03:00
logData = logData + ",";
2025-03-28 22:47:10 +03:00
if (addFile(path, logData) != "success")
{
2025-03-28 20:43:10 +03:00
SerialPrint("i", F("Loging2"), "'" + id + "' file writing error, return");
return;
};
SerialPrint("i", F("Loging2"), "'" + id + "' loging in file http://" + WiFi.localIP().toString() + path);
}
// данная функция уже перенесена в ядро и будет удалена в последствии
2025-03-28 22:47:10 +03:00
bool hasDayChanged()
{
2025-03-28 20:43:10 +03:00
bool changed = false;
String currentDate = getTodayDateDotFormated();
2025-03-28 22:47:10 +03:00
if (!firstTimeInit)
{
if (prevDate != currentDate)
{
2025-03-28 20:43:10 +03:00
changed = true;
SerialPrint("i", F("NTP"), F("Change day event"));
#if defined(ESP8266)
FileFS.gc();
#endif
#if defined(ESP32)
#endif
}
}
firstTimeInit = false;
prevDate = currentDate;
return changed;
}
2025-03-28 22:47:10 +03:00
void publishValue()
{
2025-03-28 20:43:10 +03:00
String dir = "/lg2/" + id;
filesList = getFilesList(dir);
SerialPrint("i", F("Loging2"), "file list: " + filesList);
int f = 0;
bool noData = true;
2025-03-28 22:47:10 +03:00
while (filesList.length())
{
2025-03-28 20:43:10 +03:00
String path = selectToMarker(filesList, ";");
path = "/lg2/" + id + path;
f++;
unsigned long fileUnixTimeLocal = getFileUnixLocalTime(path);
unsigned long reqUnixTime = strDateToUnix(getItemValue(id + "-date"));
2025-03-28 22:47:10 +03:00
if (fileUnixTimeLocal > reqUnixTime && fileUnixTimeLocal < reqUnixTime + 86400)
{
2025-03-28 20:43:10 +03:00
noData = false;
String json = getAdditionalJson();
2025-03-28 22:47:10 +03:00
if (_publishType == TO_MQTT)
{
2025-03-28 20:43:10 +03:00
publishChartFileToMqtt(path, id, calculateMaxCount());
2025-03-28 22:47:10 +03:00
}
else if (_publishType == TO_WS)
{
2025-03-28 20:43:10 +03:00
sendFileToWsByFrames(path, "charta", json, _wsNum, WEB_SOCKETS_FRAME_SIZE);
2025-03-28 22:47:10 +03:00
}
else if (_publishType == TO_MQTT_WS)
{
2025-03-28 20:43:10 +03:00
sendFileToWsByFrames(path, "charta", json, _wsNum, WEB_SOCKETS_FRAME_SIZE);
publishChartFileToMqtt(path, id, calculateMaxCount());
}
SerialPrint("i", F("Loging2"), String(f) + ") " + path + ", " + getDateTimeDotFormatedFromUnix(fileUnixTimeLocal) + ", sent");
2025-03-28 22:47:10 +03:00
}
else
{
2025-03-28 20:43:10 +03:00
SerialPrint("i", F("Loging2"), String(f) + ") " + path + ", " + getDateTimeDotFormatedFromUnix(fileUnixTimeLocal) + ", skipped");
}
filesList = deleteBeforeDelimiter(filesList, ";");
}
// если данных нет отправляем пустой грфик
2025-03-28 22:47:10 +03:00
if (noData)
{
2025-03-28 20:43:10 +03:00
clearValue();
}
}
2025-03-28 22:47:10 +03:00
String getAdditionalJson()
{
2025-03-28 20:43:10 +03:00
String topic = mqttRootDevice + "/" + id;
String json = "{\"maxCount\":" + String(calculateMaxCount()) + ",\"topic\":\"" + topic + "\"}";
return json;
}
2025-03-28 22:47:10 +03:00
void publishChartToWsSinglePoint(String value)
{
2025-03-28 20:43:10 +03:00
String topic = mqttRootDevice + "/" + id;
2025-03-28 22:47:10 +03:00
String value2 = getItemValue(logid2);
String json = "{\"maxCount\":" + String(calculateMaxCount()) + ",\"topic\":\"" + topic + "\",\"status\":[{\"x\":" + String(unixTime) + ",\"y1\":" + value + ",\"y2\":" + value2 + "}]}";
2025-03-28 20:43:10 +03:00
sendStringToWs("chartb", json, -1);
}
2025-03-28 22:47:10 +03:00
void clearValue()
{
2025-03-28 20:43:10 +03:00
String topic = mqttRootDevice + "/" + id;
String json = "{\"maxCount\":0,\"topic\":\"" + topic + "\",\"status\":[]}";
sendStringToWs("chartb", json, -1);
}
2025-03-28 22:47:10 +03:00
void clearHistory()
{
2025-03-28 20:43:10 +03:00
String dir = "/lg2/" + id;
cleanDirectory(dir);
}
2025-03-28 22:47:10 +03:00
void deleteLastFile()
{
2025-03-28 20:43:10 +03:00
IoTFSInfo tmp = getFSInfo();
SerialPrint("i", "Loging2", String(tmp.freePer) + " % free flash remaining");
2025-03-28 22:47:10 +03:00
if (tmp.freePer <= 20.00)
{
2025-03-28 20:43:10 +03:00
String dir = "/lg/" + id;
filesList = getFilesList(dir);
int i = 0;
2025-03-28 22:47:10 +03:00
while (filesList.length())
{
2025-03-28 20:43:10 +03:00
String path = selectToMarker(filesList, ";");
path = dir + path;
i++;
2025-03-28 22:47:10 +03:00
if (i == 1)
{
2025-03-28 20:43:10 +03:00
removeFile(path);
SerialPrint("!", "Loging2", String(i) + ") " + path + " => oldest files been deleted");
return;
}
filesList = deleteBeforeDelimiter(filesList, ";");
}
}
}
2025-03-28 22:47:10 +03:00
void setPublishDestination(int publishType, int wsNum)
{
2025-03-28 20:43:10 +03:00
_publishType = publishType;
_wsNum = wsNum;
}
2025-03-28 22:47:10 +03:00
String getValue()
{
2025-03-28 20:43:10 +03:00
return "";
}
2025-03-28 22:47:10 +03:00
/*
void loop() {
if (enableDoByInt) {
currentMillis = millis();
difference = currentMillis - prevMillis;
if (difference >= interval) {
prevMillis = millis();
if (interval != 0) {
this->doByInterval();
}
2025-03-28 20:43:10 +03:00
}
}
}
2025-03-28 22:47:10 +03:00
*/
void regEvent(const String &value, const String &consoleInfo, bool error = false, bool genEvent = true)
{
2025-03-28 20:43:10 +03:00
String userDate = getItemValue(id + "-date");
String currentDate = getTodayDateDotFormated();
// отправляем в график данные только когда выбран сегодняшний день
2025-03-28 22:47:10 +03:00
if (userDate == currentDate)
{
2025-03-28 20:43:10 +03:00
// generateEvent(_id, value);
// publishStatusMqtt(_id, value);
publishChartToWsSinglePoint(value);
// SerialPrint("i", "Sensor " + consoleInfo, "'" + _id + "' data: " + value + "'");
}
}
// просто максимальное количество точек
2025-03-28 22:47:10 +03:00
int calculateMaxCount()
{
2025-03-28 20:43:10 +03:00
return 86400;
}
// путь вида: /lg/log/1231231.txt
2025-03-28 22:47:10 +03:00
unsigned long getFileUnixLocalTime(String path)
{
2025-03-28 20:43:10 +03:00
return gmtTimeToLocal(selectToMarkerLast(deleteToMarkerLast(path, "."), "/").toInt() + START_DATETIME);
}
2025-03-28 22:47:10 +03:00
/*
void setValue(const IoTValue &Value, bool genEvent = true)
{
2025-03-28 20:43:10 +03:00
value = Value;
this->SetDoByInterval(String(value.valD));
SerialPrint("i", "Loging2", "setValue:" + String(value.valD));
regEvent(value.valS, "Loging2", false, genEvent);
}
2025-03-28 22:47:10 +03:00
*/
2025-03-28 20:43:10 +03:00
};
2025-03-28 22:47:10 +03:00
void *getAPI_Loging2(String subtype, String param)
{
if (subtype == F("Loging2"))
{
2025-03-28 20:43:10 +03:00
return new Loging2(param);
2025-03-28 22:47:10 +03:00
}
else
{
2025-03-28 20:43:10 +03:00
return nullptr;
}
}
2025-03-28 22:47:10 +03:00
class Date : public IoTItem
{
private:
2025-03-28 20:43:10 +03:00
bool firstTime = true;
2025-03-28 22:47:10 +03:00
public:
2025-03-28 20:43:10 +03:00
String id;
2025-03-28 22:47:10 +03:00
Date(String parameters) : IoTItem(parameters)
{
2025-03-28 20:43:10 +03:00
jsonRead(parameters, F("id"), id);
value.isDecimal = false;
}
2025-03-28 22:47:10 +03:00
void setValue(const String &valStr, bool genEvent = true)
{
2025-03-28 20:43:10 +03:00
value.valS = valStr;
setValue(value, genEvent);
}
2025-03-28 22:47:10 +03:00
void setValue(const IoTValue &Value, bool genEvent = true)
{
2025-03-28 20:43:10 +03:00
value = Value;
regEvent(value.valS, "", false, genEvent);
// отправка данных при изменении даты
2025-03-28 22:47:10 +03:00
for (std::list<IoTItem *>::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it)
{
if ((*it)->getSubtype() == "Loging2")
{
if ((*it)->getID() == selectToMarker(id, "-"))
{
2025-03-28 20:43:10 +03:00
(*it)->setPublishDestination(TO_MQTT_WS, -1);
(*it)->publishValue();
}
}
}
}
2025-03-28 22:47:10 +03:00
void setTodayDate()
{
2025-03-28 20:43:10 +03:00
setValue(getTodayDateDotFormated());
SerialPrint("E", F("Loging2"), "today date set " + getTodayDateDotFormated());
}
2025-03-28 22:47:10 +03:00
void doByInterval()
{
if (isTimeSynch)
{
if (firstTime)
{
2025-03-28 20:43:10 +03:00
setTodayDate();
firstTime = false;
}
}
}
};
2025-03-28 22:47:10 +03:00
void *getAPI_Date2(String param)
{
2025-03-28 20:43:10 +03:00
return new Date(param);
}