исправление веба. стабильная версия

This commit is contained in:
Dmitry Borisenko
2022-09-18 19:29:46 +02:00
parent 1bcf206dcc
commit 2f2e2d9755
10 changed files with 76 additions and 44 deletions

File diff suppressed because one or more lines are too long

View File

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

View File

@@ -11,7 +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 const String getTodayDateDotFormated();
extern unsigned long strDateToUnix(String date); extern unsigned long strDateToUnix(String date);
extern const String getDateTimeDotFormatedFromUnix(unsigned long unixTime); extern const String getDateTimeDotFormatedFromUnix(unsigned long unixTime);
extern unsigned long gmtTimeToLocal(unsigned long gmtTimestamp); extern unsigned long gmtTimeToLocal(unsigned long gmtTimestamp);

View File

@@ -28,6 +28,7 @@ class IoTItem {
virtual void cleanChart(); virtual void cleanChart();
virtual void setPublishType(int type, int num); virtual void setPublishType(int type, int num);
virtual void cleanData(); virtual void cleanData();
virtual void setTodayDate();
String getID(); String getID();
virtual String getValue(); virtual String getValue();

View File

@@ -8,10 +8,11 @@ extern File seekFile(const String& filename, size_t position = 0);
extern const String writeFile(const String& filename, const String& str); extern const String writeFile(const String& filename, const String& str);
const String writeEmptyFile(const String& filename); const String writeEmptyFile(const String& filename);
extern const String addFileLn(const String& filename, const String& str); extern const String addFileLn(const String& filename, const String& str);
extern const String addFile(const String& filename, const String& str);
extern const String readFile(const String& filename, size_t max_size); extern const String readFile(const String& filename, size_t max_size);
extern const String filepath(const String& filename); extern const String filepath(const String& filename);
extern bool cutFile(const String& src, const String& dst); extern bool cutFile(const String& src, const String& dst);
extern size_t countLines(const String filename); extern size_t countJsonObj(const String filename, size_t& size);
void removeFile(const String& filename); void removeFile(const String& filename);
void removeDirectory(const String& dir); void removeDirectory(const String& dir);
void cleanDirectory(String path); void cleanDirectory(String path);

View File

@@ -121,7 +121,7 @@ const String getDateTimeDotFormated() {
return String(buf); return String(buf);
} }
const String getDateDotFormated() { const String getTodayDateDotFormated() {
char buf[32]; char buf[32];
sprintf(buf, "%02d.%02d.%d", _time_local.day_of_month, _time_local.month, _time_local.year + 2000); sprintf(buf, "%02d.%02d.%d", _time_local.day_of_month, _time_local.month, _time_local.year + 2000);
return String(buf); return String(buf);

View File

@@ -57,10 +57,26 @@ void webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length)
//отвечаем данными на запрос страницы //отвечаем данными на запрос страницы
if (headerStr == "/|") { if (headerStr == "/|") {
sendFileToWs("/layout.json", num, 1024); sendFileToWs("/layout.json", num, 1024);
String json = getParamsJson(); }
//отвечаем на запрос параметров
if (headerStr == "/params|") {
String json = "{}";
jsonWriteStr(json, "params", "");
for (std::list<IoTItem*>::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) {
if ((*it)->getSubtype() != "Loging") {
if ((*it)->iAmLocal) jsonWriteStr(json, (*it)->getID(), (*it)->getValue());
}
}
standWebSocket.sendTXT(num, json); standWebSocket.sendTXT(num, json);
//отправка данных графиков только в выбранный сокет //отправка данных графиков только в выбранный сокет
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)->getID().endsWith("-date")) {
// (*it)->setTodayDate();
//}
if ((*it)->getSubtype() == "Loging") { if ((*it)->getSubtype() == "Loging") {
(*it)->setPublishType(2, num); (*it)->setPublishType(2, num);
(*it)->sendChart(); (*it)->sendChart();
@@ -179,6 +195,8 @@ void webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length)
standWebSocket.sendTXT(num, settingsFlashJson); standWebSocket.sendTXT(num, settingsFlashJson);
sendFileToWs("/config.json", num, 1024); sendFileToWs("/config.json", num, 1024);
sendFileToWs("/items.json", num, 1024); sendFileToWs("/items.json", num, 1024);
String json = getParamsJson();
standWebSocket.sendTXT(num, json);
} }
//----------------------------------------------------------------------// //----------------------------------------------------------------------//
@@ -263,10 +281,16 @@ void publishStatusWs(const String& topic, const String& data) {
//публикация статус сообщений //публикация статус сообщений
void publishChartWs(int num, String& data) { void publishChartWs(int num, String& data) {
bool ok = false;
if (num == -1) { if (num == -1) {
standWebSocket.broadcastTXT(data); ok = standWebSocket.broadcastTXT(data);
} else { } else {
standWebSocket.sendTXT(num, data); ok = standWebSocket.sendTXT(num, data);
}
if (ok) {
SerialPrint(F("i"), F("WS"), F("sent sucsess"));
} else {
SerialPrint(F("E"), F("WS"), F("sent error"));
} }
} }

View File

@@ -136,6 +136,8 @@ void IoTItem::setPublishType(int publishType, int wsNum){};
void IoTItem::cleanData() {} void IoTItem::cleanData() {}
void IoTItem::setTodayDate() {}
String IoTItem::getID() { String IoTItem::getID() {
return _id; return _id;
}; };

View File

@@ -66,7 +66,9 @@ class Loging : public IoTItem {
regEvent(value, F("Loging")); regEvent(value, F("Loging"));
String logData = String(unixTimeShort) + " " + value; String logData;
jsonWriteInt(logData, "x", unixTime);
jsonWriteInt(logData, "y1", value.toFloat());
//прочитаем путь к файлу последнего сохранения //прочитаем путь к файлу последнего сохранения
String filePath = readDataDB(id); String filePath = readDataDB(id);
@@ -78,16 +80,17 @@ class Loging : public IoTItem {
return; return;
} else { } else {
//если файл все же есть но был создан не сегодня, то создаем сегодняшний //если файл все же есть но был создан не сегодня, то создаем сегодняшний
if (getDateDotFormated() != getDateDotFormatedFromUnix(getFileUnixLocalTime(filePath))) { if (getTodayDateDotFormated() != getDateDotFormatedFromUnix(getFileUnixLocalTime(filePath))) {
SerialPrint("E", F("Loging"), "'" + id + "' file too old, start create new file"); SerialPrint("E", F("Loging"), "'" + id + "' file too old, start create new file");
createNewFileWithData(logData); createNewFileWithData(logData);
return; return;
} }
} }
//считаем количество строк //считаем количество строк и определяем размер файла
int lines = countLines(filePath); size_t size = 0;
SerialPrint("i", F("Loging"), "'" + id + "' " + String(lines) + " lines found in file"); int lines = countJsonObj(filePath, size);
SerialPrint("i", F("Loging"), "'" + id + "' " + "lines = " + String(lines) + ", size = " + String(size));
//если количество строк до заданной величины и дата не менялась //если количество строк до заданной величины и дата не менялась
if (lines <= points && !hasDayChanged()) { if (lines <= points && !hasDayChanged()) {
@@ -103,6 +106,7 @@ class Loging : public IoTItem {
} }
void createNewFileWithData(String &logData) { void createNewFileWithData(String &logData) {
logData = logData + ",";
String path = "/lg/" + id + "/" + String(unixTimeShort) + ".txt"; //создадим путь вида /lg/id/133256622333.txt String path = "/lg/" + id + "/" + String(unixTimeShort) + ".txt"; //создадим путь вида /lg/id/133256622333.txt
//создадим пустой файл //создадим пустой файл
if (writeEmptyFile(path) != "sucсess") { if (writeEmptyFile(path) != "sucсess") {
@@ -110,7 +114,7 @@ class Loging : public IoTItem {
return; return;
} }
//запишем в него данные //запишем в него данные
if (addFileLn(path, logData) != "sucсess") { if (addFile(path, logData) != "sucсess") {
SerialPrint("E", F("Loging"), "'" + id + "' data writing error, return"); SerialPrint("E", F("Loging"), "'" + id + "' data writing error, return");
return; return;
} }
@@ -123,7 +127,8 @@ class Loging : public IoTItem {
} }
void addNewDataToExistingFile(String &path, String &logData) { void addNewDataToExistingFile(String &path, String &logData) {
if (addFileLn(path, logData) != "sucсess") { logData = logData + ",";
if (addFile(path, logData) != "sucсess") {
SerialPrint("i", F("Loging"), "'" + id + "' file writing error, return"); SerialPrint("i", F("Loging"), "'" + id + "' file writing error, return");
return; return;
}; };
@@ -132,7 +137,7 @@ class Loging : public IoTItem {
bool hasDayChanged() { bool hasDayChanged() {
bool changed = false; bool changed = false;
String currentDate = getDateDotFormated(); String currentDate = getTodayDateDotFormated();
if (!firstTimeDate) { if (!firstTimeDate) {
if (prevDate != currentDate) { if (prevDate != currentDate) {
changed = true; changed = true;
@@ -227,25 +232,8 @@ class Loging : public IoTItem {
if (!configFile) { if (!configFile) {
return false; return false;
} }
configFile.seek(0, SeekSet);
String buf = "{}"; String oneSingleJson = configFile.readString();
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(); configFile.close();
@@ -253,12 +241,13 @@ class Loging : public IoTItem {
oneSingleJson = "{\"maxCount\":" + String(calculateMaxCount()) + ",\"topic\":\"" + topic + "\",\"status\":[" + oneSingleJson + "]}"; oneSingleJson = "{\"maxCount\":" + String(calculateMaxCount()) + ",\"topic\":\"" + topic + "\",\"status\":[" + oneSingleJson + "]}";
oneSingleJson.replace("},]}", "}]}"); oneSingleJson.replace("},]}", "}]}");
SerialPrint("i", "Loging", "json size: " + String(oneSingleJson.length()));
publishJson(oneSingleJson); publishJson(oneSingleJson);
return true; return true;
} }
// publishType 1 - в mqtt, 2 - в ws, 3 - mqtt и ws // publishType 1 - в mqtt, 2 - в ws, 3 - mqtt и ws, wsNum = -1 => broadcast
// wsNum = -1 => broadcast
void setPublishType(int publishType, int wsNum) { void setPublishType(int publishType, int wsNum) {
_publishType = publishType; _publishType = publishType;
_wsNum = wsNum; _wsNum = wsNum;
@@ -294,7 +283,7 @@ class Loging : public IoTItem {
void regEvent(String value, String consoleInfo = "") { void regEvent(String value, String consoleInfo = "") {
String userDate = getItemValue(id + "-date"); String userDate = getItemValue(id + "-date");
String currentDate = getDateDotFormated(); String currentDate = getTodayDateDotFormated();
//отправляем в график данные только когда выбран сегодняшний день //отправляем в график данные только когда выбран сегодняшний день
if (userDate == currentDate) { if (userDate == currentDate) {
generateEvent(_id, value); generateEvent(_id, value);
@@ -366,11 +355,15 @@ class Date : public IoTItem {
} }
} }
void setTodayDate() {
setValue(getTodayDateDotFormated());
SerialPrint("E", F("Loging"), "today date set " + getTodayDateDotFormated());
}
void doByInterval() { void doByInterval() {
if (isTimeSynch) { if (isTimeSynch) {
if (firstTime) { if (firstTime) {
setValue(getDateDotFormated()); setTodayDate();
SerialPrint("E", F("Loging"), "today date set " + getDateDotFormated());
firstTime = false; firstTime = false;
} }
} }

View File

@@ -101,6 +101,18 @@ const String addFileLn(const String& filename, const String& str) {
onFlashWrite(); onFlashWrite();
} }
const String addFile(const String& filename, const String& str) {
String path = filepath(filename);
auto file = FileFS.open(path, FILE_APPEND);
if (!file) {
return "failed";
}
file.print(str);
file.close();
return "sucсess";
onFlashWrite();
}
const String readFile(const String& filename, size_t max_size) { const String readFile(const String& filename, size_t max_size) {
String path = filepath(filename); String path = filepath(filename);
auto file = FileFS.open(path, FILE_READ); auto file = FileFS.open(path, FILE_READ);
@@ -147,7 +159,7 @@ bool cutFile(const String& src, const String& dst) {
} }
//функция считает количество строк в файле //функция считает количество строк в файле
size_t countLines(const String filename) { size_t countJsonObj(const String filename, size_t& size) {
size_t cnt = -1; size_t cnt = -1;
String path = filepath(filename); String path = filepath(filename);
auto file = FileFS.open(path, FILE_READ); auto file = FileFS.open(path, FILE_READ);
@@ -155,12 +167,11 @@ size_t countLines(const String filename) {
return cnt; return cnt;
} }
file.seek(0, SeekSet); file.seek(0, SeekSet);
size_t size = file.size(); size = file.size();
size_t psn; size_t psn;
do { do {
cnt++; cnt++;
// или /n тут один знак file.readStringUntil('}');
file.readStringUntil('\r');
psn = file.position(); psn = file.position();
} while (psn < size); } while (psn < size);
file.close(); file.close();