рабочие графики

This commit is contained in:
Dmitry Borisenko
2022-09-26 16:19:44 +02:00
parent c7477872a8
commit e7e174de10
4 changed files with 41 additions and 40 deletions

View File

@@ -1 +0,0 @@
{"x":0,"y1":0},

View File

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

View File

@@ -142,6 +142,11 @@ class Loging : public IoTItem {
if (prevDate != currentDate) { if (prevDate != currentDate) {
changed = true; changed = true;
SerialPrint("i", F("NTP"), "Change day event"); SerialPrint("i", F("NTP"), "Change day event");
#if defined(ESP8266)
FileFS.gc();
#endif
#if defined(ESP32)
#endif
} }
} }
firstTimeDate = false; firstTimeDate = false;
@@ -172,12 +177,12 @@ class Loging : public IoTItem {
if (fileUnixTimeLocal > reqUnixTime && fileUnixTimeLocal < reqUnixTime + 86400) { if (fileUnixTimeLocal > reqUnixTime && fileUnixTimeLocal < reqUnixTime + 86400) {
noData = false; noData = false;
if (_publishType == TO_MQTT) { if (_publishType == TO_MQTT) {
sendChartFileToMqtt(path); publishChartFileToMqtt(path);
} else if (_publishType == TO_WS) { } else if (_publishType == TO_WS) {
sendChartFileToWs(path, _wsNum, 1000); publishChartToWs(path, _wsNum, 1000);
} else if (_publishType == TO_MQTT_WS) { } else if (_publishType == TO_MQTT_WS) {
sendChartFileToMqtt(path); publishChartFileToMqtt(path);
sendChartFileToWs(path, _wsNum, 1000); publishChartToWs(path, _wsNum, 1000);
} }
SerialPrint("i", F("Loging"), String(f) + ") " + path + ", " + getDateTimeDotFormatedFromUnix(fileUnixTimeLocal) + ", sent"); SerialPrint("i", F("Loging"), String(f) + ") " + path + ", " + getDateTimeDotFormatedFromUnix(fileUnixTimeLocal) + ", sent");
} else { } else {
@@ -192,11 +197,6 @@ class Loging : public IoTItem {
} }
} }
void clearValue() {
SerialPrint("i", F("Loging"), "clear chart");
sendChartFileToWs("/empty.txt", -1, 1000);
}
void clearHistory() { void clearHistory() {
String dir = "/lg/" + id; String dir = "/lg/" + id;
cleanDirectory(dir); cleanDirectory(dir);
@@ -211,9 +211,7 @@ class Loging : public IoTItem {
int i = 0; int i = 0;
while (filesList.length()) { while (filesList.length()) {
String path = selectToMarker(filesList, ";"); String path = selectToMarker(filesList, ";");
path = dir + path; path = dir + path;
i++; i++;
if (i == 1) { if (i == 1) {
removeFile(path); removeFile(path);
@@ -226,7 +224,7 @@ class Loging : public IoTItem {
} }
} }
bool sendChartFileToMqtt(String path) { bool publishChartFileToMqtt(String path) {
File configFile = FileFS.open(path, FILE_READ); File configFile = FileFS.open(path, FILE_READ);
if (!configFile) { if (!configFile) {
SerialPrint("E", F("Loging"), path + " file reading error, json not created, return"); SerialPrint("E", F("Loging"), path + " file reading error, json not created, return");
@@ -234,18 +232,21 @@ class Loging : public IoTItem {
} }
String oneSingleJson = configFile.readString(); String oneSingleJson = configFile.readString();
configFile.close(); configFile.close();
// String topic = mqttRootDevice + "/" + id; String topic = mqttRootDevice + "/" + id;
// oneSingleJson = "{\"maxCount\":" + String(calculateMaxCount()) + ",\"topic\":\"" + topic + "\",\"status\":[" + oneSingleJson + "]}"; oneSingleJson = "{\"maxCount\":" + String(calculateMaxCount()) + ",\"topic\":\"" + topic + "\",\"status\":[" + oneSingleJson + "]}";
oneSingleJson += "]}";
oneSingleJson.replace("},]}", "}]}"); oneSingleJson.replace("},]}", "}]}");
SerialPrint("i", "Loging", "json size: " + String(oneSingleJson.length())); SerialPrint("i", "Loging", "json size: " + String(oneSingleJson.length()));
publishChartMqtt(id, oneSingleJson); publishChartMqtt(id, oneSingleJson);
return true; return true;
} }
void sendChartFileToWs(String filename, int num, size_t frameSize) { //особая функция отправки графиков в веб
String topic = mqttRootDevice + "/" + id; void publishChartToWs(String filename, int num, size_t frameSize) {
String st = "/st/chart.json|" + topic; String json;
jsonWriteStr(json, "topic", mqttRootDevice + "/" + id);
jsonWriteInt(json, "maxCount", calculateMaxCount());
String st = "/st/chart.json|";
if (num == -1) { if (num == -1) {
standWebSocket.broadcastTXT(st); standWebSocket.broadcastTXT(st);
} else { } else {
@@ -270,7 +271,7 @@ class Loging : public IoTItem {
countRead = file.read(payload, sizeof(payload)); countRead = file.read(payload, sizeof(payload));
} }
file.close(); file.close();
String end = "/end/chart.json|" + topic; String end = "/end/chart.json|" + json;
if (num == -1) { if (num == -1) {
standWebSocket.broadcastTXT(end); standWebSocket.broadcastTXT(end);
} else { } else {
@@ -278,6 +279,20 @@ class Loging : public IoTItem {
} }
} }
void clearValue() {
String topic = mqttRootDevice + "/" + id;
String json = "{\"maxCount\":0,\"topic\":\"" + topic + "\",\"status\":[]}";
String pk = "/string/chart.json|" + json;
standWebSocket.broadcastTXT(pk);
}
void publishChartToWsSinglePoint(String value) {
String topic = mqttRootDevice + "/" + id;
String json = "{\"maxCount\":" + String(calculateMaxCount()) + ",\"topic\":\"" + topic + "\",\"status\":[{\"x\":" + String(unixTime) + ",\"y1\":" + value + "}]}";
String pk = "/string/chart.json|" + json;
standWebSocket.broadcastTXT(pk);
}
void setPublishDestination(int publishType, int wsNum = -1) { void setPublishDestination(int publishType, int wsNum = -1) {
_publishType = publishType; _publishType = publishType;
_wsNum = wsNum; _wsNum = wsNum;
@@ -305,22 +320,12 @@ class Loging : public IoTItem {
if (userDate == currentDate) { if (userDate == currentDate) {
// generateEvent(_id, value); // generateEvent(_id, value);
// publishStatusMqtt(_id, value); // publishStatusMqtt(_id, value);
// String json = createSingleJson(_id, value);
// publishChartWs(-1, json); publishChartToWsSinglePoint(value);
// SerialPrint("i", "Sensor " + consoleInfo, "'" + _id + "' data: " + value + "'"); // SerialPrint("i", "Sensor " + consoleInfo, "'" + _id + "' data: " + value + "'");
} }
} }
String createSingleJson(String id, String value) {
String topic = mqttRootDevice + "/" + _id;
return "{\"topic\":\"" + topic + "\",\"status\":[{\"x\":" + String(unixTime) + ",\"y1\":" + value + "}]}";
}
String createEmtyJson() {
String topic = mqttRootDevice + "/" + _id;
return "{\"topic\":\"" + topic + "\",\"status\":[],\"maxCount\":\"0\"}";
}
//просто максимальное количество точек //просто максимальное количество точек
int calculateMaxCount() { int calculateMaxCount() {
return 86400; return 86400;
@@ -362,7 +367,6 @@ class Date : public IoTItem {
//отправка данных при изменении даты //отправка данных при изменении даты
for (std::list<IoTItem *>::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) { for (std::list<IoTItem *>::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) {
if ((*it)->getSubtype() == "Loging") { if ((*it)->getSubtype() == "Loging") {
//отправляем только свои данные
if ((*it)->getID() == selectToMarker(id, "-")) { if ((*it)->getID() == selectToMarker(id, "-")) {
(*it)->setPublishDestination(TO_MQTT_WS); (*it)->setPublishDestination(TO_MQTT_WS);
(*it)->clearValue(); (*it)->clearValue();

View File

@@ -9,11 +9,10 @@
"widget": "chart2", "widget": "chart2",
"page": "Графики", "page": "Графики",
"descr": "Температура", "descr": "Температура",
"num": 1,
"int": 5, "int": 5,
"logid": "t", "logid": "t",
"num": 1, "points": 300
"points": 300,
"keepdays": 2
} }
], ],
"about": { "about": {
@@ -25,12 +24,11 @@
"moduleVersion": "3.0", "moduleVersion": "3.0",
"usedRam": 15, "usedRam": 15,
"title": "Логирование в график", "title": "Логирование в график",
"moduleDesc": "Расширение позволяющее логировать любую величину в график. Графики доступны в мобильном приложении и в веб интерфейсе. Данные графиков хранятся в встроенной памяти esp. График отображает период времени выбранный пользователем. В окне ввода даты нужно выбрать день, историю которого вы хотите посмотреть", "moduleDesc": "Расширение позволяющее логировать любую величину в график. Графики доступны в мобильном приложении и в веб интерфейсе. Данные графиков хранятся в встроенной памяти esp. В окне ввода даты нужно выбрать день, историю которого вы хотите посмотреть. Старые файлы будут удаляться автоматически после того как объем оставшейся flesh памяти устройства будет менее 20 процентов",
"propInfo": { "propInfo": {
"int": "Интервал логирования в мнутах, рекомендуется для esp8266 использоать интервал не менее 5-ти минут", "int": "Интервал логирования в мнутах, рекомендуется для esp8266 использоать интервал не менее 5-ти минут",
"logid": "ID величины которую будем логировать", "logid": "ID величины которую будем логировать",
"points": "Максимальное количество точек в одном файле, может быть не более 300. Не рекомендуется менять этот параметр", "points": "Максимальное количество точек в одном файле, может быть не более 300. Не рекомендуется менять этот параметр"
"keepdays": "Количество дней за которое необходимо хранить историю. Данные старее будут удалены автоматически"
} }
}, },
"defActive": true, "defActive": true,