mirror of
https://github.com/IoTManagerProject/IoTManager.git
synced 2026-03-26 22:22:16 +03:00
добавил отправку прием сетевых событий
This commit is contained in:
@@ -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;}
|
||||
@@ -15,5 +15,6 @@
|
||||
"mqttUser": "rise",
|
||||
"mqttPass": "hostel3333",
|
||||
"serverip": "http://206.189.49.244:8081",
|
||||
"log": 0
|
||||
"log": 0,
|
||||
"mqttin": 1
|
||||
}
|
||||
@@ -26,8 +26,9 @@ extern FS* filesystem;
|
||||
extern bool fileSystemInit();
|
||||
extern void globalVarsSync();
|
||||
|
||||
extern String getParamsJson();
|
||||
|
||||
extern void syncSettingsFlashJson();
|
||||
extern void saveParamsFlashJson();
|
||||
|
||||
extern const String getChipId();
|
||||
extern void setChipId();
|
||||
|
||||
@@ -84,8 +84,6 @@ extern WebSocketsServer standWebSocket;
|
||||
**********************************************************************************************************************/
|
||||
extern String settingsFlashJson;
|
||||
extern String errorsHeapJson;
|
||||
extern String paramsFlashJson;
|
||||
extern String paramsHeapJson;
|
||||
|
||||
// buf
|
||||
extern String orderBuf;
|
||||
|
||||
@@ -31,16 +31,16 @@ void spaceCmdExecute(String& cmdStr) {
|
||||
}
|
||||
}
|
||||
|
||||
String getValueJson(String& key) {
|
||||
String live = jsonReadStr(paramsHeapJson, key);
|
||||
String store = jsonReadStr(paramsFlashJson, key);
|
||||
if (live != nullptr) {
|
||||
return live;
|
||||
} else if (store != nullptr) {
|
||||
return store;
|
||||
} else if (store == nullptr && live == nullptr) {
|
||||
return "no value";
|
||||
} else {
|
||||
return "data error";
|
||||
}
|
||||
}
|
||||
// String getValueJson(String& key) {
|
||||
// String live = jsonReadStr(paramsHeapJson, key);
|
||||
// String store = jsonReadStr(paramsFlashJson, key);
|
||||
// if (live != nullptr) {
|
||||
// return live;
|
||||
// } else if (store != nullptr) {
|
||||
// return store;
|
||||
// } else if (store == nullptr && live == nullptr) {
|
||||
// return "no value";
|
||||
// } else {
|
||||
// return "data error";
|
||||
// }
|
||||
// }
|
||||
|
||||
@@ -20,17 +20,20 @@ void globalVarsSync() {
|
||||
|
||||
jsonWriteStr_(errorsHeapJson, "errors", ""); //метка для парсинга
|
||||
jsonWriteStr_(ssidListHeapJson, "ssid", ""); //метка для парсинга
|
||||
jsonWriteStr(paramsHeapJson, "params", ""); //метка для парсинга
|
||||
// jsonWriteStr(paramsHeapJson, "params", ""); //метка для парсинга
|
||||
}
|
||||
|
||||
String getParamsJson() {
|
||||
String json;
|
||||
serializeJson(*getLocalItemsAsJSON(), json);
|
||||
jsonWriteStr_(json, "params", "");
|
||||
return json;
|
||||
}
|
||||
|
||||
void syncSettingsFlashJson() {
|
||||
writeFile(F("settings.json"), settingsFlashJson);
|
||||
}
|
||||
|
||||
void saveParamsFlashJson() {
|
||||
writeFile(F("params.json"), paramsFlashJson);
|
||||
}
|
||||
|
||||
const String getChipId() {
|
||||
return String(ESP_getChipId()) + "-" + String(ESP_getFlashChipId());
|
||||
}
|
||||
|
||||
@@ -34,9 +34,6 @@ IoTGpio IoTgpio(0);
|
||||
String settingsFlashJson = "{}"; //переменная в которой хранятся все настройки, находится в оперативной памяти и синхронизированна с flash памятью
|
||||
String errorsHeapJson = "{}"; //переменная в которой хранятся все ошибки, находится в оперативной памяти только
|
||||
|
||||
String paramsFlashJson = "{}"; //переменная в которой хранятся все параметры, находится в оперативной памяти и синхронизированна с flash памятью
|
||||
String paramsHeapJson = "{}"; //переменная в которой хранятся все параметры, находится в оперативной памяти только
|
||||
|
||||
// buf
|
||||
String orderBuf = "";
|
||||
String eventBuf = "";
|
||||
|
||||
15
src/Main.cpp
15
src/Main.cpp
@@ -56,20 +56,21 @@ void setup() {
|
||||
|
||||
//загрузка сценария
|
||||
iotScen.loadScenario("/scenario.txt");
|
||||
//iotScen.ExecScenario("");
|
||||
// iotScen.ExecScenario("");
|
||||
|
||||
// test
|
||||
Serial.println("-------test start--------");
|
||||
Serial.println("--------test end---------");
|
||||
|
||||
// симуляция добавления внешних событий
|
||||
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\":\"rel1\",\"val\":10,\"int\":20}"));
|
||||
// IoTItems.push_back((IoTItem*)new externalVariable("{\"id\":\"rel4\",\"val\":34,\"int\":30}"));
|
||||
|
||||
// пример получения JSON всех Items
|
||||
serializeJson(*getLocalItemsAsJSON(), Serial);
|
||||
Serial.println("");
|
||||
Serial.println(getParamsJson());
|
||||
|
||||
//чтение одного параметра
|
||||
// Serial.println(findIoTItem("t1")->getValue());
|
||||
|
||||
//тест перебора пинов из расширения
|
||||
// for (int i = 109; i < 112; i++) {
|
||||
@@ -104,7 +105,7 @@ void loop() {
|
||||
mqttLoop();
|
||||
|
||||
// передаем управление каждому элементу конфигурации для выполнения своих функций
|
||||
for (std::list<IoTItem*>::iterator it=IoTItems.begin(); it != IoTItems.end(); ++it) {
|
||||
for (std::list<IoTItem*>::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) {
|
||||
(*it)->loop();
|
||||
if ((*it)->iAmDead) {
|
||||
delete *it;
|
||||
|
||||
@@ -109,7 +109,7 @@ void mqttSubscribe() {
|
||||
mqtt.subscribe((mqttRootDevice + "/+/control").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 + "/+/+/order").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);
|
||||
}
|
||||
|
||||
// else if (topicStr.indexOf("event") != -1) {
|
||||
// if (!jsonReadBool(settingsFlashJson, "MqttIn")) {
|
||||
// return;
|
||||
// }
|
||||
// if (topicStr.indexOf(chipId) == -1) {
|
||||
// String devId = selectFromMarkerToMarker(topicStr, "/", 2);
|
||||
// String key = selectFromMarkerToMarker(topicStr, "/", 3);
|
||||
// SerialPrint("i", F("=>MQTT"), "Received event from other device: '" + devId + "' " + key + " " + payloadStr);
|
||||
// String event = key + " " + payloadStr + ",";
|
||||
// eventBuf += event;
|
||||
// }
|
||||
//}
|
||||
//
|
||||
// else if (topicStr.indexOf("order") != -1) {
|
||||
// if (!jsonReadBool(settingsFlashJson, "MqttIn")) {
|
||||
// return;
|
||||
// }
|
||||
// String devId = selectFromMarkerToMarker(topicStr, "/", 2);
|
||||
// String key = selectFromMarkerToMarker(topicStr, "/", 3);
|
||||
// SerialPrint("i", F("=>MQTT"), "Received direct order " + key + " " + payloadStr);
|
||||
// String order = key + " " + payloadStr + ",";
|
||||
// loopCmdAdd(order);
|
||||
// SerialPrint("i", "Order add", order);
|
||||
//}
|
||||
//
|
||||
//здесь мы получаем события с других устройств, которые потом проверяются в сценариях этого устройства
|
||||
else if (topicStr.indexOf("event") != -1) {
|
||||
if (!jsonReadBool(settingsFlashJson, "mqttin")) {
|
||||
return;
|
||||
}
|
||||
if (topicStr.indexOf(chipId) == -1) {
|
||||
String devId = selectFromMarkerToMarker(topicStr, "/", 2);
|
||||
String id = selectFromMarkerToMarker(topicStr, "/", 3);
|
||||
//добавим событие в базу
|
||||
IoTItems.push_back((IoTItem*)new externalVariable(payloadStr));
|
||||
//запустим проверку его в сценариях
|
||||
generateEvent(id, payloadStr);
|
||||
SerialPrint("i", F("=>MQTT"), "Received event from other device: '" + devId + "' " + id + " " + payloadStr);
|
||||
}
|
||||
}
|
||||
|
||||
//здесь мы получаем прямые команды которые сразу выполнятся на этом устройстве
|
||||
//необходимо для тех кто хочет управлять своим устройством из mqtt
|
||||
else if (topicStr.indexOf("order") != -1) {
|
||||
if (!jsonReadBool(settingsFlashJson, "mqttin")) {
|
||||
return;
|
||||
}
|
||||
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) {
|
||||
// if (topicStr.indexOf("scen") != -1) {
|
||||
// writeFile(String(DEVICE_SCENARIO_FILE), payloadStr);
|
||||
@@ -260,9 +263,7 @@ void publishWidgets() {
|
||||
}
|
||||
|
||||
void publishState() {
|
||||
String json = "{}";
|
||||
jsonMergeObjects(json, paramsHeapJson);
|
||||
jsonMergeObjects(json, paramsFlashJson);
|
||||
String json = getParamsJson();
|
||||
json.replace("{", "");
|
||||
json.replace("}", "");
|
||||
json.replace("\"", "");
|
||||
|
||||
@@ -41,21 +41,15 @@ void printGlobalVarSize() {
|
||||
// SerialPrint(F("i"), F("settingsFlashJson"), String(settingsFlashJsonSize));
|
||||
size_t errorsHeapJsonSize = errorsHeapJson.length();
|
||||
// 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();
|
||||
// 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;
|
||||
|
||||
if (settingsFlashJsonSize > halfBuffer ||
|
||||
errorsHeapJsonSize > halfBuffer ||
|
||||
paramsFlashJsonSize > halfBuffer ||
|
||||
paramsHeapJsonSize > halfBuffer ||
|
||||
devListHeapJsonSize > halfBuffer) {
|
||||
SerialPrint(F("EE"), F("Json"), F("Insufficient buffer size!!!"));
|
||||
jsonWriteInt(errorsHeapJson, "jse1", 1);
|
||||
|
||||
@@ -22,7 +22,7 @@ void standWebServerInit() {
|
||||
});
|
||||
|
||||
HTTP.on("/params.json", HTTP_GET, []() {
|
||||
HTTP.send(200, "application/json", paramsHeapJson);
|
||||
// HTTP.send(200, "application/json", paramsHeapJson);
|
||||
});
|
||||
|
||||
HTTP.on("/errors.json", HTTP_GET, []() {
|
||||
|
||||
@@ -51,9 +51,7 @@ void webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length)
|
||||
//**отправка**//
|
||||
if (headerStr == "/|") {
|
||||
sendFileToWs("/layout.json", num, 1024);
|
||||
String json = "{}";
|
||||
jsonMergeObjects(json, paramsHeapJson);
|
||||
jsonMergeObjects(json, paramsFlashJson);
|
||||
String json = getParamsJson();
|
||||
standWebSocket.sendTXT(num, json);
|
||||
}
|
||||
// page configutation================================================================
|
||||
|
||||
@@ -16,7 +16,7 @@ IoTItem::IoTItem(String parameters) {
|
||||
jsonRead(parameters, F("round"), _round, false);
|
||||
|
||||
String valAsStr;
|
||||
if (jsonRead(parameters, F("val"), valAsStr, false)) // значение переменной или датчика при инициализации если есть в конфигурации
|
||||
if (jsonRead(parameters, F("val"), valAsStr, false)) // значение переменной или датчика при инициализации если есть в конфигурации
|
||||
if (value.isDecimal = isDigitDotCommaStr(valAsStr))
|
||||
value.valD = valAsStr.toFloat();
|
||||
else
|
||||
@@ -43,8 +43,10 @@ String IoTItem::getID() {
|
||||
};
|
||||
|
||||
String IoTItem::getValue() {
|
||||
if (value.isDecimal) return (String)value.valD;
|
||||
else return value.valS;
|
||||
if (value.isDecimal)
|
||||
return (String)value.valD;
|
||||
else
|
||||
return value.valS;
|
||||
}
|
||||
|
||||
void IoTItem::loop() {
|
||||
@@ -58,8 +60,17 @@ void IoTItem::loop() {
|
||||
|
||||
void IoTItem::regEvent(String value, String consoleInfo = "") {
|
||||
generateEvent(_id, value);
|
||||
jsonWriteStr(paramsHeapJson, _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);
|
||||
SerialPrint("i", "Sensor " + consoleInfo, "'" + _id + "' data: " + value + "'");
|
||||
}
|
||||
@@ -97,14 +108,15 @@ IoTGpio* IoTItem::getGpioDriver() {
|
||||
|
||||
void IoTItem::setValue(IoTValue Value) {
|
||||
value = Value;
|
||||
if (value.isDecimal) regEvent(value.valD, "");
|
||||
else regEvent(value.valS, "");
|
||||
if (value.isDecimal)
|
||||
regEvent(value.valD, "");
|
||||
else
|
||||
regEvent(value.valS, "");
|
||||
}
|
||||
|
||||
|
||||
externalVariable::externalVariable(String parameters) : IoTItem(parameters) {
|
||||
prevMillis = millis(); // запоминаем текущее значение таймера для выполения doByInterval после int сек
|
||||
iAmLocal = false; // указываем, что это сущность прилетела из сети
|
||||
iAmLocal = false; // указываем, что это сущность прилетела из сети
|
||||
Serial.printf("Call from externalVariable: parameters %s %d\n", parameters.c_str(), _interval);
|
||||
}
|
||||
|
||||
@@ -112,15 +124,14 @@ externalVariable::~externalVariable() {
|
||||
Serial.printf("Call from ~externalVariable: Im dead\n");
|
||||
}
|
||||
|
||||
void externalVariable::doByInterval() { // для данного класса doByInterval+int выполняет роль счетчика обратного отсчета до уничтожения
|
||||
void externalVariable::doByInterval() { // для данного класса doByInterval+int выполняет роль счетчика обратного отсчета до уничтожения
|
||||
iAmDead = true;
|
||||
}
|
||||
|
||||
|
||||
IoTItem* myIoTItem;
|
||||
|
||||
IoTItem* findIoTItem(String name) { // поиск элемента модуля в существующей конфигурации
|
||||
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() == name) return *it;
|
||||
}
|
||||
|
||||
@@ -129,9 +140,9 @@ IoTItem* findIoTItem(String name) { // поиск элемента модуля
|
||||
|
||||
StaticJsonDocument<JSON_BUFFER_SIZE> docForExport;
|
||||
|
||||
StaticJsonDocument<JSON_BUFFER_SIZE>* getLocalItemsAsJSON () {
|
||||
StaticJsonDocument<JSON_BUFFER_SIZE>* getLocalItemsAsJSON() {
|
||||
docForExport.clear();
|
||||
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)->iAmLocal) docForExport[(*it)->getID()] = (*it)->getValue();
|
||||
}
|
||||
|
||||
|
||||
@@ -15,80 +15,82 @@ class Lcd2004 : public IoTItem {
|
||||
int _prevStrSize;
|
||||
|
||||
public:
|
||||
Lcd2004(String parameters): IoTItem(parameters) {
|
||||
Lcd2004(String parameters) : IoTItem(parameters) {
|
||||
String addr, size, xy;
|
||||
_prevStrSize = 0;
|
||||
|
||||
|
||||
jsonRead(parameters, "addr", addr);
|
||||
jsonRead(parameters, "size", size);
|
||||
int w = selectFromMarkerToMarker(size, ",", 0).toInt(); //количество столбцов
|
||||
int h = selectFromMarkerToMarker(size, ",", 1).toInt(); //количество строк
|
||||
if (LCDI2C == nullptr) { //инициализации экрана еще не было
|
||||
if (LCDI2C == nullptr) { //инициализации экрана еще не было
|
||||
LCDI2C = new LiquidCrystal_I2C(hexStringToUint8(addr), w, h);
|
||||
if(LCDI2C != nullptr) {
|
||||
if (LCDI2C != nullptr) {
|
||||
LCDI2C->init();
|
||||
LCDI2C->backlight();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
jsonRead(parameters, "coord", xy);
|
||||
_x = selectFromMarkerToMarker(xy, ",", 0).toInt();
|
||||
_y = selectFromMarkerToMarker(xy, ",", 1).toInt();
|
||||
_y = selectFromMarkerToMarker(xy, ",", 1).toInt();
|
||||
|
||||
jsonRead(parameters, "descr", _descr);
|
||||
jsonRead(parameters, "id2show", _id2show);
|
||||
}
|
||||
|
||||
|
||||
void doByInterval() {
|
||||
if (LCDI2C != nullptr) {
|
||||
printBlankStr(_prevStrSize);
|
||||
|
||||
String tmpStr;
|
||||
jsonRead(paramsHeapJson, _id2show, tmpStr);
|
||||
if (_descr != "none") tmpStr = _descr + " " + tmpStr;
|
||||
// to do
|
||||
// jsonRead(paramsHeapJson, _id2show, tmpStr);
|
||||
if (_descr != "none") tmpStr = _descr + " " + tmpStr;
|
||||
LCDI2C->setCursor(_x, _y);
|
||||
LCDI2C->print(tmpStr);
|
||||
LCDI2C->print(tmpStr);
|
||||
|
||||
// LCDI2C->print("Helloy,Manager 404 !");
|
||||
// LCDI2C->print("Helloy,Manager 404 !");
|
||||
|
||||
_prevStrSize = tmpStr.length();
|
||||
}
|
||||
}
|
||||
|
||||
IoTValue execute(String command, std::vector<IoTValue> ¶m) { // будет возможным использовать, когда сценарии запустятся
|
||||
if (command == "noBacklight") LCDI2C->noBacklight();
|
||||
else if (command == "backlight") LCDI2C->backlight();
|
||||
else if (command == "noDisplay") LCDI2C->noDisplay();
|
||||
else if (command == "display") LCDI2C->display();
|
||||
IoTValue execute(String command, std::vector<IoTValue> ¶m) { // будет возможным использовать, когда сценарии запустятся
|
||||
if (command == "noBacklight")
|
||||
LCDI2C->noBacklight();
|
||||
else if (command == "backlight")
|
||||
LCDI2C->backlight();
|
||||
else if (command == "noDisplay")
|
||||
LCDI2C->noDisplay();
|
||||
else if (command == "display")
|
||||
LCDI2C->display();
|
||||
else if (command == "x") {
|
||||
_x = param[0].valD;
|
||||
}
|
||||
else if (command == "y") {
|
||||
} else if (command == "y") {
|
||||
_y = param[0].valD;
|
||||
}
|
||||
else if (command == "descr") {
|
||||
} else if (command == "descr") {
|
||||
_descr = param[0].valS;
|
||||
}
|
||||
else if (command == "id2show") {
|
||||
} else if (command == "id2show") {
|
||||
_id2show = param[0].valS;
|
||||
}
|
||||
|
||||
doByInterval();
|
||||
doByInterval();
|
||||
return {};
|
||||
}
|
||||
|
||||
//печать пустой строки нужной длинны для затирания предыдущего значения на экране
|
||||
void printBlankStr(int strSize){
|
||||
void printBlankStr(int strSize) {
|
||||
String tmpStr = "";
|
||||
for(int i=0; i<strSize; i++) tmpStr += " ";
|
||||
LCDI2C->setCursor(_x, _y);
|
||||
for (int i = 0; i < strSize; i++) tmpStr += " ";
|
||||
LCDI2C->setCursor(_x, _y);
|
||||
LCDI2C->print(tmpStr);
|
||||
}
|
||||
|
||||
~Lcd2004() {};
|
||||
|
||||
~Lcd2004(){};
|
||||
};
|
||||
|
||||
void* getAPI_Lcd2004(String subtype, String param) {
|
||||
void *getAPI_Lcd2004(String subtype, String param) {
|
||||
if (subtype == F("Lcd2004")) {
|
||||
return new Lcd2004(param);
|
||||
} else {
|
||||
|
||||
Reference in New Issue
Block a user