добавил отправку прием сетевых событий

This commit is contained in:
Dmitry Borisenko
2022-02-28 01:10:14 +01:00
parent c50e0606e4
commit 28add9cb25
14 changed files with 121 additions and 118 deletions

View File

@@ -1,4 +0,0 @@
#if t22 > 10 then var = var + 1;
#if var == 1 then btn1.change();
#if var == 2 then btn2.change();
#if var == 3 then { btn3.change(); var = 0;}

View File

@@ -15,5 +15,6 @@
"mqttUser": "rise", "mqttUser": "rise",
"mqttPass": "hostel3333", "mqttPass": "hostel3333",
"serverip": "http://206.189.49.244:8081", "serverip": "http://206.189.49.244:8081",
"log": 0 "log": 0,
"mqttin": 1
} }

View File

@@ -26,8 +26,9 @@ extern FS* filesystem;
extern bool fileSystemInit(); extern bool fileSystemInit();
extern void globalVarsSync(); extern void globalVarsSync();
extern String getParamsJson();
extern void syncSettingsFlashJson(); extern void syncSettingsFlashJson();
extern void saveParamsFlashJson();
extern const String getChipId(); extern const String getChipId();
extern void setChipId(); extern void setChipId();

View File

@@ -84,8 +84,6 @@ extern WebSocketsServer standWebSocket;
**********************************************************************************************************************/ **********************************************************************************************************************/
extern String settingsFlashJson; extern String settingsFlashJson;
extern String errorsHeapJson; extern String errorsHeapJson;
extern String paramsFlashJson;
extern String paramsHeapJson;
// buf // buf
extern String orderBuf; extern String orderBuf;

View File

@@ -31,16 +31,16 @@ void spaceCmdExecute(String& cmdStr) {
} }
} }
String getValueJson(String& key) { // String getValueJson(String& key) {
String live = jsonReadStr(paramsHeapJson, key); // String live = jsonReadStr(paramsHeapJson, key);
String store = jsonReadStr(paramsFlashJson, key); // String store = jsonReadStr(paramsFlashJson, key);
if (live != nullptr) { // if (live != nullptr) {
return live; // return live;
} else if (store != nullptr) { // } else if (store != nullptr) {
return store; // return store;
} else if (store == nullptr && live == nullptr) { // } else if (store == nullptr && live == nullptr) {
return "no value"; // return "no value";
} else { // } else {
return "data error"; // return "data error";
} // }
} // }

View File

@@ -20,17 +20,20 @@ void globalVarsSync() {
jsonWriteStr_(errorsHeapJson, "errors", ""); //метка для парсинга jsonWriteStr_(errorsHeapJson, "errors", ""); //метка для парсинга
jsonWriteStr_(ssidListHeapJson, "ssid", ""); //метка для парсинга jsonWriteStr_(ssidListHeapJson, "ssid", ""); //метка для парсинга
jsonWriteStr(paramsHeapJson, "params", ""); //метка для парсинга // jsonWriteStr(paramsHeapJson, "params", ""); //метка для парсинга
}
String getParamsJson() {
String json;
serializeJson(*getLocalItemsAsJSON(), json);
jsonWriteStr_(json, "params", "");
return json;
} }
void syncSettingsFlashJson() { void syncSettingsFlashJson() {
writeFile(F("settings.json"), settingsFlashJson); writeFile(F("settings.json"), settingsFlashJson);
} }
void saveParamsFlashJson() {
writeFile(F("params.json"), paramsFlashJson);
}
const String getChipId() { const String getChipId() {
return String(ESP_getChipId()) + "-" + String(ESP_getFlashChipId()); return String(ESP_getChipId()) + "-" + String(ESP_getFlashChipId());
} }

View File

@@ -34,9 +34,6 @@ IoTGpio IoTgpio(0);
String settingsFlashJson = "{}"; //переменная в которой хранятся все настройки, находится в оперативной памяти и синхронизированна с flash памятью String settingsFlashJson = "{}"; //переменная в которой хранятся все настройки, находится в оперативной памяти и синхронизированна с flash памятью
String errorsHeapJson = "{}"; //переменная в которой хранятся все ошибки, находится в оперативной памяти только String errorsHeapJson = "{}"; //переменная в которой хранятся все ошибки, находится в оперативной памяти только
String paramsFlashJson = "{}"; //переменная в которой хранятся все параметры, находится в оперативной памяти и синхронизированна с flash памятью
String paramsHeapJson = "{}"; //переменная в которой хранятся все параметры, находится в оперативной памяти только
// buf // buf
String orderBuf = ""; String orderBuf = "";
String eventBuf = ""; String eventBuf = "";

View File

@@ -63,13 +63,14 @@ void setup() {
Serial.println("--------test end---------"); Serial.println("--------test end---------");
// симуляция добавления внешних событий // симуляция добавления внешних событий
IoTItems.push_back((IoTItem*) new externalVariable("{\"id\":\"rel1\",\"val\":10,\"int\":20}")); // IoTItems.push_back((IoTItem*)new externalVariable("{\"id\":\"rel1\",\"val\":10,\"int\":20}"));
IoTItems.push_back((IoTItem*) new externalVariable("{\"id\":\"rel4\",\"val\":34,\"int\":30}")); // IoTItems.push_back((IoTItem*)new externalVariable("{\"id\":\"rel4\",\"val\":34,\"int\":30}"));
// пример получения JSON всех Items // пример получения JSON всех Items
serializeJson(*getLocalItemsAsJSON(), Serial); Serial.println(getParamsJson());
Serial.println("");
//чтение одного параметра
// Serial.println(findIoTItem("t1")->getValue());
//тест перебора пинов из расширения //тест перебора пинов из расширения
// for (int i = 109; i < 112; i++) { // for (int i = 109; i < 112; i++) {

View File

@@ -109,7 +109,7 @@ void mqttSubscribe() {
mqtt.subscribe((mqttRootDevice + "/+/control").c_str()); mqtt.subscribe((mqttRootDevice + "/+/control").c_str());
mqtt.subscribe((mqttRootDevice + "/update").c_str()); mqtt.subscribe((mqttRootDevice + "/update").c_str());
if (jsonReadBool(settingsFlashJson, "MqttIn")) { if (jsonReadBool(settingsFlashJson, "mqttin")) {
mqtt.subscribe((mqttPrefix + "/+/+/event").c_str()); mqtt.subscribe((mqttPrefix + "/+/+/event").c_str());
mqtt.subscribe((mqttPrefix + "/+/+/order").c_str()); mqtt.subscribe((mqttPrefix + "/+/+/order").c_str());
mqtt.subscribe((mqttPrefix + "/+/+/info").c_str()); mqtt.subscribe((mqttPrefix + "/+/+/info").c_str());
@@ -145,31 +145,34 @@ void mqttCallback(char* topic, uint8_t* payload, size_t length) {
SerialPrint("i", F("=>MQTT"), "Msg from iotmanager app: " + key + " " + payloadStr); SerialPrint("i", F("=>MQTT"), "Msg from iotmanager app: " + key + " " + payloadStr);
} }
// else if (topicStr.indexOf("event") != -1) { //здесь мы получаем события с других устройств, которые потом проверяются в сценариях этого устройства
// if (!jsonReadBool(settingsFlashJson, "MqttIn")) { else if (topicStr.indexOf("event") != -1) {
// return; if (!jsonReadBool(settingsFlashJson, "mqttin")) {
// } return;
// if (topicStr.indexOf(chipId) == -1) { }
// String devId = selectFromMarkerToMarker(topicStr, "/", 2); if (topicStr.indexOf(chipId) == -1) {
// String key = selectFromMarkerToMarker(topicStr, "/", 3); String devId = selectFromMarkerToMarker(topicStr, "/", 2);
// SerialPrint("i", F("=>MQTT"), "Received event from other device: '" + devId + "' " + key + " " + payloadStr); String id = selectFromMarkerToMarker(topicStr, "/", 3);
// String event = key + " " + payloadStr + ","; //добавим событие в базу
// eventBuf += event; IoTItems.push_back((IoTItem*)new externalVariable(payloadStr));
// } //запустим проверку его в сценариях
//} generateEvent(id, payloadStr);
// SerialPrint("i", F("=>MQTT"), "Received event from other device: '" + devId + "' " + id + " " + payloadStr);
// else if (topicStr.indexOf("order") != -1) { }
// if (!jsonReadBool(settingsFlashJson, "MqttIn")) { }
// return;
// } //здесь мы получаем прямые команды которые сразу выполнятся на этом устройстве
// String devId = selectFromMarkerToMarker(topicStr, "/", 2); //необходимо для тех кто хочет управлять своим устройством из mqtt
// String key = selectFromMarkerToMarker(topicStr, "/", 3); else if (topicStr.indexOf("order") != -1) {
// SerialPrint("i", F("=>MQTT"), "Received direct order " + key + " " + payloadStr); if (!jsonReadBool(settingsFlashJson, "mqttin")) {
// String order = key + " " + payloadStr + ","; return;
// loopCmdAdd(order); }
// SerialPrint("i", "Order add", order); String devId = selectFromMarkerToMarker(topicStr, "/", 2);
//} String id = selectFromMarkerToMarker(topicStr, "/", 3);
// generateOrder(id, payloadStr);
SerialPrint("i", F("=>MQTT"), "Received direct order " + id + " " + payloadStr);
}
// else if (topicStr.indexOf("info") != -1) { // else if (topicStr.indexOf("info") != -1) {
// if (topicStr.indexOf("scen") != -1) { // if (topicStr.indexOf("scen") != -1) {
// writeFile(String(DEVICE_SCENARIO_FILE), payloadStr); // writeFile(String(DEVICE_SCENARIO_FILE), payloadStr);
@@ -260,9 +263,7 @@ void publishWidgets() {
} }
void publishState() { void publishState() {
String json = "{}"; String json = getParamsJson();
jsonMergeObjects(json, paramsHeapJson);
jsonMergeObjects(json, paramsFlashJson);
json.replace("{", ""); json.replace("{", "");
json.replace("}", ""); json.replace("}", "");
json.replace("\"", ""); json.replace("\"", "");

View File

@@ -41,21 +41,15 @@ void printGlobalVarSize() {
// SerialPrint(F("i"), F("settingsFlashJson"), String(settingsFlashJsonSize)); // SerialPrint(F("i"), F("settingsFlashJson"), String(settingsFlashJsonSize));
size_t errorsHeapJsonSize = errorsHeapJson.length(); size_t errorsHeapJsonSize = errorsHeapJson.length();
// SerialPrint(F("i"), F("errorsHeapJson"), String(errorsHeapJsonSize)); // SerialPrint(F("i"), F("errorsHeapJson"), String(errorsHeapJsonSize));
size_t paramsFlashJsonSize = paramsFlashJson.length();
// SerialPrint(F("i"), F("paramsFlashJson"), String(paramsFlashJsonSize));
size_t paramsHeapJsonSize = paramsHeapJson.length();
// SerialPrint(F("i"), F("paramsHeapJson"), String(paramsHeapJsonSize));
size_t devListHeapJsonSize = devListHeapJson.length(); size_t devListHeapJsonSize = devListHeapJson.length();
// SerialPrint(F("i"), F("devListHeapJson"), String(devListHeapJsonSize)); // SerialPrint(F("i"), F("devListHeapJson"), String(devListHeapJsonSize));
SerialPrint(F("i"), F("Var summ sz"), String(settingsFlashJsonSize + errorsHeapJsonSize + paramsFlashJsonSize + paramsHeapJsonSize + devListHeapJsonSize)); SerialPrint(F("i"), F("Var summ sz"), String(settingsFlashJsonSize + errorsHeapJsonSize + devListHeapJsonSize));
size_t halfBuffer = JSON_BUFFER_SIZE / 2; size_t halfBuffer = JSON_BUFFER_SIZE / 2;
if (settingsFlashJsonSize > halfBuffer || if (settingsFlashJsonSize > halfBuffer ||
errorsHeapJsonSize > halfBuffer || errorsHeapJsonSize > halfBuffer ||
paramsFlashJsonSize > halfBuffer ||
paramsHeapJsonSize > halfBuffer ||
devListHeapJsonSize > halfBuffer) { devListHeapJsonSize > halfBuffer) {
SerialPrint(F("EE"), F("Json"), F("Insufficient buffer size!!!")); SerialPrint(F("EE"), F("Json"), F("Insufficient buffer size!!!"));
jsonWriteInt(errorsHeapJson, "jse1", 1); jsonWriteInt(errorsHeapJson, "jse1", 1);

View File

@@ -22,7 +22,7 @@ void standWebServerInit() {
}); });
HTTP.on("/params.json", HTTP_GET, []() { HTTP.on("/params.json", HTTP_GET, []() {
HTTP.send(200, "application/json", paramsHeapJson); // HTTP.send(200, "application/json", paramsHeapJson);
}); });
HTTP.on("/errors.json", HTTP_GET, []() { HTTP.on("/errors.json", HTTP_GET, []() {

View File

@@ -51,9 +51,7 @@ 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 = "{}"; String json = getParamsJson();
jsonMergeObjects(json, paramsHeapJson);
jsonMergeObjects(json, paramsFlashJson);
standWebSocket.sendTXT(num, json); standWebSocket.sendTXT(num, json);
} }
// page configutation================================================================ // page configutation================================================================

View File

@@ -43,8 +43,10 @@ String IoTItem::getID() {
}; };
String IoTItem::getValue() { String IoTItem::getValue() {
if (value.isDecimal) return (String)value.valD; if (value.isDecimal)
else return value.valS; return (String)value.valD;
else
return value.valS;
} }
void IoTItem::loop() { void IoTItem::loop() {
@@ -58,8 +60,17 @@ void IoTItem::loop() {
void IoTItem::regEvent(String value, String consoleInfo = "") { void IoTItem::regEvent(String value, String consoleInfo = "") {
generateEvent(_id, value); generateEvent(_id, value);
jsonWriteStr(paramsHeapJson, _id, value);
publishStatusMqtt(_id, value); publishStatusMqtt(_id, value);
//отправка события другим устройствам в сети==============================
if (jsonReadBool(settingsFlashJson, "mqttin")) {
String json = "{}";
jsonWriteStr_(json, "id", _id);
jsonWriteStr_(json, "val", value);
jsonWriteInt_(json, "int", _interval + 5000); // 5 секунд про запас
publishEvent(_id, json);
SerialPrint("i", F("<=MQTT"), "Broadcast event: " + json);
}
//========================================================================
publishStatusWs(_id, value); publishStatusWs(_id, value);
SerialPrint("i", "Sensor " + consoleInfo, "'" + _id + "' data: " + value + "'"); SerialPrint("i", "Sensor " + consoleInfo, "'" + _id + "' data: " + value + "'");
} }
@@ -97,11 +108,12 @@ IoTGpio* IoTItem::getGpioDriver() {
void IoTItem::setValue(IoTValue Value) { void IoTItem::setValue(IoTValue Value) {
value = Value; value = Value;
if (value.isDecimal) regEvent(value.valD, ""); if (value.isDecimal)
else regEvent(value.valS, ""); regEvent(value.valD, "");
else
regEvent(value.valS, "");
} }
externalVariable::externalVariable(String parameters) : IoTItem(parameters) { externalVariable::externalVariable(String parameters) : IoTItem(parameters) {
prevMillis = millis(); // запоминаем текущее значение таймера для выполения doByInterval после int сек prevMillis = millis(); // запоминаем текущее значение таймера для выполения doByInterval после int сек
iAmLocal = false; // указываем, что это сущность прилетела из сети iAmLocal = false; // указываем, что это сущность прилетела из сети
@@ -116,7 +128,6 @@ void externalVariable::doByInterval() { // для данного класса
iAmDead = true; iAmDead = true;
} }
IoTItem* myIoTItem; IoTItem* myIoTItem;
IoTItem* findIoTItem(String name) { // поиск элемента модуля в существующей конфигурации IoTItem* findIoTItem(String name) { // поиск элемента модуля в существующей конфигурации

View File

@@ -44,7 +44,8 @@ class Lcd2004 : public IoTItem {
printBlankStr(_prevStrSize); printBlankStr(_prevStrSize);
String tmpStr; String tmpStr;
jsonRead(paramsHeapJson, _id2show, tmpStr); // to do
// jsonRead(paramsHeapJson, _id2show, tmpStr);
if (_descr != "none") tmpStr = _descr + " " + tmpStr; if (_descr != "none") tmpStr = _descr + " " + tmpStr;
LCDI2C->setCursor(_x, _y); LCDI2C->setCursor(_x, _y);
LCDI2C->print(tmpStr); LCDI2C->print(tmpStr);
@@ -56,20 +57,21 @@ class Lcd2004 : public IoTItem {
} }
IoTValue execute(String command, std::vector<IoTValue> &param) { // будет возможным использовать, когда сценарии запустятся IoTValue execute(String command, std::vector<IoTValue> &param) { // будет возможным использовать, когда сценарии запустятся
if (command == "noBacklight") LCDI2C->noBacklight(); if (command == "noBacklight")
else if (command == "backlight") LCDI2C->backlight(); LCDI2C->noBacklight();
else if (command == "noDisplay") LCDI2C->noDisplay(); else if (command == "backlight")
else if (command == "display") LCDI2C->display(); LCDI2C->backlight();
else if (command == "noDisplay")
LCDI2C->noDisplay();
else if (command == "display")
LCDI2C->display();
else if (command == "x") { else if (command == "x") {
_x = param[0].valD; _x = param[0].valD;
} } else if (command == "y") {
else if (command == "y") {
_y = param[0].valD; _y = param[0].valD;
} } else if (command == "descr") {
else if (command == "descr") {
_descr = param[0].valS; _descr = param[0].valS;
} } else if (command == "id2show") {
else if (command == "id2show") {
_id2show = param[0].valS; _id2show = param[0].valS;
} }