diff --git a/data_svelte/items.json b/data_svelte/items.json index 3468a035..e244ac84 100644 --- a/data_svelte/items.json +++ b/data_svelte/items.json @@ -7,7 +7,7 @@ "header": "Виртуальные элементы" }, { - "name": "1. Логгирование в график", + "name": "1. Логирование в график", "type": "Writing", "subtype": "Loging", "id": "log", @@ -457,11 +457,23 @@ "apin": -1, "num": 34 }, + { + "name": "35. Телеграм-Лайт", + "type": "Writing", + "subtype": "TelegramLT", + "id": "tg", + "widget": "", + "page": "", + "descr": "", + "token": "", + "chatID": "", + "num": 35 + }, { "header": "Экраны" }, { - "name": "35. LCD экран 2004", + "name": "36. LCD экран 2004", "type": "Reading", "subtype": "Lcd2004", "id": "Lcd", @@ -473,10 +485,10 @@ "size": "20,4", "coord": "0,0", "id2show": "id датчика", - "num": 35 + "num": 36 }, { - "name": "36. LCD экран 1602", + "name": "37. LCD экран 1602", "type": "Reading", "subtype": "Lcd2004", "id": "Lcd", @@ -488,6 +500,6 @@ "size": "16,2", "coord": "0,0", "id2show": "id датчика", - "num": 36 + "num": 37 } ] \ No newline at end of file diff --git a/include/classes/IoTScenario.h b/include/classes/IoTScenario.h index f212bb8a..83a47531 100644 --- a/include/classes/IoTScenario.h +++ b/include/classes/IoTScenario.h @@ -26,7 +26,7 @@ class IoTScenario { //===----------------------------------------------------------------------===// String IdentifierStr; // Заполняется, если tok_identifier - float NumVal; // Заполняется, если tok_number + String NumStr = ""; // Заполняется, если tok_number int LastChar; int curLine; diff --git a/include/utils/StringUtils.h b/include/utils/StringUtils.h index b40e443a..5a1edc41 100644 --- a/include/utils/StringUtils.h +++ b/include/utils/StringUtils.h @@ -39,3 +39,5 @@ boolean isDigitStr(const String& str); boolean isDigitDotCommaStr(const String& str); String prettyBytes(size_t size); + +String uint64ToString(uint64_t input); diff --git a/myProfile.json b/myProfile.json index 4fcac5c5..28cb48c2 100644 --- a/myProfile.json +++ b/myProfile.json @@ -162,6 +162,10 @@ { "path": "src\\modules\\exec\\Telegram", "active": false + }, + { + "path": "src\\modules\\exec\\TelegramLT", + "active": true } ], "Экраны": [ diff --git a/platformio.ini b/platformio.ini index d7470c0d..01416d14 100644 --- a/platformio.ini +++ b/platformio.ini @@ -31,6 +31,7 @@ platform = espressif32 @3.3.0 monitor_filters = esp32_exception_decoder upload_speed = 921600 monitor_speed = 115200 +debug_tool = esp-prog build_src_filter = +<*.cpp> + @@ -89,6 +90,7 @@ build_src_filter = + + + + + + [env:esp32_4mb_fromitems] diff --git a/src/classes/IoTScenario.cpp b/src/classes/IoTScenario.cpp index e66d7a64..1b09eacc 100644 --- a/src/classes/IoTScenario.cpp +++ b/src/classes/IoTScenario.cpp @@ -46,7 +46,10 @@ class NumberExprAST : public ExprAST { IoTValue Val; public: - NumberExprAST(float val) { Val.valD = val; } + NumberExprAST(String val) { + Val.valD = strtod(val.c_str(), 0); + Val.valS = val; + } IoTValue *exec() { if (isIotScenException) return nullptr; @@ -624,7 +627,7 @@ int IoTScenario::gettok() { return tok_identifier; } - String NumStr=""; + NumStr=""; if (LastChar == '-') { LastChar = getLastChar(); if (isdigit(LastChar)) NumStr = "-"; @@ -637,7 +640,6 @@ int IoTScenario::gettok() { LastChar = getLastChar(); } while (isdigit(LastChar) || LastChar == '.'); - NumVal = strtod(NumStr.c_str(), 0); return tok_number; } @@ -788,7 +790,7 @@ ExprAST *IoTScenario::ParseIdentifierExpr(String *IDNames, bool callFromConditio /// numberexpr ::= number ExprAST *IoTScenario::ParseNumberExpr() { - ExprAST *Result = new NumberExprAST(NumVal); + ExprAST *Result = new NumberExprAST(NumStr); getNextToken(); // получаем число return Result; } diff --git a/src/modules/API.cpp b/src/modules/API.cpp index e570b3b6..9ee02105 100644 --- a/src/modules/API.cpp +++ b/src/modules/API.cpp @@ -23,6 +23,7 @@ void* getAPI_IoTServo(String subtype, String params); void* getAPI_Mcp23017(String subtype, String params); void* getAPI_Mp3(String subtype, String params); void* getAPI_Pwm8266(String subtype, String params); +void* getAPI_TelegramLT(String subtype, String params); void* getAPI_Lcd2004(String subtype, String params); void* getAPI(String subtype, String params) { @@ -50,6 +51,7 @@ if ((tmpAPI = getAPI_IoTServo(subtype, params)) != nullptr) return tmpAPI; if ((tmpAPI = getAPI_Mcp23017(subtype, params)) != nullptr) return tmpAPI; if ((tmpAPI = getAPI_Mp3(subtype, params)) != nullptr) return tmpAPI; if ((tmpAPI = getAPI_Pwm8266(subtype, params)) != nullptr) return tmpAPI; +if ((tmpAPI = getAPI_TelegramLT(subtype, params)) != nullptr) return tmpAPI; if ((tmpAPI = getAPI_Lcd2004(subtype, params)) != nullptr) return tmpAPI; return nullptr; } \ No newline at end of file diff --git a/src/modules/exec/Telegram/Telegram.cpp b/src/modules/exec/Telegram/Telegram.cpp index 6e48d84a..3ad5144e 100644 --- a/src/modules/exec/Telegram/Telegram.cpp +++ b/src/modules/exec/Telegram/Telegram.cpp @@ -3,23 +3,6 @@ #include "CTBot.h" -String uint64ToString(uint64_t input) { - String result = ""; - uint8_t base = 10; - - do { - char c = input % base; - input /= base; - - if (c < 10) - c +='0'; - else - c += 'A' - 10; - result = c + result; - } while (input); - return result; -} - class Telegram : public IoTItem { private: diff --git a/src/modules/exec/TelegramLT/TelegramLT.cpp b/src/modules/exec/TelegramLT/TelegramLT.cpp new file mode 100644 index 00000000..d3f13f71 --- /dev/null +++ b/src/modules/exec/TelegramLT/TelegramLT.cpp @@ -0,0 +1,82 @@ +#include "Global.h" +#include "classes/IoTItem.h" + +String _prevMsg = ""; +String _token; +unsigned long _chatID; + +class TelegramLT : public IoTItem +{ + +public: + TelegramLT(String parameters) : IoTItem(parameters) { + jsonRead(parameters, "token", _token); + jsonRead(parameters, "chatID", _chatID); + } + + void sendTelegramMsg(bool often, String msg) + { + if (WiFi.status() == WL_CONNECTED && (often || !often && _prevMsg != msg)) { + WiFiClient client; + HTTPClient http; + http.begin(client, "http://live-control.com/iotm/telegram.php"); + http.addHeader("Content-Type", "application/x-www-form-urlencoded"); + String httpRequestData = "url=https://api.telegram.org/bot" + _token + "/sendmessage?chat_id=" + uint64ToString(_chatID) + "&text=" + msg; + int httpResponseCode = http.POST(httpRequestData); + String payload = http.getString(); + SerialPrint("<-", F("Telegram"), "chat ID: " + uint64ToString(_chatID) + ", msg: " + msg); + SerialPrint("->", F("Telegram"), "chat ID: " + uint64ToString(_chatID) + ", server: " + httpResponseCode); + + if (!strstr(payload.c_str(), "{\"ok\":true")) { + value.valD = 1; + Serial.printf("Telegram error, msg from server: %s\n", payload.c_str()); + regEvent(value.valD, payload); + } else { + value.valD = 0; + } + http.end(); + _prevMsg = msg; + } + } + + IoTValue execute(String command, std::vector ¶m) + { + if (param.size() == 1) { + String strTmp; + if (param[0].isDecimal && param[0].valS == "") + strTmp = param[0].valD; + else + strTmp = param[0].valS; + + if (command == "sendMsg") + { + if (param.size()) + { + sendTelegramMsg(false, strTmp); + } + } + else if (command == "sendOftenMsg") + { + if (param.size()) + { + sendTelegramMsg(true, strTmp); + } + } + } + return {}; + } + + ~TelegramLT(){}; +}; + +void *getAPI_TelegramLT(String subtype, String param) +{ + if (subtype == F("TelegramLT")) + { + return new TelegramLT(param); + } + else + { + return nullptr; + } +} \ No newline at end of file diff --git a/src/modules/exec/TelegramLT/modinfo.json b/src/modules/exec/TelegramLT/modinfo.json new file mode 100644 index 00000000..4eeb7aab --- /dev/null +++ b/src/modules/exec/TelegramLT/modinfo.json @@ -0,0 +1,51 @@ +{ + "menuSection": "Исполнительные устройства", + + "configItem": [ + { + "name": "Телеграм-Лайт", + "type": "Writing", + "subtype": "TelegramLT", + "id": "tg", + "widget": "", + "page": "", + "descr": "", + "token": "", + "chatID": "" + } + ], + + "about": { + "authorName": "AVAKS", + "authorContact": "https://t.me/@avaks_dev", + "authorGit": "https://github.com/avaksru", + "specialThanks": "", + "moduleName": "TelegramLT", + "moduleVersion": "1.0", + "moduleDesc": "Только отправка уведомлений в телеграм о событиях. Модуль занимает значительно меньше памяти в ESP по сравнению со стандартным. Внимание! для отправки сообщений используется промежуточный сервер http://live-control.com", + "propInfo": { + "token": "Токен для авторизации бота в системе Telegram", + "chatID": "ИД диалога с контактом. Необходим для отправки сообщений именно вам. Найти можно так: https://webhamster.ru/mytetrashare/index/mtb339/157520247213ix05mbe2" + }, + "retInfo": "Элемент данного модуля может иметь два значения 0 - все хорошо, 1 - произошла ошибка отправки сообщения, подробности в консоли. Данный статус можно использовать в сценарии для совершения экстренных действий при ошибке.", + "funcInfo": [ + { + "name": "sendMsg", + "descr": "Отправить сообщение без повторений.", + "params": ["Сообщение, может быть строкой, числом или ИД другого элемента для получения значения"] + }, + { + "name": "sendOftenMsg", + "descr": "Отправить сообщение в любом случае, даж если отправляли такое ранее.", + "params": ["Сообщение, может быть строкой, числом или ИД другого элемента для получения значения"] + } + ] + }, + + "defActive": true, + + "devices": { + "esp32_4mb": [], + "esp8266_4mb": [] + } +} diff --git a/src/utils/StringUtils.cpp b/src/utils/StringUtils.cpp index 8dc18410..16717fc2 100644 --- a/src/utils/StringUtils.cpp +++ b/src/utils/StringUtils.cpp @@ -176,3 +176,20 @@ String prettyBytes(size_t size) { else return String(size / 1024.0 / 1024.0 / 1024.0) + "GB"; } + +String uint64ToString(uint64_t input) { + String result = ""; + uint8_t base = 10; + + do { + char c = input % base; + input /= base; + + if (c < 10) + c +='0'; + else + c += 'A' - 10; + result = c + result; + } while (input); + return result; +}