Telegram V2 & espCAM

This commit is contained in:
Mit4el
2023-10-02 21:29:02 +03:00
parent 8eb719ea6c
commit 0e679f132d
88 changed files with 527 additions and 446 deletions

View File

@@ -46,6 +46,7 @@
"defActive": true,
"usedLibs": {
"esp32_4mb": [],
"esp32cam_4mb": [],
"esp32_16mb": [],
"esp32s2_4mb": [],
"esp8266_4mb": [],

View File

@@ -45,6 +45,7 @@
"defActive": true,
"usedLibs": {
"esp32_4mb": [],
"esp32cam_4mb": [],
"esp32_16mb": [],
"esp32s2_4mb": [],
"esp8266_4mb": [],

View File

@@ -104,6 +104,7 @@
"defActive": true,
"usedLibs": {
"esp32_4mb": [],
"esp32cam_4mb": [],
"esp8266_4mb": [],
"esp8266_1mb": [],
"esp8266_1mb_ota": [],

View File

@@ -46,6 +46,9 @@
"esp32_4mb": [
"gyverlibs/EncButton @ ^2.0"
],
"esp32cam_4mb": [
"gyverlibs/EncButton @ ^2.0"
],
"esp8266_4mb": [
"gyverlibs/EncButton @ ^2.0"
],

View File

@@ -3,64 +3,108 @@
#include "NTP.h"
#include "esp_camera.h"
#include "soc/soc.h" // Disable brownour problems
#include "soc/rtc_cntl_reg.h" // Disable brownour problems
#include "soc/soc.h" // Disable brownour problems
#include "soc/rtc_cntl_reg.h" // Disable brownour problems
#include "FS.h" // SD Card ESP32
#include "SD_MMC.h" // SD Card ESP32
#include "FS.h" // SD Card ESP32
#include "SD_MMC.h" // SD Card ESP32
void handleGetPic();
// ===================
// Select camera model
// ===================
//#define CAMERA_MODEL_WROVER_KIT // Has PSRAM
//#define CAMERA_MODEL_ESP_EYE // Has PSRAM
//#define CAMERA_MODEL_ESP32S3_EYE // Has PSRAM
//#define CAMERA_MODEL_M5STACK_PSRAM // Has PSRAM
//#define CAMERA_MODEL_M5STACK_V2_PSRAM // M5Camera version B Has PSRAM
//#define CAMERA_MODEL_M5STACK_WIDE // Has PSRAM
//#define CAMERA_MODEL_M5STACK_ESP32CAM // No PSRAM
//#define CAMERA_MODEL_M5STACK_UNITCAM // No PSRAM
// #define CAMERA_MODEL_WROVER_KIT // Has PSRAM
// #define CAMERA_MODEL_ESP_EYE // Has PSRAM
// #define CAMERA_MODEL_ESP32S3_EYE // Has PSRAM
// #define CAMERA_MODEL_M5STACK_PSRAM // Has PSRAM
// #define CAMERA_MODEL_M5STACK_V2_PSRAM // M5Camera version B Has PSRAM
// #define CAMERA_MODEL_M5STACK_WIDE // Has PSRAM
// #define CAMERA_MODEL_M5STACK_ESP32CAM // No PSRAM
// #define CAMERA_MODEL_M5STACK_UNITCAM // No PSRAM
#define CAMERA_MODEL_AI_THINKER // Has PSRAM
//#define CAMERA_MODEL_TTGO_T_JOURNAL // No PSRAM
//#define CAMERA_MODEL_XIAO_ESP32S3 // Has PSRAM
// ** Espressif Internal Boards **
//#define CAMERA_MODEL_ESP32_CAM_BOARD
//#define CAMERA_MODEL_ESP32S2_CAM_BOARD
//#define CAMERA_MODEL_ESP32S3_CAM_LCD
// #define CAMERA_MODEL_TTGO_T_JOURNAL // No PSRAM
// #define CAMERA_MODEL_XIAO_ESP32S3 // Has PSRAM
// ** Espressif Internal Boards **
// #define CAMERA_MODEL_ESP32_CAM_BOARD
// #define CAMERA_MODEL_ESP32S2_CAM_BOARD
// #define CAMERA_MODEL_ESP32S3_CAM_LCD
#define LED_LEDC_CHANNEL 2 //Using different ledc channel/timer than camera
#define LED_LEDC_CHANNEL 2 // Using different ledc channel/timer than camera
#define CONFIG_LED_MAX_INTENSITY 255
#include "camera_pins.h"
IoTItem* globalItem = nullptr;
class EspCam : public IoTItem {
private:
IoTItem *_camItem = nullptr;
camera_fb_t *frame = NULL;
class EspCam : public IoTItem
{
private:
bool _useLed, _ticker, _webTicker, _initSD;
public:
public:
bool isUsedLed() { return _useLed; }
bool isWebTicker() { return _webTicker; }
EspCam(String parameters): IoTItem(parameters) {
WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); //disable brownout detector
EspCam(String parameters) : IoTItem(parameters)
{
jsonRead(parameters, "useLed", _useLed); // используем = 1 или нет = 0 подсветку (вспышку)
if (_useLed) {
jsonRead(parameters, "ticker", _ticker); // тикать = 1 - сообщаем всем, что сделали снимок и он готов
jsonRead(parameters, "webTicker", _webTicker); // сообщать всем, что через веб попросили отдать картинку с камеры
jsonRead(parameters, "flashOn", _useLed); // используем = 1 или нет = 0 подсветку (вспышку)
// globalItem = this; // выносим адрес переменной экземпляра для доступа к данным из обработчика событий веб
_camItem = this;
initCam();
HTTP.on("/getpic", HTTP_GET, handleGetPic);
initSD();
}
void doByInterval()
{
// save_picture();
}
IoTValue execute(String command, std::vector<IoTValue> &param)
{
if (command == "save")
{
if (param.size() == 1)
save_picture(param[0].valS);
else
save_picture();
}
else if (command == "flashOn" && param.size() == 1)
{
ledcSetup(LED_LEDC_CHANNEL, 5000, 8);
ledcAttachPin(LED_GPIO_NUM, LED_LEDC_CHANNEL);
_useLed = true;
}
else if (command == "flashOff")
{
_useLed = false;
}
else if (command == "sendFoto")
{
sendFoto();
}
else if (command == "editFoto")
{
editFoto();
}
jsonRead(parameters, "ticker", _ticker); // тикать = 1 - сообщаем всем, что сделали снимок и он готов
jsonRead(parameters, "webTicker", _webTicker); // сообщать всем, что через веб попросили отдать картинку с камеры
globalItem = this; // выносим адрес переменной экземпляра для доступа к данным из обработчика событий веб
return {};
}
/*
IoTItem *getCAMDriver()
{
return this;
}
*/
void initCam()
{
WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); // disable brownout detector
camera_config_t config;
config.ledc_channel = LEDC_CHANNEL_0;
config.ledc_timer = LEDC_TIMER_0;
@@ -83,110 +127,141 @@ class EspCam : public IoTItem {
config.xclk_freq_hz = 20000000;
config.frame_size = FRAMESIZE_UXGA;
config.pixel_format = PIXFORMAT_JPEG; // for streaming
//config.pixel_format = PIXFORMAT_RGB565; // for face detection/recognition
// config.pixel_format = PIXFORMAT_RGB565; // for face detection/recognition
config.grab_mode = CAMERA_GRAB_WHEN_EMPTY;
config.fb_location = CAMERA_FB_IN_PSRAM;
config.jpeg_quality = 12;
config.fb_count = 1;
// if PSRAM IC present, init with UXGA resolution and higher JPEG quality
// for larger pre-allocated frame buffer.
if(psramFound()){
if (psramFound())
{
config.jpeg_quality = 10;
config.fb_count = 2;
config.grab_mode = CAMERA_GRAB_LATEST;
} else {
}
else
{
// Limit the frame size when PSRAM is not available
config.frame_size = FRAMESIZE_SVGA;
config.fb_location = CAMERA_FB_IN_DRAM;
}
#if defined(CAMERA_MODEL_ESP_EYE)
#if defined(CAMERA_MODEL_ESP_EYE)
pinMode(13, INPUT_PULLUP);
pinMode(14, INPUT_PULLUP);
#endif
#endif
// camera init
esp_err_t err = esp_camera_init(&config);
if (err != ESP_OK) {
if (err != ESP_OK)
{
Serial.printf("Camera init failed with error 0x%x", err);
return;
}
sensor_t * s = esp_camera_sensor_get();
sensor_t *s = esp_camera_sensor_get();
// initial sensors are flipped vertically and colors are a bit saturated
if (s->id.PID == OV3660_PID) {
s->set_vflip(s, 1); // flip it back
s->set_brightness(s, 1); // up the brightness just a bit
if (s->id.PID == OV3660_PID)
{
s->set_vflip(s, 1); // flip it back
s->set_brightness(s, 1); // up the brightness just a bit
s->set_saturation(s, -2); // lower the saturation
}
#if defined(CAMERA_MODEL_M5STACK_WIDE) || defined(CAMERA_MODEL_M5STACK_ESP32CAM)
if (_useLed)
{
ledcSetup(LED_LEDC_CHANNEL, 5000, 8);
ledcAttachPin(LED_GPIO_NUM, LED_LEDC_CHANNEL);
}
#if defined(CAMERA_MODEL_M5STACK_WIDE) || defined(CAMERA_MODEL_M5STACK_ESP32CAM)
s->set_vflip(s, 1);
s->set_hmirror(s, 1);
#endif
#endif
#if defined(CAMERA_MODEL_ESP32S3_EYE)
#if defined(CAMERA_MODEL_ESP32S3_EYE)
s->set_vflip(s, 1);
#endif
HTTP.on("/getpic", HTTP_GET, handleGetPic);
#endif
}
void initSD()
{
// Start Micro SD card
_initSD = true;
Serial.println("Starting SD Card");
if(!SD_MMC.begin("/sdcard", true)){
if (!SD_MMC.begin("/sdcard", true))
{
Serial.println("SD Card Mount Failed");
_initSD = false;
return;
}
uint8_t cardType = SD_MMC.cardType();
if(cardType == CARD_NONE){
if (cardType == CARD_NONE)
{
Serial.println("No SD Card attached");
_initSD = false;
return;
}
fs::FS &fs = SD_MMC;
fs.mkdir("/photos/");
fs.mkdir("/photos");
}
void save_picture(String path = "") {
// if (_useLed) digitalWrite(4, HIGH); //Turn on the flash
void sendFoto()
{
if (tlgrmItem)
{
if (_useLed)
ledcWrite(LED_LEDC_CHANNEL, CONFIG_LED_MAX_INTENSITY); // Turn on the flash
frame = esp_camera_fb_get();
if (!frame)
{
SerialPrint("E", F("Esp-Cam to Telegram"), "Fail esp-cam initialization");
return;
}
if (_useLed)
ledcWrite(LED_LEDC_CHANNEL, 0);
(tlgrmItem)->sendFoto((byte *)frame->buf, frame->len, "photo.jpg");
esp_camera_fb_return(frame);
SerialPrint("i", F("Esp-Cam to Telegram"), "esp_CAM send foto");
}
}
// // Take Picture with Camera
// fb = esp_camera_fb_get();
// if(!fb || fb->len >= PICBUF_SIZE) {
// if (fb) {
// Serial.printf("Camera capture failed size=%d\n", fb->len);
// esp_camera_fb_return(fb);
// } else Serial.printf("Camera capture failed\n");
// return;
// }
// // if (value.extBinInfoSize < fb->len) {
// // if (value.extBinInfo) free(value.extBinInfo);
// // value.extBinInfo = (uint8_t*)malloc(sizeof(uint8_t) * fb->len);
// // }
// memcpy(value.extBinInfo, fb->buf, fb->len);
// value.extBinInfoSize = fb->len;
// Serial.printf("try send pic by size=%d", fb->len);
// if (_useLed) digitalWrite(4, LOW);
// if (_ticker) regEvent("shot", "EspCam");
// esp_camera_fb_return(fb);
void editFoto()
{
if (tlgrmItem)
{
if (_useLed)
ledcWrite(LED_LEDC_CHANNEL, CONFIG_LED_MAX_INTENSITY); // Turn on the flash
frame = esp_camera_fb_get();
if (!frame)
{
SerialPrint("E", F("Esp-Cam to Telegram"), "Fail esp-cam initialization");
return;
}
if (_useLed)
ledcWrite(LED_LEDC_CHANNEL, 0);
(tlgrmItem)->editFoto((byte *)frame->buf, frame->len, "photo.jpg");
esp_camera_fb_return(frame);
SerialPrint("i", F("Esp-Cam to Telegram"), "esp_CAM edit foto");
}
}
void save_picture(String path = "")
{
// Save picture to microSD card
fs::FS &fs = SD_MMC;
if (path == "") {
if (path == "")
{
path = "/photos/";
path += getTodayDateDotFormated();
path += "/";
path += getTodayDateDotFormated();
// path += "/";
fs.mkdir(path.c_str());
char buf[32];
@@ -196,79 +271,78 @@ class EspCam : public IoTItem {
}
Serial.println(path);
// Take Picture with Camera
camera_fb_t * fb = esp_camera_fb_get();
if (_useLed)
ledcWrite(LED_LEDC_CHANNEL, CONFIG_LED_MAX_INTENSITY); // Turn on the flash
if(!fb) {
// Take Picture with Camera
frame = esp_camera_fb_get();
if (_useLed)
ledcWrite(LED_LEDC_CHANNEL, 0); // Turn on the flash
if (!frame)
{
Serial.println("Camera capture failed");
return;
}
File file = fs.open(path.c_str(), FILE_WRITE);
if(!file){
if (!file)
{
Serial.println("Failed to open file in writing mode");
}
else {
file.write(fb->buf, fb->len); // payload (image), payload length
}
else
{
file.write(frame->buf, frame->len); // payload (image), payload length
Serial.printf("Saved file to path: %s\n", path.c_str());
}
file.close();
//return the frame buffer back to the driver for reuse
esp_camera_fb_return(fb);
// return the frame buffer back to the driver for reuse
esp_camera_fb_return(frame);
}
void doByInterval() {
//save_picture();
}
IoTValue execute(String command, std::vector<IoTValue> &param) {
if (command == "save") {
if (param.size() == 1)
save_picture(param[0].valS);
else
save_picture();
} else if (command == "ledOn" && param.size() == 1) {
ledcSetup(LED_LEDC_CHANNEL, 5000, 8);
ledcAttachPin(LED_GPIO_NUM, LED_LEDC_CHANNEL);
ledcWrite(LED_LEDC_CHANNEL, param[0].valD);
} else if (command == "ledOff") {
ledcWrite(LED_LEDC_CHANNEL, 0);
}
return {};
}
~EspCam() {
//free(value.extBinInfo);
globalItem = nullptr;
~EspCam()
{
// free(value.extBinInfo);
_camItem = nullptr;
};
};
void handleGetPic() {
if (!globalItem) return;
void handleGetPic()
{
if (!_camItem)
return;
if (((EspCam*)globalItem)->isUsedLed()) ledcWrite(LED_LEDC_CHANNEL, CONFIG_LED_MAX_INTENSITY); //Turn on the flash
if (((EspCam *)_camItem)->isUsedLed())
ledcWrite(LED_LEDC_CHANNEL, CONFIG_LED_MAX_INTENSITY); // Turn on the flash
camera_fb_t* fb = NULL;
fb = esp_camera_fb_get();
if (!fb) {
// camera_fb_t *fb = NULL;
frame = esp_camera_fb_get();
if (((EspCam *)_camItem)->isUsedLed())
ledcWrite(LED_LEDC_CHANNEL, 0);
if (!frame)
{
HTTP.send(200, "text/json", F("Item EspCam not prepared yet or camera hasn't taken a picture yet"));
return;
}
HTTP.send_P(200, "image/jpeg", (char *)fb->buf, fb->len);
if (((EspCam*)globalItem)->isUsedLed()) ledcWrite(LED_LEDC_CHANNEL, 0);
if (((EspCam*)globalItem)->isWebTicker()) globalItem->regEvent("webTakesPhoto", "EspCam");
esp_camera_fb_return(fb);
HTTP.send_P(200, "image/jpeg", (char *)frame->buf, frame->len);
if (((EspCam *)_camItem)->isWebTicker())
_camItem->regEvent("webTakesPhoto", "EspCam");
esp_camera_fb_return(frame);
}
void* getAPI_EspCam(String subtype, String param) {
if (subtype == F("EspCam")) {
void *getAPI_EspCam(String subtype, String param)
{
if (subtype == F("EspCam"))
{
return new EspCam(param);
} else {
}
else
{
return nullptr;
}
}

View File

@@ -11,7 +11,7 @@
"page": "",
"descr": "",
"int": 60,
"useLed": 0,
"flashOn": 0,
"ticker": 0,
"webTicker": 0
}
@@ -28,10 +28,10 @@
"esp8266_4mb": 15
},
"title": "Camera OV2640 (ESPcam)",
"moduleDesc": "Предназначен для специальной платы esp32 со встроенной камерой. Добавляет в прошивку функцию создания фото и сохранения на SD при наличии. По адресу /getpic можно получить текущее фото (работает в том числе без SD карты).",
"moduleDesc": "Предназначен для специальной платы esp32 со встроенной камерой. Добавляет в прошивку функцию создания фото и сохранения на SD при наличии. По адресу /getpic можно получить текущее фото (работает в том числе без SD карты). Отправка фото в телеграмм через модуль Telegram_v2",
"propInfo": {
"int": "Пауза в секундах во время постоянной фотосъемки.",
"useLed": "использовать диод подсветки при съемке.",
"flashOn": "использовать диод подсветки при съемке. используем = 1 или нет = 0 подсветку (вспышку)",
"ticker": "Генерировать(1) или нет(0) событие с интервалом int",
"webTicker": "Генерировать(1) или нет(0) событие при обращении через веб-страницу по адресу /getpic."
},
@@ -41,6 +41,16 @@
"descr": "Сохранить снимок на SD",
"params": []
},
{
"name": "sendFoto",
"descr": "Отправить фото с esp-CAM в телеграмм",
"params": [""]
},
{
"name": "editFoto",
"descr": "Отредактировать последнее отправленное фото в телеграмм",
"params": [""]
},
{
"name": "ledOn",
"descr": "Включить подсветку",
@@ -57,7 +67,7 @@
},
"defActive": false,
"usedLibs": {
"esp32_4mb": [
"esp32cam_4mb": [
"espressif/esp32-camera @ ^2.0.0"
]
}

View File

@@ -35,6 +35,7 @@
"defActive": false,
"usedLibs": {
"esp32_4mb": [],
"esp32cam_4mb": [],
"esp32_16mb": [],
"esp32s2_4mb": [],
"esp8266_4mb": [],

View File

@@ -50,6 +50,7 @@
"defActive": false,
"usedLibs": {
"esp32_4mb": [],
"esp32cam_4mb": [],
"esp32s2_4mb": [],
"esp8266_4mb": [],
"esp8266_1mb": [],

View File

@@ -51,6 +51,9 @@
"esp32_4mb": [
"https://github.com/RoboticsBrno/ServoESP32#v1.0.3"
],
"esp32cam_4mb": [
"https://github.com/RoboticsBrno/ServoESP32#v1.0.3"
],
"esp8266_4mb": []
}
}

View File

@@ -40,6 +40,10 @@
"adafruit/Adafruit Mcp23017 Arduino Library@^2.1.0",
"adafruit/Adafruit BusIO @ ^1.13.2"
],
"esp32cam_4mb": [
"adafruit/Adafruit Mcp23017 Arduino Library@^2.1.0",
"adafruit/Adafruit BusIO @ ^1.13.2"
],
"esp8266_4mb": [
"adafruit/Adafruit Mcp23017 Arduino Library@^2.1.0",
"adafruit/Adafruit BusIO @ ^1.13.2"

View File

@@ -40,6 +40,10 @@
"adafruit/Adafruit MCP23017 Arduino Library@^2.1.0",
"adafruit/Adafruit BusIO @ ^1.13.2"
],
"esp32cam_4mb": [
"adafruit/Adafruit MCP23017 Arduino Library@^2.1.0",
"adafruit/Adafruit BusIO @ ^1.13.2"
],
"esp8266_4mb": [
"adafruit/Adafruit MCP23017 Arduino Library@^2.1.0",
"adafruit/Adafruit BusIO @ ^1.13.2"

View File

@@ -92,6 +92,9 @@
"esp32_4mb": [
"dfrobot/DFRobotDFPlayerMini @ ^1.0.5"
],
"esp32cam_4mb": [
"dfrobot/DFRobotDFPlayerMini @ ^1.0.5"
],
"esp8266_4mb": [
"dfrobot/DFRobotDFPlayerMini @ ^1.0.5"
]

View File

@@ -44,6 +44,7 @@
"defActive": true,
"usedLibs": {
"esp32_4mb": [],
"esp32cam_4mb": [],
"esp8266_4mb": [],
"esp8266_1mb": [],
"esp8266_1mb_ota": [],

View File

@@ -49,6 +49,7 @@
},
"defActive": false,
"usedLibs": {
"esp32_4mb": []
"esp32_4mb": [],
"esp32cam_4mb": []
}
}

View File

@@ -35,6 +35,9 @@
"esp32_4mb": [
"adafruit/Adafruit BusIO @ ^1.13.2"
],
"esp32cam_4mb": [
"adafruit/Adafruit BusIO @ ^1.13.2"
],
"esp8266_4mb": [
"adafruit/Adafruit BusIO @ ^1.13.2"
],

View File

@@ -44,6 +44,7 @@
},
"defActive": true,
"usedLibs": {
"esp32_4mb": []
"esp32_4mb": [],
"esp32cam_4mb": []
}
}

View File

@@ -34,6 +34,9 @@
"usedLibs": {
"esp32_4mb": [
"espressif/esp32-camera @ ^2.0.0"
],
"esp32cam_4mb": [
"espressif/esp32-camera @ ^2.0.0"
]
}
}

View File

@@ -33,6 +33,7 @@
"defActive": false,
"usedLibs": {
"esp32_4mb": [],
"esp32cam_4mb": [],
"esp8266_4mb": []
}
}

View File

@@ -58,6 +58,9 @@
"esp32_4mb": [
"CTBot @2.1.9"
],
"esp32cam_4mb": [
"CTBot @2.1.9"
],
"esp32_16mb": [
"CTBot @2.1.9"
],

View File

@@ -1,210 +0,0 @@
#include "Global.h"
#include "classes/IoTItem.h"
//#define FB_NO_UNICODE
//#define FB_NO_URLENCODE
//#define FB_NO_OTA
//#define FB_DYNAMIC
//#include <GyverGFX.h>
//#include <CharPlot.h>
#include <FastBot.h>
#include <vector>
// FastBot _myBot;
FastBot *_myBot = nullptr;
FastBot *instanceBot()
{
if (!_myBot)
{
_myBot = new FastBot();
// ot->begin();
}
return _myBot;
}
String _token;
String _chatID;
bool _autos;
class TelegramFast : public IoTItem
{
private:
bool _receiveMsg;
String _prevMsg = "";
public:
TelegramFast(String parameters) : IoTItem(parameters)
{
jsonRead(parameters, "token", _token);
jsonRead(parameters, "autos", _autos);
jsonRead(parameters, "receiveMsg", _receiveMsg);
jsonRead(parameters, "chatID", _chatID);
instanceBot();
_myBot->attach(telegramMsgParse);
#ifdef ESP32
// _myBot->useDNS(true);
#endif
_myBot->setToken(_token);
// _myBot->enableUTF8Encoding(true);
}
void loop()
{
if (_receiveMsg)
{
_myBot->tick();
}
// Далее вызов doByInterval для обработки комманд
if (enableDoByInt)
{
currentMillis = millis();
difference = currentMillis - prevMillis;
if (difference >= _interval)
{
prevMillis = millis();
this->doByInterval();
}
}
}
void doByInterval()
{
}
IoTValue execute(String command, std::vector<IoTValue> &param)
{
if (command == "sendMsg")
{
if (param.size())
{
String strTmp;
if (param[0].isDecimal)
strTmp = param[0].valD;
else
strTmp = param[0].valS;
sendTelegramMsg(false, strTmp);
}
}
else if (command == "sendOftenMsg")
{
if (param.size())
{
String strTmp;
if (param[0].isDecimal)
strTmp = param[0].valD;
else
strTmp = param[0].valS;
sendTelegramMsg(true, strTmp);
}
}
return {};
}
void static telegramMsgParse(FB_msg &msg)
{
// FB_msg msg;
SerialPrint("->", F("Telegram"), "chat ID: " + msg.chatID + ", msg: " + msg.text);
// _myBot->setChatID(_chatID);
if (_autos)
{
_chatID = msg.chatID;
}
if (msg.text.indexOf("set") != -1)
{
msg.text = deleteBeforeDelimiter(msg.text, "_");
generateOrder(selectToMarker(msg.text, "_"), selectToMarkerLast(msg.text, "_"));
_myBot->replyMessage("order done", msg.messageID, _chatID);
SerialPrint("<-", F("Telegram"), "chat ID: " + _chatID + ", msg: " + String(msg.text));
}
else if (msg.text.indexOf("get") != -1)
{
msg.text = deleteBeforeDelimiter(msg.text, "_");
IoTItem *item = findIoTItem(msg.text);
if (item)
{
_myBot->replyMessage(item->getValue(), msg.messageID, _chatID);
SerialPrint("<-", F("Telegram"), "chat ID: " + _chatID + ", msg: " + String(msg.text));
}
}
else if (msg.text.indexOf("all") != -1)
{
// String list = returnListOfParams();
String out;
std::vector<float> vctr;
for (std::list<IoTItem *>::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it)
{
if ((*it)->iAmLocal)
{
out = out + (*it)->getID() + ": " + (*it)->getValue() + "\n";
vctr.push_back(atoff((*it)->getValue().c_str()));
// _myBot->sendMessage((*it)->getID() + ": " + (*it)->getValue(), _chatID);
}
}
//_myBot->sendMessage(list, _chatID);
SerialPrint("<-", F("Telegram"), "chat ID: " + _chatID + "\n" + out);
// _myBot->sendMessage(CharPlot<LINE_X2>(&vctr[0], vctr.size(), 5), _chatID);
// SerialPrint("<-", F("Telegram"), CharPlot<LINE_X2>(&vctr[0], vctr.size(), 10));
}
else if (msg.text.indexOf("help") != -1)
{
_myBot->sendMessage("ID: " + chipId, _chatID);
_myBot->sendMessage("chatID: " + _chatID, _chatID);
_myBot->sendMessage(F("Wrong order, use /all to get all values, /get_id to get value, or /set_id_value to set value"), _chatID);
}
else
{
// setValue(msg.text);
}
}
/*
String static returnListOfParams()
{
String out;
for (std::list<IoTItem *>::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it)
{
if ((*it)->iAmLocal)
out = out + (*it)->getID() + ": " + (*it)->getValue() + "\n";
}
return out;
}
*/
void sendTelegramMsg(bool often, String msg)
{
if (often)
{
_myBot->sendMessage(msg, _chatID);
SerialPrint("<-", F("Telegram"), "chat ID: " + _chatID + ", msg: " + msg);
}
else
{
if (_prevMsg != msg)
{
_prevMsg = msg;
_myBot->sendMessage(msg, _chatID);
SerialPrint("<-", F("Telegram"), "chat ID: " + _chatID + ", msg: " + msg);
}
}
}
~TelegramFast(){
};
};
void *getAPI_TelegramFast(String subtype, String param)
{
if (subtype == F("TelegramFast"))
{
return new TelegramFast(param);
}
else
{
return nullptr;
}
}

View File

@@ -1,72 +0,0 @@
{
"menuSection": "executive_devices",
"configItem": [{
"global": 0,
"name": "Телеграм-Бот v2",
"type": "Writing",
"subtype": "TelegramFast",
"id": "tg",
"widget": "",
"page": "",
"descr": "",
"int": 10,
"token": "",
"autos": 1,
"receiveMsg": 0,
"chatID": ""
}],
"about": {
"authorName": "Mikhail Bubnov",
"authorContact": "https://t.me/Mit4bmw",
"authorGit": "https://github.com/Mit4el",
"specialThanks": "",
"moduleName": "TelegramFast",
"moduleVersion": "1.0",
"usedRam": {
"esp32_4mb": 37,
"esp8266_4mb": 37
},
"title": "Телеграм-Бот",
"moduleDesc": "Добавляет возможность отправлять сообщения от имени бота контакту в Телеграм-чате и получать команды.",
"propInfo": {
"token": "Токен для авторизации бота в системе Telegram",
"autos": "Автоматически(1) или нет(0) запоминать ChatID по входящим сообщениям. Т.е. бот будет информировать тех, кто последний прислал сообщение.",
"receiveMsg": "Обрабатывать(1) или нет(0) входящие сообщения.",
"chatID": "ИД диалога с контактом. Необходим для отправки сообщений именно вам."
},
"funcInfo": [
{
"name": "sendMsg",
"descr": "Отправить сообщение без повторений.",
"params": ["Сообщение, может быть строкой, числом или ИД другого элемента для получения значения"]
},
{
"name": "sendOftenMsg",
"descr": "Отправить сообщение в любом случае, даж если отправляли такое ранее.",
"params": ["Сообщение, может быть строкой, числом или ИД другого элемента для получения значения"]
}
]
},
"defActive": false,
"usedLibs": {
"esp32_4mb": [
"gyverlibs/FastBot"
],
"esp32s2_4mb": [
"gyverlibs/GyverGFX",
"gyverlibs/CharDisplay",
"gyverlibs/FastBot"
],
"esp32_16mb": [
"gyverlibs/FastBot"
],
"esp8266_4mb": [
"gyverlibs/FastBot"
]
}
}

View File

@@ -52,6 +52,7 @@
"defActive": true,
"usedLibs": {
"esp32_4mb": [],
"esp32cam_4mb": [],
"esp32_16mb": [],
"esp32s2_4mb": [],
"esp8266_4mb": [],

View File

@@ -1,12 +1,13 @@
#include "Global.h"
#include "classes/IoTItem.h"
// #define FB_NO_UNICODE
// #define FB_NO_URLENCODE
// #define FB_NO_OTA
// #define FB_DYNAMIC
// #include <GyverGFX.h>
// #include <CharPlot.h>
// #include "esp_camera.h"
#include <FastBot.h>
#include <vector>
@@ -25,12 +26,14 @@ FastBot *instanceBot()
String _token;
String _chatID;
bool _autos;
bool _initSD;
class Telegram_v2 : public IoTItem
{
private:
bool _receiveMsg;
String _prevMsg = "";
bool _useLed = false;
public:
Telegram_v2(String parameters) : IoTItem(parameters)
@@ -243,13 +246,15 @@ public:
{
String path = '/' + msg.fileName; // вида /filename.xxx
auto file = FileFS.open(path, FILE_WRITE); // открываем для записи
if(!_myBot->downloadFile(file, msg.fileUrl))
_myBot->sendMessage("Downloading from: " + _chatID + ", file: " + String(msg.fileName), _chatID);
if (!_myBot->downloadFile(file, msg.fileUrl))
{
SerialPrint("X", F("Telegram"), "download from: error write" );
SerialPrint("X", F("Telegram"), "download from: error write");
_myBot->sendMessage("Download Fail", _chatID);
return;
}
SerialPrint("<-", F("Telegram"), "download from: " + _chatID + ", file: " + String(msg.fileUrl));
_myBot->sendMessage("download from: " + _chatID + ", file: " + String(msg.fileName), _chatID);
_myBot->sendMessage("Download Ok", _chatID);
}
}
else if (msg.text.indexOf("help") != -1)
@@ -293,8 +298,25 @@ public:
}
}
~Telegram_v2(){
void sendFoto(uint8_t *buf, uint32_t length, const String &name)
{
_myBot->sendFile(buf, length, FB_PHOTO, name, _chatID);
SerialPrint("<-", F("Telegram"), "chat ID: " + _chatID + ", send foto from esp-cam");
}
void editFoto(uint8_t *buf, uint32_t length, const String &name)
{
_myBot->editFile(buf, length, FB_PHOTO, name, _myBot->lastBotMsg(), _chatID);
SerialPrint("<-", F("Telegram"), "chat ID: " + _chatID + ", edit foto from esp-cam");
}
IoTItem* getTlgrmDriver() {
return this;
}
~Telegram_v2(){
tlgrmItem = nullptr;
};
};

View File

@@ -67,8 +67,7 @@
"name": "editFile",
"descr": "Отредактировать последний отправленный файл, с указанием типа файла: 0-фото, 1-аудио, 2-документ, 3-видео, 4-анимация, 5-голос",
"params": ["Путь к файлу (/test.png)", "Тип файла/информации (число)"]
}
}
]
},
@@ -78,6 +77,9 @@
"esp32_4mb": [
"gyverlibs/FastBot"
],
"esp32cam_4mb": [
"gyverlibs/FastBot"
],
"esp32s2_4mb": [
"gyverlibs/FastBot"
],

View File

@@ -134,6 +134,7 @@
"defActive": false,
"usedLibs": {
"esp32_4mb": [],
"esp32cam_4mb": [],
"esp8266_4mb": [],
"esp8266_1mb": [],
"esp8266_1mb_ota": [],