This commit is contained in:
Dmitry Borisenko
2021-12-21 22:10:35 +01:00
parent 715d20c21f
commit 70add780bd
71 changed files with 972 additions and 9927 deletions

View File

@@ -0,0 +1,4 @@
#include "Class/TCircularBuffer.h"
TCircularBuffer<char *, 1024> *myTCircularBuffer;
TCircularBuffer<char *, 20480> *myWsBuffer;

View File

@@ -18,6 +18,7 @@ AsyncWebServer server(80);
boolean just_load = true;
boolean telegramInitBeen = false;
boolean savedFromWeb = false;
boolean wsSetupFlag = false;
// Json
String configSetupJson = "{}";
@@ -43,8 +44,13 @@ int mqttConnectAttempts = 0;
bool changeBroker = false;
int currentBroker = 1;
// web sockets
int wsAttempts = 100;
//char* wsBufChar = "";
// orders and events
String orderBuf = "";
String wsBuf = "";
String eventBuf = "";
String mysensorBuf = "";
String itemsFile = "";

View File

@@ -75,8 +75,8 @@ void deviceInit() {
}
savedFromWeb = false;
//publishWidgets();
//publishState();
// publishWidgets();
// publishState();
}
void loadScenario() {

View File

@@ -180,14 +180,14 @@ boolean mqttConnect() {
void mqttCallback(char* topic, uint8_t* payload, size_t length) {
String topicStr = String(topic);
//SerialPrint("I", "=>MQTT", topicStr);
// SerialPrint("I", "=>MQTT", topicStr);
String payloadStr;
payloadStr.reserve(length + 1);
for (size_t i = 0; i < length; i++) {
payloadStr += (char)payload[i];
}
//SerialPrint("I", "=>MQTT", payloadStr);
// SerialPrint("I", "=>MQTT", payloadStr);
if (payloadStr.startsWith("HELLO")) {
SerialPrint("I", F("MQTT"), F("Full update"));
@@ -321,8 +321,8 @@ void publishWidgets() {
line = all_widgets.substring(psn_1, psn_2);
line.replace("\n", "");
line.replace("\r\n", "");
//jsonWriteStr(line, "id", String(counter));
//jsonWriteStr(line, "pageId", String(counter));
// jsonWriteStr(line, "id", String(counter));
// jsonWriteStr(line, "pageId", String(counter));
counter++;
sendMQTT("config", line);
Serial.println("[V] " + line);

View File

@@ -1,6 +1,7 @@
#include "Tests.h"
#include "BufferExecute.h"
#include "Class/TCircularBuffer.h"
#include "Global.h"
#include "ItemsList.h"
#include "Macro.h"
@@ -8,31 +9,51 @@
#include "Utils/StringUtils.h"
void testsPerform() {
//Serial.println("====some tests section====");
////===========================================================================
//String str = "0;1;2;3;4";
//char* mychar = new char[str.length() + 1];
//strcpy(mychar, str.c_str());
//test(mychar);
////===========================================================================
//String myJson;
//const int capacity = JSON_ARRAY_SIZE(2) + 3 * JSON_OBJECT_SIZE(3);
//StaticJsonBuffer<capacity> jb;
//JsonArray& arr = jb.createArray();
//JsonObject& obj1 = jb.createObject();
//obj1["test1"] = 1;
//obj1["test2"] = 2;
//obj1["test3"] = 3;
//arr.add(obj1);
//arr.printTo(myJson);
//Serial.println(myJson);
Serial.println("====some tests section====");
//ТЕСТ КОЛЬЦЕВОГО БУФЕРА=============================================================================
myTCircularBuffer = new TCircularBuffer<char*, 1024>;
char* buf = "text";
for (int i = 1; i <= 5; i++) {
myTCircularBuffer->push(buf);
}
char* item;
while (myTCircularBuffer->pop(item)) {
Serial.println(item);
}
//===================================================================================================
// String str = "0;1;2;3;4";
// char* mychar = new char[str.length() + 1];
// strcpy(mychar, str.c_str());
// test(mychar);
//===========================================================================
// String myJson;
// const int capacity = JSON_ARRAY_SIZE(2) + 3 * JSON_OBJECT_SIZE(3);
// StaticJsonBuffer<capacity> jb;
// JsonArray& arr = jb.createArray();
// JsonObject& obj1 = jb.createObject();
// obj1["test1"] = 1;
// obj1["test2"] = 2;
// obj1["test3"] = 3;
// arr.add(obj1);
// arr.printTo(myJson);
// Serial.println(myJson);
//
//
//
////===========================================================================
////Serial.println(isDigitDotCommaStr("-12552.5555"));
////String str = "Geeks for Geeks ";
////Serial.println(itemsCount2(str, " "));
//===========================================================================
// Serial.println(isDigitDotCommaStr("-12552.5555"));
// String str = "Geeks for Geeks ";
// Serial.println(itemsCount2(str, " "));
//
//Serial.println("==========end============");
Serial.println("==========end============");
}
void testLoop() {
// char* item;
// myCircularBuffer->pop(item);
// Serial.println(item);
}

View File

@@ -2,11 +2,10 @@
#include "Global.h"
#include "WebServer.h"
#include "WebSocket.h"
void SerialPrint(String errorLevel, String module, String msg) {
String tosend = prettyMillis(millis()) + " [" + errorLevel + "] [" + module + "] " + msg;
Serial.println(tosend);
// mqttRootDevice +
ws.textAll("/core/" + tosend);
// wsPublishData(F("log"), tosend);
}

View File

@@ -1,4 +1,5 @@
#include "Web.h"
#include "BufferExecute.h"
#include "Class/NotAsync.h"
#include "Global.h"
@@ -174,7 +175,7 @@ void web_init() {
}
//==============================mqtt settings=============================================
//primary
// primary
if (request->hasArg(F("mqttServer"))) {
jsonWriteStr(configSetupJson, F("mqttServer"), request->getParam(F("mqttServer"))->value());
saveConfig();
@@ -206,7 +207,7 @@ void web_init() {
myNotAsyncActions->make(do_MQTTPARAMSCHANGED);
request->send(200);
}
//secondary
// secondary
if (request->hasArg(F("mqttServer2"))) {
jsonWriteStr(configSetupJson, F("mqttServer2"), request->getParam(F("mqttServer2"))->value());
saveConfig();
@@ -240,7 +241,7 @@ void web_init() {
}
if (request->hasArg("mqttsend")) {
//myNotAsyncActions->make(do_MQTTUDP);
// myNotAsyncActions->make(do_MQTTUDP);
request->send(200);
}
@@ -336,7 +337,7 @@ void web_init() {
serverIP = jsonReadStr(configSetupJson, "serverip");
request->send(200);
}
//set?order=button_1
// set?order=button_1
if (request->hasArg("order")) {
String order = request->getParam("order")->value();
order.replace("_", " ");
@@ -351,7 +352,7 @@ void web_init() {
request->send(200);
}
//gate mode
// gate mode
if (request->hasArg("gateAuto")) {
bool value = request->getParam("gateAuto")->value().toInt();
@@ -359,19 +360,18 @@ void web_init() {
saveConfig();
request->send(200);
}
});
//server.on("/del", HTTP_GET, [](AsyncWebServerRequest* request) {
// if (request->hasArg("file") && request->hasArg("line")) {
// String fileName = request->getParam("file")->value();
// Serial.println(fileName);
// int line = request->getParam("line")->value().toInt();
// Serial.println(line);
// myNotAsyncActions->make(do_delChoosingItems);
// request->redirect(F("/?set.device"));
// }
//});
// server.on("/del", HTTP_GET, [](AsyncWebServerRequest* request) {
// if (request->hasArg("file") && request->hasArg("line")) {
// String fileName = request->getParam("file")->value();
// Serial.println(fileName);
// int line = request->getParam("line")->value().toInt();
// Serial.println(line);
// myNotAsyncActions->make(do_delChoosingItems);
// request->redirect(F("/?set.device"));
// }
// });
server.on("/check", HTTP_GET, [](AsyncWebServerRequest* request) {
myNotAsyncActions->make(do_GETLASTVERSION);
@@ -402,8 +402,8 @@ void web_init() {
});
/*
* Upgrade
*/
* Upgrade
*/
server.on("/upgrade", HTTP_GET, [](AsyncWebServerRequest* request) {
myNotAsyncActions->make(do_UPGRADE);
request->send(200, "text/html");

View File

@@ -1,9 +1,11 @@
#include "WebServer.h"
#include "BufferExecute.h"
#include "Class/NotAsync.h"
#include "FSEditor.h"
#include "Utils/FileUtils.h"
#include "Utils/WebUtils.h"
#include "WebSocket.h"
AsyncWebSocket ws("/ws");
AsyncEventSource events("/events");
@@ -17,6 +19,12 @@ void HttpServerinit() {
server.addHandler(new FSEditor(login, pass));
#endif
//#ifdef CORS_DEBUG
DefaultHeaders::Instance().addHeader(F("Access-Control-Allow-Origin"), F("*"));
DefaultHeaders::Instance().addHeader(F("Access-Control-Allow-Headers"), F("content-type"));
//#endif
// server.sendHeader("Access-Control-Allow-Origin", "*");
server.serveStatic("/css/", FileFS, "/css/").setCacheControl("max-age=600");
server.serveStatic("/js/", FileFS, "/js/").setCacheControl("max-age=600");
server.serveStatic("/favicon.ico", FileFS, "/favicon.ico").setCacheControl("max-age=600");
@@ -29,9 +37,17 @@ void HttpServerinit() {
server.serveStatic("/", FileFS, "/").setDefaultFile("index.htm").setAuthentication(login.c_str(), pass.c_str());
#endif
//server.onNotFound([](AsyncWebServerRequest *request) {
// SerialPrint("[E]", "WebServer", "not found:\n" + getRequestInfo(request));
// request->send(404);
//});
server.onNotFound([](AsyncWebServerRequest *request) {
SerialPrint("[E]", "WebServer", "not found:\n" + getRequestInfo(request));
request->send(404);
if (request->method() == HTTP_OPTIONS) {
request->send(200);
} else {
request->send(404);
}
});
server.onFileUpload([](AsyncWebServerRequest *request, const String &filename, size_t index, uint8_t *data, size_t len, bool final) {
@@ -44,6 +60,11 @@ void HttpServerinit() {
}
});
server.on("/file.json", HTTP_GET, [](AsyncWebServerRequest *request) {
String file = readFile("file.json", 1024);
request->send(200, "application/json", file);
});
// динамические данные
server.on("/config.live.json", HTTP_GET, [](AsyncWebServerRequest *request) {
request->send(200, "application/json", configLiveJson);
@@ -112,13 +133,9 @@ void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventTyp
}
Serial.printf("%s\n", msg.c_str());
if (msg.startsWith("config")) {
SerialPrint("I", F("WS"), F("config send"));
sendEspSetupToWS();
// publishWidgetsWS();
// publishStateWS();
// choose_log_date_and_send(); // функцию выгрузки архива с графиком я не сделал. Забираю при выгрузке по MQTT
if (msg.startsWith("/config")) {
// myNotAsyncActions->make(do_webSocketSendSetup);
// wsSetupFlag = true;
}
if (info->opcode == WS_TEXT) {
@@ -211,18 +228,3 @@ void HttpServerinitWS() {
server.addHandler(&events);
#endif
}
//===========web sockets==============================
void sendEspSetupToWS() {
File file = seekFile("/setup.json");
DynamicJsonDocument doc(1024);
file.find("[");
do {
deserializeJson(doc, file);
// Serial.println(doc.as<String>());
ws.textAll(doc.as<String>());
} while (file.findUntil(",", "]"));
}

135
src/WebSocket.cpp Normal file
View File

@@ -0,0 +1,135 @@
#include "WebSocket.h"
#include "ArduinoJson.h"
#include "Class/NotAsync.h"
#include "Class/TCircularBuffer.h"
#include "Global.h"
void wsInit() {
// myWsBuffer = new TCircularBuffer<char*, 20480>;
// myNotAsyncActions->add(
// do_webSocketSendSetup, [&](void*) {
// delay(100);
// wsSendSetup();
// },
// nullptr);
}
void wsPublishData(String topic, String data) {
if (ws.enabled()) {
if (ws.availableForWriteAll()) {
data = "[" + topic + "]" + data;
ws.textAll(data);
}
}
}
//отправка setup массива в sockets способом через буфер string, рабочий способ но буфер стринг - плохой метод
void wsSendSetup3() {
File file = seekFile("/setup.json");
DynamicJsonDocument doc(2048);
int i = 0;
file.find("[");
SerialPrint("I", F("WS"), F("start send config"));
do {
i++;
deserializeJson(doc, file);
wsBuf += doc.as<String>() + "\n";
} while (file.findUntil(",", "]"));
SerialPrint("I", F("WS"), F("completed send config"));
}
void loopWsExecute3() {
static int attampts = wsAttempts;
if (wsBuf.length()) {
if (attampts > 0) {
if (ws.availableForWriteAll()) {
String tmp = selectToMarker(wsBuf, "\n");
wsPublishData("config", tmp);
wsBuf = deleteBeforeDelimiter(wsBuf, "\n");
attampts = wsAttempts;
} else {
attampts--;
SerialPrint("I", F("WS"), String(attampts));
}
} else {
SerialPrint("I", F("WS"), F("socket fatal error"));
attampts = wsAttempts;
}
}
}
//отправка setup массива в sockets способом через кольцевой буфер char
// void wsSendSetup() {
// File file = seekFile("/setup.json");
// DynamicJsonDocument doc(2048);
// int i = 0;
// file.find("[");
// SerialPrint("I", F("WS"), F("start send config"));
// do {
// i++;
// deserializeJson(doc, file);
// char* element;
// char* element = new char[1024];
// serializeJson(doc, (char*)element, 1024);
// Serial.println(element);
//
// } while (file.findUntil(",", "]"));
// SerialPrint("I", F("WS"), F("completed send config"));
//
// char* itemsend = "element";
// myWsBuffer->push(itemsend);
//
// char* item;
// while (myWsBuffer->pop(item)) {
// Serial.println(item);
// }
//}
// void loopWsExecute() {
// char* item;
// if (myWsBuffer->pop(item)) {
// Serial.println(item);
// }
// }
//отправка setup массива в sockets способом прямой загрузки в ws buffer
// void wsSendSetupBuffer() {
// File file = seekFile("/setup.json");
// DynamicJsonDocument doc(2048);
// int i = 0;
// file.find("[");
// SerialPrint("I", F("WS"), F("start send config"));
// do {
// i++;
// deserializeJson(doc, file);
// size_t len = measureJson(doc);
// AsyncWebSocketMessageBuffer* buffer = ws.makeBuffer(len);
// if (buffer) {
// serializeJson(doc, (char*)buffer->get(), len);
// if (ws.enabled()) {
// if (ws.availableForWriteAll()) {
// ws.textAll(buffer);
// }
// }
// }
// // Serial.println(doc.as<String>());
// } while (file.findUntil(",", "]"));
// SerialPrint("I", F("WS"), F("completed send config"));
//}
//Пример прямого доступа к web socket buffer переделанный для arduino json 6
// void sendDataWs() {
// DynamicJsonDocument doc(1024);
// doc["a"] = "abc";
// doc["b"] = "abcd";
// doc["c"] = "abcde";
// doc["d"] = "abcdef";
// doc["e"] = "abcdefg";
// size_t len = measureJson(doc);
// AsyncWebSocketMessageBuffer* buffer = ws.makeBuffer(len);
// if (buffer) {
// serializeJson(doc, (char*)buffer->get(), len);
// ws.textAll(buffer);
// }
//}

View File

@@ -20,6 +20,7 @@
#include "Utils/Timings.h"
#include "Utils/WebUtils.h"
#include "WebServer.h"
#include "WebSocket.h"
#include "items/ButtonInClass.h"
#include "items/vCountDown.h"
#include "items/vImpulsOut.h"
@@ -52,6 +53,8 @@ void setup() {
myNotAsyncActions = new NotAsync(do_LAST);
myScenario = new Scenario();
wsInit();
//=========================================initialisation==============================================================
setChipId();
fileSystemInit();
@@ -84,7 +87,7 @@ void setup() {
getFSInfo();
// testsPerform();
testsPerform();
just_load = false;
initialized = true;
@@ -100,8 +103,6 @@ void setup() {
// setupESP();
sendEspSetupToWS();
SerialPrint("I", F("System"), F("✔ Initialization completed"));
}
@@ -109,6 +110,16 @@ void loop() {
if (!initialized) {
return;
}
testLoop();
// if (wsSetupFlag) {
// wsSetupFlag = false;
// wsSendSetup();
//}
// loopWsExecute();
#ifdef OTA_UPDATES_ENABLED
ArduinoOTA.handle();
#endif