графики с выбором даты

This commit is contained in:
Dmitry Borisenko
2022-09-11 01:30:22 +02:00
parent 8340ae2a0f
commit 039a36a59d
14 changed files with 102 additions and 125 deletions

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -4,7 +4,7 @@
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" /> <meta name="viewport" content="width=device-width,initial-scale=1" />
<title>IoT Manager 4.2.3</title> <title>IoT Manager 4.2.5</title>
<link rel="icon" type="image/png" href="/favicon.ico" /> <link rel="icon" type="image/png" href="/favicon.ico" />
<link rel="stylesheet" href="/build/bundle.css" /> <link rel="stylesheet" href="/build/bundle.css" />

View File

@@ -11,7 +11,7 @@
"type": "Writing", "type": "Writing",
"subtype": "Loging", "subtype": "Loging",
"id": "log", "id": "log",
"widget": "chart1", "widget": "chart2",
"page": "Графики", "page": "Графики",
"descr": "Температура", "descr": "Температура",
"int": 1, "int": 1,

View File

@@ -5,7 +5,7 @@
"appass": "", "appass": "",
"routerssid": "rise2", "routerssid": "rise2",
"routerpass": "hostel3333", "routerpass": "hostel3333",
"timezone": 1, "timezone": 2,
"ntp": "pool.ntp.org", "ntp": "pool.ntp.org",
"weblogin": "admin", "weblogin": "admin",
"webpass": "admin", "webpass": "admin",

View File

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

View File

@@ -11,5 +11,7 @@ extern void synchTime();
extern const String getTimeLocal_hhmm(); extern const String getTimeLocal_hhmm();
extern const String getTimeLocal_hhmmss(); extern const String getTimeLocal_hhmmss();
extern const String getDateTimeDotFormated(); extern const String getDateTimeDotFormated();
extern const String getDateDotFormated();
extern unsigned long strDateToUnix(String date); extern unsigned long strDateToUnix(String date);
const String getDateTimeDotFormatedFromUnix(unsigned long unixTime); const String getDateTimeDotFormatedFromUnix(unsigned long unixTime);
extern unsigned long gmtTimeToLocal(unsigned long gmtTimestamp);

View File

@@ -24,7 +24,7 @@ class IoTItem {
virtual void regEvent(float value, String consoleInfo); virtual void regEvent(float value, String consoleInfo);
String getSubtype(); String getSubtype();
virtual void sendChart(bool mqtt); virtual void sendChart(int type);
virtual void cleanData(); virtual void cleanData();
String getID(); String getID();

View File

@@ -6,7 +6,7 @@
"appass": "", "appass": "",
"routerssid": "rise2", "routerssid": "rise2",
"routerpass": "hostel3333", "routerpass": "hostel3333",
"timezone": 1, "timezone": 2,
"ntp": "pool.ntp.org", "ntp": "pool.ntp.org",
"weblogin": "admin", "weblogin": "admin",
"webpass": "admin", "webpass": "admin",

View File

@@ -137,7 +137,7 @@ void mqttCallback(char* topic, uint8_t* payload, size_t length) {
//отправка данных графиков //отправка данных графиков
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") {
(*it)->sendChart(true); (*it)->sendChart(1);
} }
} }

View File

@@ -39,6 +39,10 @@ void synchTime() {
configTime(0, 0, "pool.ntp.org", "ru.pool.ntp.org", "pool.ntp.org"); configTime(0, 0, "pool.ntp.org", "ru.pool.ntp.org", "pool.ntp.org");
} }
unsigned long gmtTimeToLocal(unsigned long gmtTimestamp) {
return gmtTimestamp + (jsonReadInt(settingsFlashJson, F("timezone")) * 60 * 60);
}
time_t getSystemTime() { time_t getSystemTime() {
timeval tv{0, 0}; timeval tv{0, 0};
timezone tz = timezone{0, 0}; timezone tz = timezone{0, 0};
@@ -117,6 +121,13 @@ const String getDateTimeDotFormated() {
return String(buf); return String(buf);
} }
const String getDateDotFormated() {
char buf[32];
sprintf(buf, "%02d.%02d.%d", _time_local.day_of_month, _time_local.month, _time_local.year + 2000);
return String(buf);
}
// format 22.02.2022
unsigned long strDateToUnix(String date) { unsigned long strDateToUnix(String date) {
int day = selectToMarker(date, ".").toInt(); int day = selectToMarker(date, ".").toInt();
date = deleteBeforeDelimiter(date, "."); date = deleteBeforeDelimiter(date, ".");

View File

@@ -62,7 +62,7 @@ void webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length)
//отправка данных графиков //отправка данных графиков
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") {
(*it)->sendChart(false); (*it)->sendChart(2);
} }
} }
} }

View File

@@ -128,7 +128,7 @@ String IoTItem::getSubtype() {
return _subtype; return _subtype;
} }
void IoTItem::sendChart(bool mqtt) {} void IoTItem::sendChart(int type) {}
void IoTItem::cleanData() {} void IoTItem::cleanData() {}

View File

@@ -12,8 +12,6 @@ class Loging : public IoTItem {
String id; String id;
String filesList = ""; String filesList = "";
bool firstTime = true;
int points; int points;
int keepdays; int keepdays;
@@ -35,43 +33,11 @@ class Loging : public IoTItem {
jsonRead(parameters, F("keepdays"), keepdays); jsonRead(parameters, F("keepdays"), keepdays);
//создадим экземпляр класса даты //создадим экземпляр класса даты
dateIoTItem = (IoTItem *)getAPI_Date("{\"id\": \"" + id + "-date\"}"); dateIoTItem = (IoTItem *)getAPI_Date("{\"id\": \"" + id + "-date\",\"int\":\"20\"}");
IoTItems.push_back(dateIoTItem); IoTItems.push_back(dateIoTItem);
} }
String getValue() {
return "";
}
void loop() {
if (enableDoByInt) {
currentMillis = millis();
difference = currentMillis - prevMillis;
if (difference >= interval) {
prevMillis = millis();
this->doByInterval();
}
}
}
void regEvent(String value, String consoleInfo = "") {
generateEvent(_id, value);
publishStatusMqtt(_id, value);
String json = createSingleJson(_id, value);
publishStatusWsJson(json);
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 + "}]}";
}
void doByInterval() { void doByInterval() {
if (firstTime) {
firstTime = false;
}
//если объект логгирования не был создан //если объект логгирования не был создан
if (!isItemExist(logid)) { if (!isItemExist(logid)) {
SerialPrint("E", F("Loging"), "'" + id + "' loging object not exist"); SerialPrint("E", F("Loging"), "'" + id + "' loging object not exist");
@@ -171,35 +137,44 @@ class Loging : public IoTItem {
#endif #endif
} }
void sendChart(bool mqtt) { void sendChart(int type) {
getFilesList(); getFilesList();
int f = 0; int f = 0;
bool noData = true;
while (filesList.length()) { while (filesList.length()) {
String buf = selectToMarker(filesList, ";"); String buf = selectToMarker(filesList, ";");
f++; f++;
int i = 0; int i = 0;
unsigned long fileUnixTime = selectToMarkerLast(deleteToMarkerLast(buf, "."), "/").toInt() + START_DATETIME; unsigned long fileUnixTimeGMT = selectToMarkerLast(deleteToMarkerLast(buf, "."), "/").toInt() + START_DATETIME;
unsigned long fileUnixTimeLocal = gmtTimeToLocal(fileUnixTimeGMT);
//удаление старых файлов //удаление старых файлов
if ((fileUnixTime + (points * (interval / 1000))) < (unixTime - (keepdays * 86400))) { // if ((fileUnixTimeLocal + (points * (interval / 1000))) < (unixTime - (keepdays * 86400))) {
SerialPrint("i", F("Loging"), "file '" + buf + "' too old, deleted"); // SerialPrint("i", F("Loging"), "file '" + buf + "' too old, deleted");
removeFile(buf); // removeFile(buf);
} else { //} else {
unsigned long reqUnixTime = strDateToUnix(date); unsigned long reqUnixTime = strDateToUnix(date);
if (fileUnixTime > reqUnixTime && fileUnixTime < reqUnixTime + 86400) { if (fileUnixTimeLocal > reqUnixTime && fileUnixTimeLocal < reqUnixTime + 86400) {
createJson(buf, i, mqtt); noData = false;
SerialPrint("i", F("Loging"), "file '" + buf + "' sent, user requested " + date); createJson(buf, i, type);
SerialPrint("i", F("Loging"), String(f) + ")" + buf + ", " + String(i) + ", " + getDateTimeDotFormatedFromUnix(fileUnixTimeLocal) + ", sent");
} else { } else {
SerialPrint("i", F("Loging"), "file '" + buf + "' skipped, user requested " + date); SerialPrint("i", F("Loging"), String(f) + ")" + buf + ", " + String(i) + ", " + getDateTimeDotFormatedFromUnix(fileUnixTimeLocal) + ", skipped");
}
} }
//}
SerialPrint("i", F("Loging"), String(f) + ") path: " + buf + ", lines №: " + String(i) + ", created: " + getDateTimeDotFormatedFromUnix(fileUnixTime));
filesList = deleteBeforeDelimiter(filesList, ";"); filesList = deleteBeforeDelimiter(filesList, ";");
} }
//если данных нет отправляем пустой грфик
if (noData) {
SerialPrint("i", F("Loging"), "clear chart");
String cleanJson = createEmtyJson();
publishJson(cleanJson, type);
}
} }
void cleanData() { void cleanData() {
@@ -216,64 +191,7 @@ class Loging : public IoTItem {
} }
} }
// void sendChart2(bool mqtt) { void createJson(String file, int &i, int type) {
// //отправка графика может происходить только если время синхронизированно
// 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)
// 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
//
// SerialPrint("i", F("Loging"), "'" + id + "'--------------'" + String(i) + "'--------------");
// }
void createJson(String file, int &i, bool mqtt) {
File configFile = FileFS.open(file, "r"); File configFile = FileFS.open(file, "r");
if (!configFile) { if (!configFile) {
SerialPrint("E", F("Loging"), "'" + id + "' open file error"); SerialPrint("E", F("Loging"), "'" + id + "' open file error");
@@ -305,17 +223,53 @@ class Loging : public IoTItem {
oneSingleJson = "{\"maxCount\":" + String(calculateMaxCount()) + ",\"topic\":\"" + topic + "\",\"status\":[" + oneSingleJson + "]}"; oneSingleJson = "{\"maxCount\":" + String(calculateMaxCount()) + ",\"topic\":\"" + topic + "\",\"status\":[" + oneSingleJson + "]}";
oneSingleJson.replace("},]}", "}]}"); oneSingleJson.replace("},]}", "}]}");
publishJson(oneSingleJson, mqtt); publishJson(oneSingleJson, type);
} }
void publishJson(String &oneSingleJson, bool mqtt) { void publishJson(String &oneSingleJson, int type) {
if (mqtt) { if (type == 1) {
publishChart(id, oneSingleJson);
} else if (type == 2) {
publishStatusWsJson(oneSingleJson);
} else if (type == 3) {
publishChart(id, oneSingleJson); publishChart(id, oneSingleJson);
} else {
publishStatusWsJson(oneSingleJson); publishStatusWsJson(oneSingleJson);
} }
} }
String getValue() {
return "";
}
void loop() {
if (enableDoByInt) {
currentMillis = millis();
difference = currentMillis - prevMillis;
if (difference >= interval) {
prevMillis = millis();
this->doByInterval();
}
}
}
void regEvent(String value, String consoleInfo = "") {
generateEvent(_id, value);
publishStatusMqtt(_id, value);
String json = createSingleJson(_id, value);
publishStatusWsJson(json);
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;
@@ -332,6 +286,8 @@ void *getAPI_Loging(String subtype, String param) {
class Date : public IoTItem { class Date : public IoTItem {
private: private:
bool firstTime = true;
public: public:
String id; String id;
Date(String parameters) : IoTItem(parameters) { Date(String parameters) : IoTItem(parameters) {
@@ -350,12 +306,20 @@ class Date : public IoTItem {
regEvent(value.valS, ""); regEvent(value.valS, "");
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") {
(*it)->sendChart(true); (*it)->sendChart(3);
} }
} }
} }
void doByInterval() {} void doByInterval() {
if (isTimeSynch) {
if (firstTime) {
setValue(getDateDotFormated());
SerialPrint("E", F("Loging"), "today date set " + getDateDotFormated());
firstTime = false;
}
}
}
}; };
void *getAPI_Date(String param) { void *getAPI_Date(String param) {