отправка данных графиков в веб интерфейс

This commit is contained in:
Dmitry Borisenko
2022-08-31 00:13:45 +02:00
parent 1c5de5b92e
commit d947e9da71
10 changed files with 46 additions and 20 deletions

View File

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

View File

@@ -15,6 +15,7 @@ extern void hexdump(const void* mem, uint32_t len, uint8_t cols);
void sendFileToWs(const char* filename, uint8_t num, size_t frameSize); void sendFileToWs(const char* filename, uint8_t num, size_t frameSize);
void publishStatusWs(const String& topic, const String& data); void publishStatusWs(const String& topic, const String& data);
void publishStatusWsJson(const String& topic, String& json);
void periodicWsSend(); void periodicWsSend();
void sendStringToWs(const String& msg, uint8_t num, String name); void sendStringToWs(const String& msg, uint8_t num, String name);

View File

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

View File

@@ -13,6 +13,7 @@ extern bool cutFile(const String& src, const String& dst);
extern size_t countLines(const String filename); extern size_t countLines(const String filename);
void removeFile(const String& filename); void removeFile(const String& filename);
void cleanDirectory(String path); void cleanDirectory(String path);
void cleanLogs();
void saveDataDB(String id, String data); void saveDataDB(String id, String data);
String readDataDB(String id); String readDataDB(String id);
extern void onFlashWrite(); extern void onFlashWrite();

View File

@@ -25,7 +25,7 @@ void globalVarsSync() {
String getParamsJson() { String getParamsJson() {
String json; String json;
serializeJson(*getLocalItemsAsJSON(), json); // Ilya, data: "1.00" (analog sensor, round set to 1, should be "1.0") serializeJson(*getLocalItemsAsJSON(), json);
jsonWriteStr_(json, "params", ""); jsonWriteStr_(json, "params", "");
return json; return json;
} }

View File

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

View File

@@ -51,11 +51,16 @@ void webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length)
} }
// Страница веб интерфейса dashboard=================================================================== // Страница веб интерфейса dashboard===================================================================
// отправляем только файл layout.json //
if (headerStr == "/|") { if (headerStr == "/|") {
sendFileToWs("/layout.json", num, 1024);
String json = getParamsJson(); String json = getParamsJson();
standWebSocket.sendTXT(num, json); standWebSocket.sendTXT(num, json);
sendFileToWs("/layout.json", num, 1024); //отправка данных графиков
for (std::list<IoTItem*>::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) {
if ((*it)->getSubtype() == "Loging") {
(*it)->sendChart(false);
}
}
} }
// Страница веб интерфейса configutation================================================================ // Страница веб интерфейса configutation================================================================
//========отправка=========================================================// //========отправка=========================================================//
@@ -150,8 +155,7 @@ void webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length)
} }
//команда очистки всех логов esp// //команда очистки всех логов esp//
if (headerStr == "/clean|") { if (headerStr == "/clean|") {
cleanDirectory("lg"); cleanLogs();
cleanDirectory("db");
} }
//Прием сообщений cotrol ============================================================================== //Прием сообщений cotrol ==============================================================================
@@ -203,13 +207,20 @@ void webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length)
//публикация статус сообщений //публикация статус сообщений
void publishStatusWs(const String& topic, const String& data) { void publishStatusWs(const String& topic, const String& data) {
String path = mqttRootDevice + "/" + topic; //+ "/status"; String path = mqttRootDevice + "/" + topic;
String json = "{}"; String json = "{}";
jsonWriteStr(json, "status", data); jsonWriteStr(json, "status", data);
jsonWriteStr(json, "topic", path); jsonWriteStr(json, "topic", path);
standWebSocket.broadcastTXT(json); standWebSocket.broadcastTXT(json);
} }
//публикация статус сообщений уже готовых
void publishStatusWsJson(const String& topic, String& json) {
String path = mqttRootDevice + "/" + topic;
jsonWriteStr(json, "topic", path);
standWebSocket.broadcastTXT(json);
}
//данные которые мы отправляем в сокеты переодически //данные которые мы отправляем в сокеты переодически
void periodicWsSend() { void periodicWsSend() {
standWebSocket.broadcastTXT(devListHeapJson); standWebSocket.broadcastTXT(devListHeapJson);

View File

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

View File

@@ -17,7 +17,7 @@ class Loging : public IoTItem {
jsonRead(parameters, F("logid"), logid); jsonRead(parameters, F("logid"), logid);
jsonRead(parameters, F("id"), id); jsonRead(parameters, F("id"), id);
jsonRead(parameters, F("points"), points); jsonRead(parameters, F("points"), points);
if (points >= 300) { if (points > 300) {
points = 300; points = 300;
SerialPrint("E", F("Loging"), "'" + id + "' user set more points than allowed, value reset to 300"); SerialPrint("E", F("Loging"), "'" + id + "' user set more points than allowed, value reset to 300");
} }
@@ -91,7 +91,7 @@ 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() { void sendChart(bool mqtt) {
SerialPrint("i", F("Loging"), "'" + id + "'----------------------------"); SerialPrint("i", F("Loging"), "'" + id + "'----------------------------");
String reqUnixTimeStr = "27.08.2022"; //нужно получить эту дату из окна ввода под графиком. String reqUnixTimeStr = "27.08.2022"; //нужно получить эту дату из окна ввода под графиком.
unsigned long reqUnixTime = strDateToUnix(reqUnixTimeStr); unsigned long reqUnixTime = strDateToUnix(reqUnixTimeStr);
@@ -124,7 +124,7 @@ class Loging : public IoTItem {
// if (fileUnixTime > reqUnixTime && fileUnixTime < reqUnixTime + 86400) { // if (fileUnixTime > reqUnixTime && fileUnixTime < reqUnixTime + 86400) {
SerialPrint("i", F("Loging"), "'" + id + "' matching file found '" + fname + "'"); SerialPrint("i", F("Loging"), "'" + id + "' matching file found '" + fname + "'");
//выгрузка по частям, по одному файлу //выгрузка по частям, по одному файлу
publishJsonPartly("/lg/" + fname, calculateMaxCount(), i); publishJsonPartly("/lg/" + fname, calculateMaxCount(), i, mqtt);
//} //}
//удаление старых файлов //удаление старых файлов
if ((fileUnixTime + (points * interval)) < (unixTime - (keepdays * 86400))) { if ((fileUnixTime + (points * interval)) < (unixTime - (keepdays * 86400))) {
@@ -144,7 +144,7 @@ class Loging : public IoTItem {
SerialPrint("i", F("Loging"), "'" + id + "'--------------'" + String(i) + "'--------------"); SerialPrint("i", F("Loging"), "'" + id + "'--------------'" + String(i) + "'--------------");
} }
void publishJsonPartly(String file, int maxCount, int &i) { void publishJsonPartly(String file, int maxCount, 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");
@@ -171,14 +171,17 @@ class Loging : public IoTItem {
} while (psn < sz); } while (psn < sz);
configFile.close(); configFile.close();
publishJson(dividedJson, maxCount);
publishJson(dividedJson, maxCount, mqtt);
} }
void publishJson(String & oneSingleJson, int &maxCount) { void publishJson(String & oneSingleJson, int &maxCount, bool mqtt) {
oneSingleJson = "{\"maxCount\":" + String(maxCount) + ",\"status\":[" + oneSingleJson + "]}"; oneSingleJson = "{\"maxCount\":" + String(maxCount) + ",\"status\":[" + oneSingleJson + "]}";
oneSingleJson.replace("},]}", "}]}"); oneSingleJson.replace("},]}", "}]}");
if (!publishChart(id, oneSingleJson)) { if (mqtt) {
SerialPrint("E", F("Loging"), "'" + id + "' mqtt publish error"); publishChart(id, oneSingleJson);
} else {
publishStatusWsJson(id, oneSingleJson);
} }
} }

View File

@@ -197,7 +197,7 @@ void cleanDirectory(String path) {
while (dir.next()) { while (dir.next()) {
String fname = dir.fileName(); String fname = dir.fileName();
removeFile(path + "/" + fname); removeFile(path + "/" + fname);
SerialPrint("I", "Files", path + "/" + fname + " => deleted"); SerialPrint("i", "Files", path + "/" + fname + " => deleted");
} }
onFlashWrite(); onFlashWrite();
#endif #endif
@@ -205,12 +205,16 @@ void cleanDirectory(String path) {
path = "/" + path; path = "/" + path;
File root = FileFS.open(path); File root = FileFS.open(path);
path = String(); path = String();
if (!root) {
SerialPrint("E", "Files", "nothing to delete");
return;
}
if (root.isDirectory()) { if (root.isDirectory()) {
File file = root.openNextFile(); File file = root.openNextFile();
while (file) { while (file) {
String fname = file.name(); String fname = file.name();
removeFile(fname); removeFile(fname);
SerialPrint("I", "Files", fname + " => deleted"); SerialPrint("i", "Files", fname + " => deleted");
file = root.openNextFile(); file = root.openNextFile();
} }
} }
@@ -227,6 +231,11 @@ String readDataDB(String id) {
return readFile(path, 2000); return readFile(path, 2000);
} }
void cleanLogs() {
cleanDirectory("lg");
cleanDirectory("db");
}
//счетчик количества записей на флешь за сеанс //счетчик количества записей на флешь за сеанс
void onFlashWrite() { void onFlashWrite() {
flashWriteNumber++; flashWriteNumber++;