From 8817c532f4441c24fd4aa2d209c81d8865b5705e Mon Sep 17 00:00:00 2001 From: Dmitry Borisenko <49808844+DmitryBorisenko33@users.noreply.github.com> Date: Tue, 3 Nov 2020 22:45:43 +0300 Subject: [PATCH 1/5] esp32 compiling version --- include/RemoteOrdersUdp.h | 4 +++- platformio.ini | 2 +- src/items/LoggingClass.cpp | 8 ++++++-- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/include/RemoteOrdersUdp.h b/include/RemoteOrdersUdp.h index a8c2d8e0..1500c55e 100644 --- a/include/RemoteOrdersUdp.h +++ b/include/RemoteOrdersUdp.h @@ -1,7 +1,9 @@ #pragma once +#ifdef ESP8266 #include "ESPAsyncUDP.h" extern AsyncUDP asyncUdp; extern void asyncUdpInit(); extern String uint8tToString(uint8_t* data, size_t len); extern bool udpPacketValidation(String& data); -extern void udpPacketParse(String& data); \ No newline at end of file +extern void udpPacketParse(String& data); +#endif \ No newline at end of file diff --git a/platformio.ini b/platformio.ini index e80eaee2..7829153a 100644 --- a/platformio.ini +++ b/platformio.ini @@ -1,6 +1,6 @@ [platformio] -default_envs = esp8266 +default_envs = esp32 ;============================================================================================================================================= [common_env_data] lib_deps_external = diff --git a/src/items/LoggingClass.cpp b/src/items/LoggingClass.cpp index ca34a0ce..b5fa298c 100644 --- a/src/items/LoggingClass.cpp +++ b/src/items/LoggingClass.cpp @@ -42,7 +42,8 @@ void LoggingClass::addNewDelOldData(const String filename, size_t maxPoints, Str logData += timeNow->getTimeUnix() + " " + payload + "\r\n"; writeFile(filename, logData); } - } else { + } + else { if (timeNow->hasTimeSynced()) { addFileLn(filename, timeNow->getTimeUnix() + " " + payload); } @@ -95,7 +96,8 @@ void sendLogData(String file, String topic) { jsonWriteFloat(buf, "y1", value.toFloat()); if (log_date.length() < 3) { json_array += buf; - } else { + } + else { json_array += buf + ","; } buf = "{}"; @@ -111,10 +113,12 @@ void sendLogData(String file, String topic) { } void clean_log_date() { +#ifdef ESP8266 auto dir = LittleFS.openDir("logs"); while (dir.next()) { String fname = dir.fileName(); SerialPrint("I", "System", fname); removeFile("logs/" + fname); } +#endif } From aec1d507326e4d67aacd566c6720dde0b85b24da Mon Sep 17 00:00:00 2001 From: Dmitry Borisenko <49808844+DmitryBorisenko33@users.noreply.github.com> Date: Tue, 3 Nov 2020 22:49:57 +0300 Subject: [PATCH 2/5] 264 --- include/Consts.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/Consts.h b/include/Consts.h index 0f7b483f..cdfcc4f6 100644 --- a/include/Consts.h +++ b/include/Consts.h @@ -7,7 +7,7 @@ #endif #ifdef ESP32 #define FIRMWARE_NAME "esp32-iotm" -#define FIRMWARE_VERSION 259 +#define FIRMWARE_VERSION 264 #endif #define FLASH_4MB true From 2cad740fc64d3369b3e8151df09974cf678df2e6 Mon Sep 17 00:00:00 2001 From: Dmitry Borisenko <49808844+DmitryBorisenko33@users.noreply.github.com> Date: Wed, 4 Nov 2020 23:48:21 +0300 Subject: [PATCH 3/5] telegram bot added (working version) --- data/config.json | 2 +- data/index.json | 4 +- data/{set.push.json => set.telegram.json} | 14 +--- include/BufferExecute.h | 56 +++++++++++++- include/Global.h | 1 + include/ItemsCmd.h | 55 -------------- include/Telegram.h | 6 ++ include/items/ButtonInClass.h | 2 + platformio.ini | 5 +- src/BufferExecute.cpp | 77 ++++++++++++++++++- src/Init.cpp | 3 +- src/ItemsCmd.cpp | 92 +++++++++++------------ src/Telegram.cpp | 35 +++++++++ src/Utils/JsonUtils.cpp | 2 - src/Web.cpp | 37 ++++----- src/items/ButtonInClass.cpp | 6 +- src/items/ButtonOutClass.cpp | 2 +- src/items/ImpulsOutClass.cpp | 2 +- src/items/InputDigitClass.cpp | 2 +- src/items/InputTimeClass.cpp | 2 +- src/items/LoggingClass.cpp | 2 +- src/items/OutputTextClass.cpp | 2 +- src/items/PwmOutClass.cpp | 2 +- src/items/SensorAnalogClass.cpp | 2 +- src/items/SensorBme280Class.cpp | 2 +- src/items/SensorBmp280Class.cpp | 2 +- src/items/SensorDallas.cpp | 2 +- src/items/SensorDhtClass.cpp | 2 +- src/items/SensorModbusClass.cpp | 2 +- src/items/SensorUltrasonicClass.cpp | 2 +- src/items/sysUptime.cpp | 2 +- src/main.cpp | 40 +++++----- 32 files changed, 294 insertions(+), 173 deletions(-) rename data/{set.push.json => set.telegram.json} (65%) delete mode 100644 include/ItemsCmd.h create mode 100644 include/Telegram.h create mode 100644 src/Telegram.cpp diff --git a/data/config.json b/data/config.json index 562ff604..3782f65d 100644 --- a/data/config.json +++ b/data/config.json @@ -13,7 +13,7 @@ "mqttUser": "rise", "mqttPass": "23ri22se32", "scen": "1", - "pushingboxid": "v7C133E426B0C69E", + "telegramApi": "1425283609:AAFf3YO8ouCJF23kU8CMiU7XXy21MFhbn9w", "weblogin": "admin", "webpass": "admin", "udponoff": "1", diff --git a/data/index.json b/data/index.json index 0f12c670..c0f41268 100644 --- a/data/index.json +++ b/data/index.json @@ -37,8 +37,8 @@ }, { "type": "link", - "title": "Конфигурация push", - "action": "/?set.push", + "title": "Конфигурация telegram", + "action": "/?set.telegram", "class": "btn btn-block btn-default" }, { diff --git a/data/set.push.json b/data/set.telegram.json similarity index 65% rename from data/set.push.json rename to data/set.telegram.json index 555797e4..bdeef290 100644 --- a/data/set.push.json +++ b/data/set.telegram.json @@ -22,30 +22,24 @@ { "type": "h4", "style": "width:60%;float:left;", - "title": "Device id:" + "title": "Telegram API token:" }, { "type": "input", "title": "", - "name": "push-arg", + "name": "telegramApi-arg", "style": "width:40%;float:right", - "state": "{{pushingboxid}}" + "state": "{{telegramApi}}" }, { "type": "button", "title": "{{ButSave}}", - "action": "set?pushingboxid=[[push-arg]]", + "action": "set?telegramApi=[[telegramApi-arg]]", "class": "btn btn-block btn-default", "style": "width:100%;display:inline" }, { "type": "hr" - }, - { - "type": "link", - "title": "Перезагрузить устройство", - "action": "javascript:if(confirm(renameBlock(jsonResponse,'Перезагрузить?'))){send_request(this,'/restart?device=ok');}", - "class": "btn btn-block btn-danger" } ] } \ No newline at end of file diff --git a/include/BufferExecute.h b/include/BufferExecute.h index 076d73da..238844f5 100644 --- a/include/BufferExecute.h +++ b/include/BufferExecute.h @@ -7,4 +7,58 @@ extern void csvCmdExecute(String& cmdStr); extern void spaceCmdExecute(String& cmdStr); extern void loopCmdExecute(); extern void addKey(String& key, String& keyNumberTable, int number); -extern int getKeyNum(String& key, String& keyNumberTable); \ No newline at end of file +extern int getKeyNum(String& key, String& keyNumberTable); + +extern void buttonOut(); +extern void buttonOutSet(); + +extern void pwmOut(); +extern void pwmOutSet(); + +extern void buttonIn(); +extern void buttonInSet(); + +extern void inputDigit(); +extern void inputDigitSet(); + +extern void inputTime(); +extern void inputTimeSet(); + +extern void textOut(); +extern void textOutSet(); + +extern void analogAdc(); +extern void analogReading(); + +extern void ultrasonicCm(); +extern void ultrasonicReading(); + +extern void dallasTemp(); +extern void dallasReading(); + +extern void dhtTemp(); +extern void dhtReadingTemp(); +extern void dhtHum(); +extern void dhtReadingHum(); + +extern void bme280Temp(); +extern void bme280ReadingTemp(); +extern void bme280Hum(); +extern void bme280ReadingHum(); +extern void bme280Press(); +extern void bme280ReadingPress(); + +extern void bmp280Temp(); +extern void bmp280ReadingTemp(); +extern void bmp280Press(); +extern void bmp280ReadingPress(); + +//extern void modbus(); +//extern void modbusReading(); + +extern void sysUptime(); +extern void uptimeReading(); + +extern void logging(); + +extern void impuls(); diff --git a/include/Global.h b/include/Global.h index b4bcb7c5..3b1d295a 100644 --- a/include/Global.h +++ b/include/Global.h @@ -3,6 +3,7 @@ #include #include #include +#include "CTBot.h" #include #include #include diff --git a/include/ItemsCmd.h b/include/ItemsCmd.h deleted file mode 100644 index 39bbca79..00000000 --- a/include/ItemsCmd.h +++ /dev/null @@ -1,55 +0,0 @@ -#pragma once - -extern void buttonOut(); -extern void buttonOutSet(); - -extern void pwmOut(); -extern void pwmOutSet(); - -extern void buttonIn(); -extern void buttonInSet(); - -extern void inputDigit(); -extern void inputDigitSet(); - -extern void inputTime(); -extern void inputTimeSet(); - -extern void textOut(); -extern void textOutSet(); - -extern void analogAdc(); -extern void analogReading(); - -extern void ultrasonicCm(); -extern void ultrasonicReading(); - -extern void dallasTemp(); -extern void dallasReading(); - -extern void dhtTemp(); -extern void dhtReadingTemp(); -extern void dhtHum(); -extern void dhtReadingHum(); - -extern void bme280Temp(); -extern void bme280ReadingTemp(); -extern void bme280Hum(); -extern void bme280ReadingHum(); -extern void bme280Press(); -extern void bme280ReadingPress(); - -extern void bmp280Temp(); -extern void bmp280ReadingTemp(); -extern void bmp280Press(); -extern void bmp280ReadingPress(); - -//extern void modbus(); -//extern void modbusReading(); - -extern void sysUptime(); -extern void uptimeReading(); - -extern void logging(); - -extern void impuls(); diff --git a/include/Telegram.h b/include/Telegram.h new file mode 100644 index 00000000..d5645454 --- /dev/null +++ b/include/Telegram.h @@ -0,0 +1,6 @@ +#pragma once + + + +extern void telegramInit(); +extern void handleTelegram(); \ No newline at end of file diff --git a/include/items/ButtonInClass.h b/include/items/ButtonInClass.h index 10763529..07f3793f 100644 --- a/include/items/ButtonInClass.h +++ b/include/items/ButtonInClass.h @@ -4,6 +4,8 @@ #include "Class/LineParsing.h" #include "Global.h" + + class ButtonInClass : public LineParsing { protected: int numberEntering = 0; diff --git a/platformio.ini b/platformio.ini index 7829153a..443e042f 100644 --- a/platformio.ini +++ b/platformio.ini @@ -1,6 +1,6 @@ [platformio] -default_envs = esp32 +default_envs = esp8266 ;============================================================================================================================================= [common_env_data] lib_deps_external = @@ -26,6 +26,7 @@ lib_deps = AsyncTCP madhephaestus/ESP32Servo luc-github/ESP32SSDP + CTBot monitor_filters = esp32_exception_decoder upload_speed = 921600 monitor_speed = 115200 @@ -43,6 +44,7 @@ lib_deps = ESPAsyncTCP ESPAsyncUDP EspSoftwareSerial + CTBot monitor_filters = esp8266_exception_decoder upload_speed = 921600 monitor_speed = 115200 @@ -58,6 +60,7 @@ lib_deps = ESPAsyncTCP ESPAsyncUDP EspSoftwareSerial + CTBot monitor_filters = esp8266_exception_decoder upload_speed = 921600 monitor_speed = 115200 diff --git a/src/BufferExecute.cpp b/src/BufferExecute.cpp index ca6ec574..84873f93 100644 --- a/src/BufferExecute.cpp +++ b/src/BufferExecute.cpp @@ -1,5 +1,5 @@ #include "BufferExecute.h" - +#include "items/SensorDallas.h" #include "Global.h" #include "Module/Terminal.h" @@ -23,9 +23,80 @@ void csvCmdExecute(String& cmdStr) { int count = 0; while (cmdStr.length()) { String buf = selectToMarker(cmdStr, "\n"); + + + buf = deleteBeforeDelimiter(buf, " "); //отсечка чекбокса + count++; - if (count > 1) sCmd.readStr(buf); + if (count > 1) { + SerialPrint("I", "Items", buf); + String order = selectToMarker(buf, " "); //отсечка самой команды + + if (order == F("button-out")) { + sCmd.addCommand(order.c_str(), buttonOut); + } + else if (order == F("pwm-out")) { + sCmd.addCommand(order.c_str(), pwmOut); + } + else if (order == F("button-in")) { + sCmd.addCommand(order.c_str(), buttonIn); + } + else if (order == F("input-digit")) { + sCmd.addCommand(order.c_str(), inputDigit); + } + else if (order == F("input-time")) { + sCmd.addCommand(order.c_str(), inputTime); + } + else if (order == F("output-text")) { + sCmd.addCommand(order.c_str(), textOut); + } + else if (order == F("analog-adc")) { + sCmd.addCommand(order.c_str(), analogAdc); + } + else if (order == F("ultrasonic-cm")) { + sCmd.addCommand(order.c_str(), ultrasonicCm); + } + else if (order == F("dallas-temp")) { + sCmd.addCommand(order.c_str(), dallas); + } + else if (order == F("dht-temp")) { + sCmd.addCommand(order.c_str(), dhtTemp); + } + else if (order == F("dht-hum")) { + sCmd.addCommand(order.c_str(), dhtHum); + } + else if (order == F("bme280-temp")) { + sCmd.addCommand(order.c_str(), bme280Temp); + } + else if (order == F("bme280-hum")) { + sCmd.addCommand(order.c_str(), bme280Hum); + } + else if (order == F("bme280-press")) { + sCmd.addCommand(order.c_str(), bme280Press); + } + else if (order == F("bmp280-temp")) { + sCmd.addCommand(order.c_str(), bmp280Temp); + } + else if (order == F("bmp280-press")) { + sCmd.addCommand(order.c_str(), bmp280Press); + } + else if (order == F("modbus")) { + //sCmd.addCommand(order.c_str(), modbus); + } + else if (order == F("uptime")) { + sCmd.addCommand(order.c_str(), sysUptime); + } + else if (order == F("logging")) { + sCmd.addCommand(order.c_str(), logging); + } + else if (order == F("impuls-out")) { + sCmd.addCommand(order.c_str(), impuls); + } + + + sCmd.readStr(buf); + } cmdStr = deleteBeforeDelimiter(cmdStr, "\n"); } } @@ -80,7 +151,7 @@ void addKey(String& key, String& keyNumberTable, int number) { int getKeyNum(String& key, String& keyNumberTable) { String keyNumberTableBuf = keyNumberTable; - //SerialPrint("","",keyNumberTable); + int number = -1; while (keyNumberTableBuf.length()) { String tmp = selectToMarker(keyNumberTableBuf, ","); diff --git a/src/Init.cpp b/src/Init.cpp index 4b75d60f..f49654c4 100644 --- a/src/Init.cpp +++ b/src/Init.cpp @@ -35,19 +35,18 @@ void Device_init() { if (mySensorDallas2 != nullptr) { mySensorDallas2->clear(); } - //======clear logging params====== if (myLogging != nullptr) { myLogging->clear(); } loggingKeyList = ""; - //======clear impuls params======= if (myImpulsOut != nullptr) { myImpulsOut->clear(); } impulsKeyList = ""; impulsEnterCounter = -1; + //================================ #ifdef LAYOUT_IN_RAM diff --git a/src/ItemsCmd.cpp b/src/ItemsCmd.cpp index 4876b5e3..0b448b42 100644 --- a/src/ItemsCmd.cpp +++ b/src/ItemsCmd.cpp @@ -1,60 +1,60 @@ -#include "ItemsCmd.h" +//#include "BufferExecute.h" +// +//#include "BufferExecute.h" +//#include "Class/NotAsync.h" +//#include "Cmd.h" +//#include "Global.h" +//#include "Module/Terminal.h" +//#include "Servo/Servos.h" +// +//#include "items/SensorDallas.h" +// +//Terminal *term = nullptr; +// +//boolean but[NUM_BUTTONS]; +//Bounce *buttons = new Bounce[NUM_BUTTONS]; +// +//#ifdef ESP8266 +//SoftwareSerial *mySerial = nullptr; +//#else +//HardwareSerial *mySerial = nullptr; +//#endif +// +//void getData(); +// +//void cmd_init() { + //sCmd.addCommand("button-out", buttonOut); + //sCmd.addCommand("pwm-out", pwmOut); + //sCmd.addCommand("button-in", buttonIn); -#include "BufferExecute.h" -#include "Class/NotAsync.h" -#include "Cmd.h" -#include "Global.h" -#include "Module/Terminal.h" -#include "Servo/Servos.h" + //sCmd.addCommand("input-digit", inputDigit); + //sCmd.addCommand("input-time", inputTime); + //sCmd.addCommand("output-text", textOut); -#include "items/SensorDallas.h" + //sCmd.addCommand("analog-adc", analogAdc); + //sCmd.addCommand("ultrasonic-cm", ultrasonicCm); + //sCmd.addCommand("dallas-temp", dallas); -Terminal *term = nullptr; + //sCmd.addCommand("dht-temp", dhtTemp); + //sCmd.addCommand("dht-hum", dhtHum); -boolean but[NUM_BUTTONS]; -Bounce *buttons = new Bounce[NUM_BUTTONS]; + //sCmd.addCommand("bme280-temp", bme280Temp); + //sCmd.addCommand("bme280-hum", bme280Hum); + //sCmd.addCommand("bme280-press", bme280Press); -#ifdef ESP8266 -SoftwareSerial *mySerial = nullptr; -#else -HardwareSerial *mySerial = nullptr; -#endif - -void getData(); - -void cmd_init() { - sCmd.addCommand("button-out", buttonOut); - sCmd.addCommand("pwm-out", pwmOut); - sCmd.addCommand("button-in", buttonIn); - - sCmd.addCommand("input-digit", inputDigit); - sCmd.addCommand("input-time", inputTime); - sCmd.addCommand("output-text", textOut); - - sCmd.addCommand("analog-adc", analogAdc); - sCmd.addCommand("ultrasonic-cm", ultrasonicCm); - sCmd.addCommand("dallas-temp", dallas); - - sCmd.addCommand("dht-temp", dhtTemp); - sCmd.addCommand("dht-hum", dhtHum); - - sCmd.addCommand("bme280-temp", bme280Temp); - sCmd.addCommand("bme280-hum", bme280Hum); - sCmd.addCommand("bme280-press", bme280Press); - - sCmd.addCommand("bmp280-temp", bmp280Temp); - sCmd.addCommand("bmp280-press", bmp280Press); + //sCmd.addCommand("bmp280-temp", bmp280Temp); + //sCmd.addCommand("bmp280-press", bmp280Press); //sCmd.addCommand("modbus", modbus); - sCmd.addCommand("uptime", sysUptime); + //sCmd.addCommand("uptime", sysUptime); - sCmd.addCommand("logging", logging); + //sCmd.addCommand("logging", logging); - sCmd.addCommand("impuls-out", impuls); + //sCmd.addCommand("impuls-out", impuls); - handle_time_init(); -} + +//} // sCmd.addCommand("timerStart", timerStart_); // sCmd.addCommand("timerStop", timerStop_); diff --git a/src/Telegram.cpp b/src/Telegram.cpp new file mode 100644 index 00000000..9e88dbf6 --- /dev/null +++ b/src/Telegram.cpp @@ -0,0 +1,35 @@ +#include "Telegram.h" +#include "Global.h" + + +CTBot* myBot{ nullptr }; + +void telegramInit() { + String token = jsonReadStr(configSetupJson, "telegramApi"); + if (!myBot) { + myBot = new CTBot(); + } + myBot->setTelegramToken(token); + if (myBot->testConnection()) { + SerialPrint("I", "Telegram", "Connected"); + } + else { + SerialPrint("E", "Telegram", "Not connected"); + } +} + +void handleTelegram() { + + TBMessage msg; + + static unsigned long prevMillis; + unsigned long currentMillis = millis(); + unsigned long difference = currentMillis - prevMillis; + if (difference >= 1000) { + prevMillis = millis(); + if (myBot->getNewMessage(msg)) { + Serial.println(msg.text); + myBot->sendMessage(msg.sender.id, msg.text); + } + } +} \ No newline at end of file diff --git a/src/Utils/JsonUtils.cpp b/src/Utils/JsonUtils.cpp index bcc2c761..2389773c 100644 --- a/src/Utils/JsonUtils.cpp +++ b/src/Utils/JsonUtils.cpp @@ -2,8 +2,6 @@ #include "Utils/FileUtils.h" #include "Global.h" -#include - String jsonReadStr(String& json, String name) { DynamicJsonBuffer jsonBuffer; JsonObject& root = jsonBuffer.parseObject(json); diff --git a/src/Web.cpp b/src/Web.cpp index 9625950b..55a94df4 100644 --- a/src/Web.cpp +++ b/src/Web.cpp @@ -193,14 +193,13 @@ void web_init() { request->send(200, "text/html", payload); } - // //==============================push settings============================================= - //#ifdef PUSH_ENABLED - // if (request->hasArg("pushingboxid")) { - // jsonWriteStr(configSetupJson, "pushingboxid", request->getParam("pushingboxid")->value()); - // saveConfig(); - // request->send(200); - // } - //#endif + //==============================push settings============================================= + if (request->hasArg("telegramApi")) { + jsonWriteStr(configSetupJson, "telegramApi", request->getParam("telegramApi")->value()); + + saveConfig(); + request->send(200); + } //==============================utilities settings============================================= if (request->hasArg("i2c")) { @@ -215,7 +214,7 @@ void web_init() { serverIP = jsonReadStr(configSetupJson, "serverip"); request->send(200); } - }); + }); //==============================list of items===================================================== //server.on("/del", HTTP_GET, [](AsyncWebServerRequest* request) { @@ -230,7 +229,7 @@ void web_init() { // request->redirect("/?setn.device"); //}); - /* + /* * Check */ server.on("/check", HTTP_GET, [](AsyncWebServerRequest* request) { @@ -240,13 +239,17 @@ void web_init() { String msg = ""; if (lastVersion == FIRMWARE_VERSION) { msg = F("Актуальная версия прошивки уже установлена."); - } else if (lastVersion > FIRMWARE_VERSION) { + } + else if (lastVersion > FIRMWARE_VERSION) { msg = F("Новая версия прошивкиИдет обновление прошивки, после обновления страница перезагрузится автоматически...')\">Установить"); - } else if (lastVersion == -1) { + } + else if (lastVersion == -1) { msg = F("Cервер не найден. Попробуйте повторить позже..."); - } else if (lastVersion == -2) { + } + else if (lastVersion == -2) { msg = F("Устройство не подключено к роутеру!"); - } else if (lastVersion < FIRMWARE_VERSION) { + } + else if (lastVersion < FIRMWARE_VERSION) { msg = F("Ошибка версии. Попробуйте повторить позже..."); } @@ -262,15 +265,15 @@ void web_init() { jsonWriteStr(tmp, "title", "" + msg); jsonWriteStr(tmp, "class", "pop-up"); request->send(200, "text/html", tmp); - }); + }); - /* + /* * Upgrade */ server.on("/upgrade", HTTP_GET, [](AsyncWebServerRequest* request) { myNotAsyncActions->make(do_UPGRADE); request->send(200, "text/html"); - }); + }); } void setConfigParam(const char* param, const String& value) { diff --git a/src/items/ButtonInClass.cpp b/src/items/ButtonInClass.cpp index 6f48a834..23a944f2 100644 --- a/src/items/ButtonInClass.cpp +++ b/src/items/ButtonInClass.cpp @@ -1,8 +1,12 @@ -#include "ItemsCmd.h" +#include "BufferExecute.h" #include "items/ButtonInClass.h" //==========================================Модуль физических кнопок======================================== //button-in switch1 toggle Кнопки Свет 1 pin[2] db[20] //========================================================================================================== + +boolean but[NUM_BUTTONS]; +Bounce *buttons = new Bounce[NUM_BUTTONS]; + ButtonInClass myButtonIn; void buttonIn() { myButtonIn.update(); diff --git a/src/items/ButtonOutClass.cpp b/src/items/ButtonOutClass.cpp index 6f2b5d03..ba674e0d 100644 --- a/src/items/ButtonOutClass.cpp +++ b/src/items/ButtonOutClass.cpp @@ -1,6 +1,6 @@ #include "items/ButtonOutClass.h" -#include "ItemsCmd.h" +#include "BufferExecute.h" //==========================================Модуль кнопок=================================================== //button-out light toggle Кнопки Свет 1 pin[12] inv[1] st[1] //========================================================================================================== diff --git a/src/items/ImpulsOutClass.cpp b/src/items/ImpulsOutClass.cpp index 99f860d4..4cab6494 100644 --- a/src/items/ImpulsOutClass.cpp +++ b/src/items/ImpulsOutClass.cpp @@ -4,7 +4,7 @@ #include "BufferExecute.h" #include "Class/LineParsing.h" #include "Global.h" -#include "ItemsCmd.h" +#include "BufferExecute.h" ImpulsOutClass::ImpulsOutClass(unsigned int impulsPin) { _impulsPin = impulsPin; diff --git a/src/items/InputDigitClass.cpp b/src/items/InputDigitClass.cpp index ff221740..1a2e3b38 100644 --- a/src/items/InputDigitClass.cpp +++ b/src/items/InputDigitClass.cpp @@ -1,4 +1,4 @@ -#include "ItemsCmd.h" +#include "BufferExecute.h" #include "items/InputClass.h" //==========================================Модуль ввода цифровых значений================================== //input-digit digit1 inputDigit Ввод Введите.цифру 4 st[60] diff --git a/src/items/InputTimeClass.cpp b/src/items/InputTimeClass.cpp index 43d14b3f..4d632550 100644 --- a/src/items/InputTimeClass.cpp +++ b/src/items/InputTimeClass.cpp @@ -1,4 +1,4 @@ -#include "ItemsCmd.h" +#include "BufferExecute.h" #include "items/InputClass.h" //==========================================Модуль ввода времени============================================ //========================================================================================================== diff --git a/src/items/LoggingClass.cpp b/src/items/LoggingClass.cpp index b5fa298c..e01e01f5 100644 --- a/src/items/LoggingClass.cpp +++ b/src/items/LoggingClass.cpp @@ -4,7 +4,7 @@ #include "Class/LineParsing.h" #include "Global.h" -#include "ItemsCmd.h" +#include "BufferExecute.h" LoggingClass::LoggingClass(unsigned long period, unsigned int maxPoints, String loggingValueKey, String key) { _period = period * 1000; diff --git a/src/items/OutputTextClass.cpp b/src/items/OutputTextClass.cpp index 89c6d322..f86de77d 100644 --- a/src/items/OutputTextClass.cpp +++ b/src/items/OutputTextClass.cpp @@ -1,4 +1,4 @@ -#include "ItemsCmd.h" +#include "BufferExecute.h" #include "items/OutputTextClass.h" //===============================================Модуль вывода текста============================================ //output-text;id;anydata;Вывод;Сигнализация;order;st[Обнаружено.движение] diff --git a/src/items/PwmOutClass.cpp b/src/items/PwmOutClass.cpp index 42d63d6f..44ece25c 100644 --- a/src/items/PwmOutClass.cpp +++ b/src/items/PwmOutClass.cpp @@ -1,4 +1,4 @@ -#include "ItemsCmd.h" +#include "BufferExecute.h" #include "items/PwmOutClass.h" //==========================================Модуль управления ШИМ=================================================== //pwm-out volume range Кнопки Свет 1 pin[12] st[500] diff --git a/src/items/SensorAnalogClass.cpp b/src/items/SensorAnalogClass.cpp index bba5cc60..470d31c6 100644 --- a/src/items/SensorAnalogClass.cpp +++ b/src/items/SensorAnalogClass.cpp @@ -1,4 +1,4 @@ -#include "ItemsCmd.h" +#include "BufferExecute.h" #include "items/SensorAnalogClass.h" #ifdef ANALOG_ENABLED //==============================================Модуль аналогового сенсора=========================================================================================== diff --git a/src/items/SensorBme280Class.cpp b/src/items/SensorBme280Class.cpp index f07ae77e..21a2f476 100644 --- a/src/items/SensorBme280Class.cpp +++ b/src/items/SensorBme280Class.cpp @@ -1,6 +1,6 @@ #include "items/SensorBme280Class.h" -#include "ItemsCmd.h" +#include "BufferExecute.h" //#ifdef SensorBme280Enabled //=========================================Модуль ультрозвукового дальномера================================================================== //bme280-temp;id;anydata;Сенсоры;Температура;order;c[1] diff --git a/src/items/SensorBmp280Class.cpp b/src/items/SensorBmp280Class.cpp index 1dbfbd5d..e6a2e7ed 100644 --- a/src/items/SensorBmp280Class.cpp +++ b/src/items/SensorBmp280Class.cpp @@ -1,6 +1,6 @@ #include "items/SensorBmp280Class.h" -#include "ItemsCmd.h" +#include "BufferExecute.h" //#ifdef SensorBmp280Enabled //=========================================Модуль ультрозвукового дальномера================================================================== //bmp280-temp;id;anydata;Сенсоры;Температура;order;c[1] diff --git a/src/items/SensorDallas.cpp b/src/items/SensorDallas.cpp index f861dc20..f30983fc 100644 --- a/src/items/SensorDallas.cpp +++ b/src/items/SensorDallas.cpp @@ -1,7 +1,7 @@ #include "items/SensorDallas.h" #include "Class/LineParsing.h" #include "Global.h" -#include "ItemsCmd.h" +#include "BufferExecute.h" #include SensorDallas::SensorDallas(unsigned long interval, unsigned int pin, unsigned int index, String key) { diff --git a/src/items/SensorDhtClass.cpp b/src/items/SensorDhtClass.cpp index 38363a8b..035a4eb2 100644 --- a/src/items/SensorDhtClass.cpp +++ b/src/items/SensorDhtClass.cpp @@ -1,6 +1,6 @@ #include "items/SensorDhtClass.h" -#include "ItemsCmd.h" +#include "BufferExecute.h" //#ifdef SensorDhtEnabled //=========================================DHT Sensor================================================================== //dht-temp;id;anydata;Сенсоры;Температура;order;pin;type[dht11];c[1] diff --git a/src/items/SensorModbusClass.cpp b/src/items/SensorModbusClass.cpp index 2683256a..368fe916 100644 --- a/src/items/SensorModbusClass.cpp +++ b/src/items/SensorModbusClass.cpp @@ -1,6 +1,6 @@ //#include "items/SensorModbusClass.h" // -//#include "ItemsCmd.h" +//#include "BufferExecute.h" ////#ifdef SensorModbusEnabled ////=========================================Модуль modbus=================================================================================== ////modbus;id;anydata;Сенсоры;Температура;order;addr[1];regaddr[0];c[1] diff --git a/src/items/SensorUltrasonicClass.cpp b/src/items/SensorUltrasonicClass.cpp index 6de999eb..cd72a470 100644 --- a/src/items/SensorUltrasonicClass.cpp +++ b/src/items/SensorUltrasonicClass.cpp @@ -1,4 +1,4 @@ -#include "ItemsCmd.h" +#include "BufferExecute.h" #include "items/SensorUltrasonicClass.h" //#ifdef SensorUltrasonicEnabled //=========================================Модуль ультрозвукового дальномера================================================================== diff --git a/src/items/sysUptime.cpp b/src/items/sysUptime.cpp index 2f1b222c..910bb871 100644 --- a/src/items/sysUptime.cpp +++ b/src/items/sysUptime.cpp @@ -1,5 +1,5 @@ #include "Class/LineParsing.h" -#include "ItemsCmd.h" +#include "BufferExecute.h" #include "Global.h" #include diff --git a/src/main.cpp b/src/main.cpp index fc1f3dc7..fef52869 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -18,6 +18,7 @@ #include "items/LoggingClass.h" #include "items/ImpulsOutClass.h" #include "items/SensorDallas.h" +#include "Telegram.h" void not_async_actions(); @@ -38,44 +39,47 @@ void setup() { myNotAsyncActions = new NotAsync(do_LAST); myScenario = new Scenario(); - SerialPrint("I", "FS", "FS Init"); fileSystemInit(); + SerialPrint("I", "FS", "FS Init"); - SerialPrint("I", "Conf", "Config Init"); loadConfig(); + SerialPrint("I", "Conf", "Config Init"); - SerialPrint("I", "Time", "Clock Init"); clock_init(); + SerialPrint("I", "Time", "Clock Init"); - SerialPrint("I", "CMD", "Commands Init"); - cmd_init(); + handle_time_init(); + SerialPrint("I", "Time", "Handle time init("); - SerialPrint("I", "Sensors", "Sensors Init"); sensorsInit(); + SerialPrint("I", "Sensors", "Sensors Init"); - SerialPrint("I", "Items", "Items Init"); itemsListInit(); + SerialPrint("I", "Items", "Items Init"); - SerialPrint("I", "Init", "Init Init"); all_init(); + SerialPrint("I", "Init", "Init Init"); - SerialPrint("I", "WIFI", "Network Init"); routerConnect(); + SerialPrint("I", "WIFI", "Network Init"); + + telegramInit(); + SerialPrint("I", "Telegram", "Telegram Init"); - SerialPrint("I", "Uptime", "Uptime Init"); uptime_init(); + SerialPrint("I", "Uptime", "Uptime Init"); - SerialPrint("I", "Update", "Updater Init"); upgradeInit(); + SerialPrint("I", "Update", "Updater Init"); - SerialPrint("I", "HTTP", "HttpServer Init"); HttpServer::init(); + SerialPrint("I", "HTTP", "HttpServer Init"); - SerialPrint("I", "Web", "WebAdmin Init"); web_init(); + SerialPrint("I", "Web", "WebAdmin Init"); - SerialPrint("I", "Stat", "Stat Init"); initSt(); + SerialPrint("I", "Stat", "Stat Init"); #ifdef UDP_ENABLED SerialPrint("I", "UDP", "Udp Init"); @@ -90,6 +94,8 @@ void setup() { SsdpInit(); #endif + + //esp_log_level_set("esp_littlefs", ESP_LOG_NONE); ts.add( @@ -99,9 +105,7 @@ void setup() { nullptr, true); just_load = false; - initialized = true; //this second POST makes the data to be processed (you don't need to connect as "keep-alive" for that to work) - - + initialized = true; } void loop() { @@ -124,6 +128,8 @@ void loop() { myNotAsyncActions->loop(); ts.update(); + handleTelegram(); + if (myLogging != nullptr) { for (unsigned int i = 0; i < myLogging->size(); i++) { myLogging->at(i).loop(); From 1f69019bb33a196923fb96f66ea0f8152da31729 Mon Sep 17 00:00:00 2001 From: Dmitry Borisenko <49808844+DmitryBorisenko33@users.noreply.github.com> Date: Thu, 5 Nov 2020 02:23:08 +0300 Subject: [PATCH 4/5] 265 Telegram support added --- data/config.json | 1 + data/set.device.json | 2 +- data/set.telegram.json | 18 ++++++++++-- include/Consts.h | 4 +-- include/Global.h | 1 + include/Telegram.h | 6 ++-- src/BufferExecute.cpp | 1 + src/Global.cpp | 1 + src/Telegram.cpp | 67 +++++++++++++++++++++++++++--------------- src/Web.cpp | 11 +++++-- 10 files changed, 79 insertions(+), 33 deletions(-) diff --git a/data/config.json b/data/config.json index 3782f65d..48676490 100644 --- a/data/config.json +++ b/data/config.json @@ -14,6 +14,7 @@ "mqttPass": "23ri22se32", "scen": "1", "telegramApi": "1425283609:AAFf3YO8ouCJF23kU8CMiU7XXy21MFhbn9w", + "telegonof": "0", "weblogin": "admin", "webpass": "admin", "udponoff": "1", diff --git a/data/set.device.json b/data/set.device.json index 9dd95abc..2b24c230 100644 --- a/data/set.device.json +++ b/data/set.device.json @@ -43,7 +43,7 @@ }, { "type": "h4", - "title": "LittleFS version: 264" + "title": "LittleFS version: 265" }, { "type": "hr" diff --git a/data/set.telegram.json b/data/set.telegram.json index bdeef290..e4a22bb7 100644 --- a/data/set.telegram.json +++ b/data/set.telegram.json @@ -19,16 +19,26 @@ { "type": "hr" }, + { + "type": "checkbox", + "name": "tel", + "title": "Включить телеграм", + "action": "/set?telegonof=[[tel]]", + "state": "{{telegonof}}" + }, + { + "type": "hr" + }, { "type": "h4", - "style": "width:60%;float:left;", + "style": "width:40%;float:left;", "title": "Telegram API token:" }, { "type": "input", "title": "", "name": "telegramApi-arg", - "style": "width:40%;float:right", + "style": "width:60%;float:right", "state": "{{telegramApi}}" }, { @@ -40,6 +50,10 @@ }, { "type": "hr" + }, + { + "type": "text", + "title": "

После настройки telegram перезагрузите устройство что бы изменения вступили в силу

" } ] } \ No newline at end of file diff --git a/include/Consts.h b/include/Consts.h index cdfcc4f6..89f366ba 100644 --- a/include/Consts.h +++ b/include/Consts.h @@ -3,11 +3,11 @@ //===========Firmware============================================================================================================================================= #ifdef ESP8266 #define FIRMWARE_NAME "esp8266-iotm" -#define FIRMWARE_VERSION 264 +#define FIRMWARE_VERSION 265 #endif #ifdef ESP32 #define FIRMWARE_NAME "esp32-iotm" -#define FIRMWARE_VERSION 264 +#define FIRMWARE_VERSION 265 #endif #define FLASH_4MB true diff --git a/include/Global.h b/include/Global.h index 3b1d295a..11de486a 100644 --- a/include/Global.h +++ b/include/Global.h @@ -47,6 +47,7 @@ extern Bounce* buttons; //Global vars extern boolean just_load; +extern boolean telegramInitBeen; // Json extern String configSetupJson; //все настройки diff --git a/include/Telegram.h b/include/Telegram.h index d5645454..1524373e 100644 --- a/include/Telegram.h +++ b/include/Telegram.h @@ -1,6 +1,6 @@ #pragma once - - +extern void sendTelegramMsg(); extern void telegramInit(); -extern void handleTelegram(); \ No newline at end of file +extern void handleTelegram(); +extern bool isTelegramEnabled(); \ No newline at end of file diff --git a/src/BufferExecute.cpp b/src/BufferExecute.cpp index 84873f93..ecba8a91 100644 --- a/src/BufferExecute.cpp +++ b/src/BufferExecute.cpp @@ -93,6 +93,7 @@ void csvCmdExecute(String& cmdStr) { else if (order == F("impuls-out")) { sCmd.addCommand(order.c_str(), impuls); } + sCmd.readStr(buf); diff --git a/src/Global.cpp b/src/Global.cpp index a6d8ae9e..75203c97 100644 --- a/src/Global.cpp +++ b/src/Global.cpp @@ -18,6 +18,7 @@ DallasTemperature sensors; */ boolean just_load = true; +boolean telegramInitBeen = false; // Json String configSetupJson = "{}"; diff --git a/src/Telegram.cpp b/src/Telegram.cpp index 9e88dbf6..a79524c2 100644 --- a/src/Telegram.cpp +++ b/src/Telegram.cpp @@ -1,35 +1,56 @@ #include "Telegram.h" #include "Global.h" - CTBot* myBot{ nullptr }; void telegramInit() { - String token = jsonReadStr(configSetupJson, "telegramApi"); - if (!myBot) { - myBot = new CTBot(); - } - myBot->setTelegramToken(token); - if (myBot->testConnection()) { - SerialPrint("I", "Telegram", "Connected"); - } - else { - SerialPrint("E", "Telegram", "Not connected"); + if (isTelegramEnabled()) { + telegramInitBeen = true; + sCmd.addCommand("telegram", sendTelegramMsg); + String token = jsonReadStr(configSetupJson, "telegramApi"); + if (!myBot) { + myBot = new CTBot(); + } + myBot->setTelegramToken(token); + myBot->enableUTF8Encoding(true); + if (myBot->testConnection()) { + SerialPrint("I", "Telegram", "Connected"); + } + else { + SerialPrint("E", "Telegram", "Not connected"); + } } } void handleTelegram() { - - TBMessage msg; - - static unsigned long prevMillis; - unsigned long currentMillis = millis(); - unsigned long difference = currentMillis - prevMillis; - if (difference >= 1000) { - prevMillis = millis(); - if (myBot->getNewMessage(msg)) { - Serial.println(msg.text); - myBot->sendMessage(msg.sender.id, msg.text); - } + if (telegramInitBeen) { + if (isTelegramEnabled()) { + TBMessage msg; + static unsigned long prevMillis; + unsigned long currentMillis = millis(); + unsigned long difference = currentMillis - prevMillis; + if (difference >= 1000) { + prevMillis = millis(); + if (myBot->getNewMessage(msg)) { + SerialPrint("->", "Telegram", "chat ID: " + String(msg.sender.id) + ", msg: " + String(msg.text)); + jsonWriteInt(configSetupJson, "chatId", msg.sender.id); + saveConfig(); + orderBuf += String(msg.text) + ","; + myBot->sendMessage(jsonReadInt(configSetupJson, "chatId"), msg.text); + SerialPrint("<-", "Telegram", "chat ID: " + String(jsonReadInt(configSetupJson, "chatId")) + ", msg: " + String(msg.text)); + } + } + } } +} + +void sendTelegramMsg() { + String msg = sCmd.next(); + msg.replace("#"," "); + myBot->sendMessage(jsonReadInt(configSetupJson, "chatId"), msg); + SerialPrint("<-", "Telegram", "chat ID: " + String(jsonReadInt(configSetupJson, "chatId")) + ", msg: " + msg); +} + +bool isTelegramEnabled() { + return jsonReadBool(configSetupJson, "telegonof"); } \ No newline at end of file diff --git a/src/Web.cpp b/src/Web.cpp index 55a94df4..d2f53825 100644 --- a/src/Web.cpp +++ b/src/Web.cpp @@ -1,10 +1,10 @@ #include "Web.h" - #include "Class/NotAsync.h" #include "Global.h" #include "Init.h" #include "ItemsList.h" #include "items/LoggingClass.h" +#include "Telegram.h" bool parseRequestForPreset(AsyncWebServerRequest* request, uint8_t& preset) { if (request->hasArg("preset")) { @@ -196,7 +196,14 @@ void web_init() { //==============================push settings============================================= if (request->hasArg("telegramApi")) { jsonWriteStr(configSetupJson, "telegramApi", request->getParam("telegramApi")->value()); - + //telegramInit(); + saveConfig(); + request->send(200); + } + if (request->hasArg("telegonof")) { + bool value = request->getParam("telegonof")->value().toInt(); + jsonWriteBool(configSetupJson, "telegonof", value); + //telegramInit(); saveConfig(); request->send(200); } From e52437b828a28df21a11097050349943a4cdc371 Mon Sep 17 00:00:00 2001 From: Dmitry Borisenko <49808844+DmitryBorisenko33@users.noreply.github.com> Date: Thu, 5 Nov 2020 17:27:18 +0300 Subject: [PATCH 5/5] 266 (fix scenario bug) --- data/config.json | 4 +- data/set.device.json | 2 +- include/Consts.h | 4 +- include/Telegram.h | 4 +- src/Class/ScenarioClass.cpp | 9 +++- src/Scenario.cpp | 97 ------------------------------------- src/Telegram.cpp | 28 ++++++++--- 7 files changed, 37 insertions(+), 111 deletions(-) delete mode 100644 src/Scenario.cpp diff --git a/data/config.json b/data/config.json index 48676490..bf6da577 100644 --- a/data/config.json +++ b/data/config.json @@ -3,8 +3,8 @@ "chipID": "", "apssid": "IoTmanager", "appass": "", - "routerssid": "rise", - "routerpass": "hostel3333", + "routerssid": "VOLODYA", + "routerpass": "BELCHENKO", "timezone": 2, "ntp": "pool.ntp.org", "mqttServer": "91.204.228.124", diff --git a/data/set.device.json b/data/set.device.json index 2b24c230..345d62eb 100644 --- a/data/set.device.json +++ b/data/set.device.json @@ -43,7 +43,7 @@ }, { "type": "h4", - "title": "LittleFS version: 265" + "title": "LittleFS version: 266" }, { "type": "hr" diff --git a/include/Consts.h b/include/Consts.h index 89f366ba..a81d1977 100644 --- a/include/Consts.h +++ b/include/Consts.h @@ -3,11 +3,11 @@ //===========Firmware============================================================================================================================================= #ifdef ESP8266 #define FIRMWARE_NAME "esp8266-iotm" -#define FIRMWARE_VERSION 265 +#define FIRMWARE_VERSION 266 #endif #ifdef ESP32 #define FIRMWARE_NAME "esp32-iotm" -#define FIRMWARE_VERSION 265 +#define FIRMWARE_VERSION 266 #endif #define FLASH_4MB true diff --git a/include/Telegram.h b/include/Telegram.h index 1524373e..69a75811 100644 --- a/include/Telegram.h +++ b/include/Telegram.h @@ -1,6 +1,8 @@ #pragma once +#include "Global.h" extern void sendTelegramMsg(); extern void telegramInit(); extern void handleTelegram(); -extern bool isTelegramEnabled(); \ No newline at end of file +extern bool isTelegramEnabled(); +extern void telegramMsgParse(String msg); \ No newline at end of file diff --git a/src/Class/ScenarioClass.cpp b/src/Class/ScenarioClass.cpp index d066cc62..b7de405e 100644 --- a/src/Class/ScenarioClass.cpp +++ b/src/Class/ScenarioClass.cpp @@ -1,2 +1,9 @@ #include "Class/ScenarioClass.h" -Scenario* myScenario; \ No newline at end of file +Scenario* myScenario; + +void eventGen(String event_name, String number) { + if (!jsonReadBool(configSetupJson, "scen")) { + return; + } + eventBuf += event_name + number + ","; +} \ No newline at end of file diff --git a/src/Scenario.cpp b/src/Scenario.cpp deleted file mode 100644 index ce0ec90d..00000000 --- a/src/Scenario.cpp +++ /dev/null @@ -1,97 +0,0 @@ -#include "Cmd.h" -#include "Global.h" -#include "Class/ScenarioClass.h" - - - -boolean isScenarioEnabled() { - return jsonReadBool(configSetupJson, "scen") && eventBuf != ""; -} - -//void loopScenario() { -// if (!isScenarioEnabled()) { -// return; -// } -// String scenarioTmp = scenario; -// scenarioTmp += "\n"; -// scenarioTmp.replace("\r\n", "\n"); -// scenarioTmp.replace("\r", "\n"); -// -// while (scenarioTmp.length()) { -// String scenBlok = selectToMarker(scenarioTmp, "end"); //выделяем первый сценарий -// if (!scenBlok.length()) { -// return; -// } -// -// size_t i = 0; -// i++; -// if (scenario_line_status[i] == 1) { -// String condition = selectToMarker(scenBlok, "\n"); //выделяем условие -// -// String conditionParam = selectFromMarkerToMarker(condition, " ", 0); //выделяем параметр условия -// String order = eventBuf; -// String eventParam = selectToMarker(order, ","); //выделяем параметр события -// -// if (conditionParam == eventParam) { //если поступившее событие равно событию заданному buttonSet1 в файле начинаем его обработку -// -// String conditionSign = selectFromMarkerToMarker(condition, " ", 1); //выделяем знак (=) -// -// String conditionValue = selectFromMarkerToMarker(condition, " ", 2); //выделяем значение (1) -// -// boolean flag = false; -// -// String eventParam = jsonReadStr(configLiveJson, conditionParam); //получаем значение этого параметра события из json -// -// if (conditionSign == "=") { -// flag = eventParam == conditionValue; -// } else if (conditionSign == "!=") { -// flag = eventParam != conditionValue; -// } else if (conditionSign == "<") { -// flag = eventParam.toInt() < conditionValue.toInt(); -// } else if (conditionSign == ">") { -// flag = eventParam.toInt() > conditionValue.toInt(); -// } else if (conditionSign == ">=") { -// flag = eventParam.toInt() >= conditionValue.toInt(); -// } else if (conditionSign == "<=") { -// flag = eventParam.toInt() <= conditionValue.toInt(); -// } -// -// if (flag) { -// scenBlok = deleteBeforeDelimiter(scenBlok, "\n"); // удаляем строку самого сценария оставляя только команды -// SerialPrint("I","module","do: " + scenBlok); -// spaceCmdExecute(scenBlok); // выполняем все команды -// } -// } -// } -// scenarioTmp = deleteBeforeDelimiter(scenarioTmp, "end\n"); //удаляем первый сценарий -// } -// -// String eventBufTmp = eventBuf; //читаем файл событий -// eventBufTmp = deleteBeforeDelimiter(eventBufTmp, ","); //удаляем выполненное событие -// eventBuf = eventBufTmp; //записываем обновленный файл событий -//} - -void eventGen(String event_name, String number) { - if (!jsonReadBool(configSetupJson, "scen")) { - return; - } - eventBuf = event_name + number + ","; -} - -//String add_set(String str) { -// String num1 = str.substring(str.length() - 1); -// String num2 = str.substring(str.length() - 2, str.length() - 1); -// if (isDigitStr(num1) && isDigitStr(num2)) { -// str = str.substring(0, str.length() - 2) + "Set" + num2 + num1; -// } else { -// if (isDigitStr(num1)) { -// str = str.substring(0, str.length() - 1) + "Set" + num1; -// } -// } -// return str; -//} - -//button-out1 = 1 -//button-out2 1 -//button-out3 1 -//end \ No newline at end of file diff --git a/src/Telegram.cpp b/src/Telegram.cpp index a79524c2..46973e42 100644 --- a/src/Telegram.cpp +++ b/src/Telegram.cpp @@ -1,5 +1,5 @@ #include "Telegram.h" -#include "Global.h" + CTBot* myBot{ nullptr }; @@ -29,24 +29,38 @@ void handleTelegram() { static unsigned long prevMillis; unsigned long currentMillis = millis(); unsigned long difference = currentMillis - prevMillis; - if (difference >= 1000) { + if (difference >= 5000) { prevMillis = millis(); if (myBot->getNewMessage(msg)) { SerialPrint("->", "Telegram", "chat ID: " + String(msg.sender.id) + ", msg: " + String(msg.text)); jsonWriteInt(configSetupJson, "chatId", msg.sender.id); saveConfig(); - orderBuf += String(msg.text) + ","; - myBot->sendMessage(jsonReadInt(configSetupJson, "chatId"), msg.text); - SerialPrint("<-", "Telegram", "chat ID: " + String(jsonReadInt(configSetupJson, "chatId")) + ", msg: " + String(msg.text)); + telegramMsgParse(String(msg.text)); } } - } + } + } +} + +void telegramMsgParse(String msg) { + SerialPrint("<-", "Telegram", "chat ID: " + String(jsonReadInt(configSetupJson, "chatId")) + ", msg: " + String(msg)); + if (msg.indexOf("order") != -1) { + msg = deleteBeforeDelimiter(msg, " "); + orderBuf += String(msg) + ","; + myBot->sendMessage(jsonReadInt(configSetupJson, "chatId"), "order done"); + } + else if (msg.indexOf("get") != -1) { + msg = deleteBeforeDelimiter(msg, " "); + myBot->sendMessage(jsonReadInt(configSetupJson, "chatId"), jsonReadStr(configLiveJson, msg)); + } + else { + myBot->sendMessage(jsonReadInt(configSetupJson, "chatId"), "wrong order, use 'get id' to get value, or 'order id value' to send order"); } } void sendTelegramMsg() { String msg = sCmd.next(); - msg.replace("#"," "); + msg.replace("#", " "); myBot->sendMessage(jsonReadInt(configSetupJson, "chatId"), msg); SerialPrint("<-", "Telegram", "chat ID: " + String(jsonReadInt(configSetupJson, "chatId")) + ", msg: " + msg); }