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

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

View File

@@ -121,7 +121,7 @@ const String getDateTimeDotFormated() {
return String(buf);
}
const String getDateDotFormated() {
const String getTodayDateDotFormated() {
char buf[32];
sprintf(buf, "%02d.%02d.%d", _time_local.day_of_month, _time_local.month, _time_local.year + 2000);
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 == "/|") {
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);
//отправка данных графиков только в выбранный сокет
for (std::list<IoTItem*>::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) {
//сбрасываем даты графиков
// if ((*it)->getID().endsWith("-date")) {
// (*it)->setTodayDate();
//}
if ((*it)->getSubtype() == "Loging") {
(*it)->setPublishType(2, num);
(*it)->sendChart();
@@ -179,6 +195,8 @@ void webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length)
standWebSocket.sendTXT(num, settingsFlashJson);
sendFileToWs("/config.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) {
bool ok = false;
if (num == -1) {
standWebSocket.broadcastTXT(data);
ok = standWebSocket.broadcastTXT(data);
} 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::setTodayDate() {}
String IoTItem::getID() {
return _id;
};

View File

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

View File

@@ -101,6 +101,18 @@ const String addFileLn(const String& filename, const String& str) {
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) {
String path = filepath(filename);
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;
String path = filepath(filename);
auto file = FileFS.open(path, FILE_READ);
@@ -155,12 +167,11 @@ size_t countLines(const String filename) {
return cnt;
}
file.seek(0, SeekSet);
size_t size = file.size();
size = file.size();
size_t psn;
do {
cnt++;
// или /n тут один знак
file.readStringUntil('\r');
file.readStringUntil('}');
psn = file.position();
} while (psn < size);
file.close();