Merge branch 'ver4dev' into ver4dev

This commit is contained in:
2022-10-14 18:01:46 +03:00
committed by GitHub
19 changed files with 117 additions and 113 deletions

2
.gitignore vendored
View File

@@ -3,4 +3,6 @@
.vscode/c_cpp_properties.json
.vscode/launch.json
.vscode/ipch
/myProfile_wm.json
/myProfile.json
data_svelte/settings.json

Binary file not shown.

Binary file not shown.

View File

@@ -19,5 +19,6 @@
"pinSCL": 0,
"pinSDA": 0,
"i2cFreq": 100000,
"wg": "group1",
"settings_": ""
}

View File

@@ -23,6 +23,8 @@
#define JSON_BUFFER_SIZE 2048
#define WEB_SOCKETS_FRAME_SIZE 2048
//#define LOOP_DEBUG
//выбор сервера
//#define ASYNC_WEB_SERVER
//#define ASYNC_WEB_SOCKETS

View File

@@ -137,6 +137,8 @@ extern Time_t _time_local;
extern Time_t _time_utc;
extern bool _time_isTrust;
extern unsigned long loopPeriod;
// extern DynamicJsonDocument settingsFlashJsonDoc;
// extern DynamicJsonDocument paramsFlashJsonDoc;
// extern DynamicJsonDocument paramsHeapJsonDoc;

View File

@@ -10,8 +10,5 @@
extern void periodicTasksInit();
extern void printGlobalVarSize();
extern void handleError(String errorId, String errorValue);
extern void handleError(String errorId, int errorValue);
extern String ESP_getResetReason(void);
extern String ESP32GetResetReason(uint32_t cpu_no);

View File

@@ -17,5 +17,5 @@ void publishStatusWs(const String& topic, const String& data);
void publishChartWs(int num, String& path);
void periodicWsSend();
void sendFileToWsByFrames(const String& filename, const String& header, const String& json, uint8_t client_id, size_t frameSize);
void sendFileToWsByFrames(const String& filename, const String& header, const String& json, int client_id, size_t frameSize);
void sendStringToWs(const String& header, String& payload, int client_id);

View File

@@ -22,6 +22,7 @@
"pinSDA": 0,
"i2cFreq": 100000,
"settings_": ""
"wg": "group1"
},
"projectProp": {
"platformio": {

View File

@@ -191,7 +191,7 @@ build_src_filter =
[env:esp32_4mb_fromitems]
lib_deps =
Adafruit AHTX0
https://github.com/enjoyneering/AHTxx.git
adafruit/Adafruit BME280 Library
adafruit/Adafruit BMP280 Library
beegee-tokyo/DHT sensor library for ESPx
@@ -199,7 +199,6 @@ lib_deps =
https://github.com/JonasGMorsch/GY-21.git
ClosedCube HDC1080
adafruit/MAX6675 library
mandulaj/PZEM-004T-v30
rc-switch @ ^2.6.4
robtillaart/SHT2x@^0.1.1
WEMOS SHT3x@1.0.0
@@ -208,35 +207,37 @@ lib_deps =
adafruit/Adafruit MCP23017 Arduino Library@^2.1.0
adafruit/Adafruit BusIO @ ^1.13.2
dfrobot/DFRobotDFPlayerMini @ ^1.0.5
adafruit/Adafruit BusIO @ ^1.13.2
marcoschwartz/LiquidCrystal_I2C@^1.1.4
build_src_filter =
+<modules\virtual\Loging>
+<modules\virtual\LogingDaily>
+<modules\virtual\Timer>
+<modules\virtual\Variable>
+<modules\virtual\VButton>
+<modules\sensors\Acs712>
+<modules\sensors\Aht20>
+<modules\sensors\AnalogAdc>
+<modules\sensors\Bme280>
+<modules\sensors\Bmp280>
+<modules\sensors\Dht1122>
+<modules\sensors\Ds18b20>
+<modules\sensors\GY21>
+<modules\sensors\Hdc1080>
+<modules\sensors\Max6675>
+<modules\sensors\Pzem004t>
+<modules\sensors\RCswitch>
+<modules\sensors\Sht20>
+<modules\sensors\Sht30>
+<modules\sensors\Sonar>
+<modules\sensors\UART>
+<modules\exec\ButtonIn>
+<modules\exec\ButtonOut>
+<modules\exec\IoTServo>
+<modules\exec\Mcp23017>
+<modules\exec\Mp3>
+<modules\exec\Pwm32>
+<modules\exec\TelegramLT>
+<modules\display\Lcd2004>
+<modules/virtual/Loging>
+<modules/virtual/LogingDaily>
+<modules/virtual/Timer>
+<modules/virtual/Variable>
+<modules/virtual/VButton>
+<modules/sensors/Acs712>
+<modules/sensors/AhtXX>
+<modules/sensors/AnalogAdc>
+<modules/sensors/Bme280>
+<modules/sensors/Bmp280>
+<modules/sensors/Dht1122>
+<modules/sensors/Ds18b20>
+<modules/sensors/GY21>
+<modules/sensors/Hdc1080>
+<modules/sensors/Max6675>
+<modules/sensors/Pzem004t>
+<modules/sensors/RCswitch>
+<modules/sensors/Sht20>
+<modules/sensors/Sht30>
+<modules/sensors/Sonar>
+<modules/sensors/UART>
+<modules/exec/ButtonIn>
+<modules/exec/ButtonOut>
+<modules/exec/IoTServo>
+<modules/exec/Mcp23017>
+<modules/exec/Mp3>
+<modules/exec/Pcf8574>
+<modules/exec/Pwm32>
+<modules/exec/TelegramLT>
+<modules/display/Lcd2004>

View File

@@ -2,7 +2,8 @@
const String getThisDevice() {
String thisDevice = "{}";
jsonWriteStr_(thisDevice, F("devicelist_"), ""); //метка для парсинга нужна для udp валидации может быть рабочей группой в последствии
jsonWriteStr_(thisDevice, F("devicelist_"), ""); //метка для парсинга
jsonWriteStr_(thisDevice, F("wg"), jsonReadStr(settingsFlashJson, F("wg"))); //рабочая группа
jsonWriteStr_(thisDevice, F("ip"), jsonReadStr(settingsFlashJson, F("ip")));
jsonWriteStr_(thisDevice, F("id"), jsonReadStr(settingsFlashJson, F("id")));
jsonWriteStr_(thisDevice, F("name"), jsonReadStr(settingsFlashJson, F("name")));
@@ -52,7 +53,7 @@ void asyncUdpInit() {
});
}
//будем отправлять каждые 30 секунд презентацию данного устройства
//будем отправлять каждые 60 секунд презентацию данного устройства
ts.add(
UDP, 60000, [&](void*) { // UDPP
if (isNetworkActive()) {
@@ -68,7 +69,9 @@ void asyncUdpInit() {
}
bool udpPacketValidation(String& data) {
if (data.indexOf("devicelist_") != -1) {
// SerialPrint("i", F("UDP"), data);
String workgroup = jsonReadStr(settingsFlashJson, "wg");
if (workgroup != "" && data.indexOf(workgroup) != -1) {
return true;
} else {
return false;

View File

@@ -27,10 +27,6 @@ void handleOrder() {
String id = selectToMarker(order, " ");
//это модификатор для даты графика
// if (id.endsWith("-date")) {
//}
//здесь нужно перебрать все методы execute всех векторов и выполнить те id которых совпали с id события
IoTItem* item = findIoTItem(id);
if (item) {

View File

@@ -68,6 +68,8 @@ String mqttRootDevice = "";
unsigned long unixTime = 0;
unsigned long unixTimeShort = 0;
unsigned long loopPeriod;
bool isTimeSynch = false;
Time_t _time_local;
Time_t _time_utc;

View File

@@ -116,38 +116,22 @@ void setup() {
}
void loop() {
// if(millis()%2000==0){
// //watch->settimeUnix(time(&iotTimeNow));
// Serial.println(watch->gettime("d-m-Y, H:i:s, M"));
// delay(1);
// }
//обновление задач таскера
ts.update();
//отправка json
#ifdef QUEUE_FROM_STR
if (sendJsonFiles) sendJsonFiles->loop();
#ifdef LOOP_DEBUG
unsigned long st = millis();
#endif
ts.update();
#ifdef STANDARD_WEB_SERVER
//обработка web сервера 1
HTTP.handleClient();
#endif
#ifdef STANDARD_WEB_SOCKETS
//обработка web сокетов
standWebSocket.loop();
#endif
//обновление mqtt
mqttLoop();
#ifdef STANDARD_WEB_SERVER
//обработка web сервера 2
// HTTP.handleClient();
#endif
// передаем управление каждому элементу конфигурации для выполнения своих функций
for (std::list<IoTItem *>::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) {
(*it)->loop();
@@ -159,33 +143,43 @@ void loop() {
}
handleOrder();
handleEvent();
#ifdef STANDARD_WEB_SERVER
//обработка web сервера 3
// HTTP.handleClient();
#ifdef LOOP_DEBUG
loopPeriod = millis() - st;
if (loopPeriod > 2) Serial.println(loopPeriod);
#endif
// сохраняем значения IoTItems в файл каждую секунду, если были изменения (установлены маркеры на сохранение)
// currentMillis = millis();
// if (currentMillis - prevMillis >= 1000) {
// prevMillis = millis();
// volStrForSave = "";
// for (std::list<IoTItem *>::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) {
// if ((*it)->needSave) {
// (*it)->needSave = false;
// volStrForSave = volStrForSave + (*it)->getID() + "=" + (*it)->getValue() + ";";
// }
// }
//
// if (volStrForSave != "") {
// Serial.print("volStrForSave: ");
// Serial.println(volStrForSave.c_str());
// }
//}
}
//отправка json
//#ifdef QUEUE_FROM_STR
// if (sendJsonFiles) sendJsonFiles->loop();
//#endif
// if(millis()%2000==0){
// //watch->settimeUnix(time(&iotTimeNow));
// Serial.println(watch->gettime("d-m-Y, H:i:s, M"));
// delay(1);
// }
// сохраняем значения IoTItems в файл каждую секунду, если были изменения (установлены маркеры на сохранение)
// currentMillis = millis();
// if (currentMillis - prevMillis >= 1000) {
// prevMillis = millis();
// volStrForSave = "";
// for (std::list<IoTItem *>::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) {
// if ((*it)->needSave) {
// (*it)->needSave = false;
// volStrForSave = volStrForSave + (*it)->getID() + "=" + (*it)->getValue() + ";";
// }
// }
//
// if (volStrForSave != "") {
// Serial.print("volStrForSave: ");
// Serial.println(volStrForSave.c_str());
// }
//}
// File dir = FileFS.open("/", "r");
// String out;
// printDirectory(dir, out);

View File

@@ -278,7 +278,7 @@ void publishWidgets() {
DeserializationError error = deserializeJson(doc, file);
if (error) {
SerialPrint("E", F("MQTT"), error.f_str());
handleError("jse3", 1);
jsonWriteInt(errorsHeapJson, F("jse3"), 1); //Ошибка чтения json файла с виджетами при отправки в mqtt
}
JsonArray arr = doc.as<JsonArray>();
for (JsonVariant value : arr) {

View File

@@ -13,9 +13,11 @@ void ntpInit() {
if (unixTime < MIN_DATETIME) {
isTimeSynch = false;
// SerialPrint("E", "NTP", "Time not synched");
jsonWriteInt(errorsHeapJson, F("tme1"), 1);
synchTime();
return;
}
jsonWriteInt(errorsHeapJson, F("tme1"), 0);
breakEpochToTime(unixTime + jsonReadInt(settingsFlashJson, F("timezone")) * 60 * 60, _time_local);
breakEpochToTime(unixTime, _time_utc);
isTimeSynch = true;

View File

@@ -31,14 +31,6 @@ void periodicTasksInit() {
SerialPrint("i", "Task", "Periodic tasks init");
}
void handleError(String errorId, String errorValue) {
jsonWriteStr_(errorsHeapJson, errorId, errorValue);
}
void handleError(String errorId, int errorValue) {
jsonWriteInt_(errorsHeapJson, errorId, errorValue);
}
void printGlobalVarSize() {
size_t settingsFlashJsonSize = settingsFlashJson.length();
// SerialPrint(F("i"), F("settingsFlashJson"), String(settingsFlashJsonSize));

View File

@@ -134,23 +134,23 @@ void webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length)
if (headerStr == "/sgnittes|") {
writeUint8tToString(payload, length, headerLenth, settingsFlashJson);
writeFileUint8tByFrames("settings.json", payload, length, headerLenth, 256);
standWebSocket.sendTXT(num, errorsHeapJson);
sendStringToWs("errors", errorsHeapJson, num);
addThisDeviceToList();
}
//обработка кнопки сохранить настройки mqtt
if (headerStr == "/mqtt|") {
standWebSocket.sendTXT(num, settingsFlashJson); //отправляем в ответ новые полученные настройки
handleMqttStatus(false, 8); //меняем статус на неопределенный
mqttReconnect(); //начинаем переподключение
standWebSocket.sendTXT(num, errorsHeapJson); //отправляем что статус неопределен
standWebSocket.sendTXT(num, ssidListHeapJson);
sendStringToWs("settin", settingsFlashJson, num); //отправляем в ответ новые полученные настройки
handleMqttStatus(false, 8); //меняем статус на неопределенный
mqttReconnect(); //начинаем переподключение
sendStringToWs("errors", errorsHeapJson, num); //отправляем что статус неопределен
sendStringToWs("ssidli", ssidListHeapJson, num);
}
//запуск асинхронного сканирования wifi сетей при нажатии выпадающего списка
if (headerStr == "/scan|") {
RouterFind(jsonReadStr(settingsFlashJson, F("routerssid")));
standWebSocket.sendTXT(num, ssidListHeapJson);
sendStringToWs("ssidli", ssidListHeapJson, num);
}
//----------------------------------------------------------------------//
@@ -176,10 +176,14 @@ void webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length)
// Страница веб интерфейса dev
//----------------------------------------------------------------------//
if (headerStr == "/dev|") {
// standWebSocket.sendTXT(num, errorsHeapJson);
// standWebSocket.sendTXT(num, settingsFlashJson);
// sendFileToWs("/config.json", num, 1024);
// sendFileToWs("/items.json", num, 1024);
sendStringToWs("errors", errorsHeapJson, num);
sendStringToWs("settin", settingsFlashJson, num);
sendFileToWsByFrames("/config.json", "config", "", num, WEB_SOCKETS_FRAME_SIZE);
sendFileToWsByFrames("/items.json", "itemsj", "", num, WEB_SOCKETS_FRAME_SIZE);
// sendFileToWsByFrames("/layout.json", "layout", "", num, WEB_SOCKETS_FRAME_SIZE);
}
if (headerStr == "/test|") {
}
//----------------------------------------------------------------------//
@@ -216,8 +220,10 @@ void webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length)
SerialPrint("i", F("=>WS"), "Msg from svelte web, WS No: " + String(num) + ", msg: " + msg);
}
if (headerStr == "/test|") {
if (headerStr == "/tst|") {
standWebSocket.sendTXT(num, "/tstr|");
}
} break;
case WStype_BIN: {
@@ -292,7 +298,7 @@ void hexdump(const void* mem, uint32_t len, uint8_t cols = 16) {
#endif
#endif
void sendFileToWsByFrames(const String& filename, const String& header, const String& json, uint8_t client_id, size_t frameSize) {
void sendFileToWsByFrames(const String& filename, const String& header, const String& json, int client_id, size_t frameSize) {
if (header.length() != 6) {
SerialPrint("E", "FS", F("wrong header size"));
return;
@@ -305,8 +311,8 @@ void sendFileToWsByFrames(const String& filename, const String& header, const St
return;
}
// size_t totalSize = file.size();
// Serial.println("Send file '" + String(filename) + "', file size: " + String(totalSize));
size_t totalSize = file.size();
// Serial.println("Send file '" + String(filename) + "', file size: " + String(totalSize));
char buf[32];
sprintf(buf, "%04d", json.length() + 12);
@@ -346,9 +352,11 @@ void sendFileToWsByFrames(const String& filename, const String& header, const St
continuation = true;
}
// Serial.println(String(i) + ") fr sz: " + String(size) + " fin: " + String(fin) + " cnt: " + String(continuation));
// Serial.println(String(i) + ") " + "ws: " + String(client_id) + " fr sz: " + String(size) + " fin: " + String(fin) + " cnt: " + String(continuation));
if (client_id == -1) {
standWebSocket.broadcastBIN(frameBuf, size, fin, continuation);
} else {
standWebSocket.sendBIN(client_id, frameBuf, size, fin, continuation);
}

View File

@@ -318,8 +318,9 @@ String jsonWriteFloat(String& json, String name, float value, bool e) {
}
void jsonErrorDetected() {
jsonWriteInt(errorsHeapJson, F("jse2"), 1);
int number = jsonReadInt(errorsHeapJson, F("jse2n"));
number++;
jsonWriteInt(errorsHeapJson, F("jse2n"), number);
// пример как отправить ошибку с количеством
// jsonWriteInt(errorsHeapJson, F("jse2"), 1);
// int number = jsonReadInt(errorsHeapJson, F("jse2n"));
// number++;
// jsonWriteInt(errorsHeapJson, F("jse2n"), number);
}