#include <WiFi.h>
#include <WiFiClientSecure.h>
#define ARDUINOJSON_DECODE_UNICODE 1
#define ARDUINOJSON_USE_LONG_LONG 1
#include <Arduino.h>
#include <ArduinoJson.h>
#include <Client.h>
#include <TelegramCertificate.h>
#define TELEGRAM_HOST "api.telegram.org"
#define TELEGRAM_SSL_PORT 443
#define HANDLE_MESSAGES 1
//unmark following line to enable debug mode
//#define _debug
typedef bool (*MoreDataAvailable)();
typedef byte (*GetNextByte)();
typedef byte* (*GetNextBuffer)();
typedef int (GetNextBufferLen)();
struct telegramMessage {
String text;
String chat_id;
String chat_title;
String from_id;
String from_name;
String date;
String type;
String file_caption;
String file_path;
String file_name;
bool hasDocument;
long file_size;
float longitude;
float latitude;
int update_id;
int message_id;
int reply_to_message_id;
String reply_to_text;
String query_id;
};
class UniversalTelegramBot {
public:
UniversalTelegramBot(const String& token, Client &client);
void updateToken(const String& token);
String getToken();
String sendGetToTelegram(const String& command);
String sendPostToTelegram(const String& command, JsonObject payload);
String
sendMultipartFormDataToTelegram(const String& command, const String& binaryPropertyName,
const String& fileName, const String& contentType,
const String& chat_id, int fileSize,
MoreDataAvailable moreDataAvailableCallback,
GetNextByte getNextByteCallback,
GetNextBuffer getNextBufferCallback,
GetNextBufferLen getNextBufferLenCallback);
bool readHTTPAnswer(String &body, String &headers);
bool getMe();
bool sendSimpleMessage(const String& chat_id, const String& text, const String& parse_mode);
bool sendMessage(const String& chat_id, const String& text, const String& parse_mode = "", int message_id = 0);
bool sendMessageWithReplyKeyboard(const String& chat_id, const String& text,
const String& parse_mode, const String& keyboard,
bool resize = false, bool oneTime = false,
bool selective = false);
bool sendMessageWithInlineKeyboard(const String& chat_id, const String& text,
const String& parse_mode, const String& keyboard, int message_id = 0);
bool sendChatAction(const String& chat_id, const String& text);
bool sendPostMessage(JsonObject payload, bool edit = false);
String sendPostPhoto(JsonObject payload);
String sendPhotoByBinary(const String& chat_id, const String& contentType, int fileSize,
MoreDataAvailable moreDataAvailableCallback,
GetNextByte getNextByteCallback,
GetNextBuffer getNextBufferCallback,
GetNextBufferLen getNextBufferLenCallback);
String sendPhoto(const String& chat_id, const String& photo, const String& caption = "",
bool disable_notification = false,
int reply_to_message_id = 0, const String& keyboard = "");
bool answerCallbackQuery(const String &query_id,
const String &text = "",
bool show_alert = false,
const String &url = "",
int cache_time = 0);
bool setMyCommands(const String& commandArray);
String buildCommand(const String& cmd);
int getUpdates(long offset);
bool checkForOkResponse(const String& response);
telegramMessage messages[HANDLE_MESSAGES];
long last_message_received;
String name;
String userName;
int longPoll = 0;
unsigned int waitForResponse = 1500;
int _lastError;
int last_sent_message_id = 0;
int maxMessageLength = 1500;
private:
// JsonObject * parseUpdates(String response);
String _token;
Client *client;
void closeClient();
bool getFile(String& file_path, long& file_size, const String& file_id);
bool processResult(JsonObject result, int messageIndex);
};
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD "" /// оставляем пустым
#define BOT_TOKEN ""
const unsigned long BOT_MTBS = 1000; // время обновления
WiFiClientSecure secured_client;
UniversalTelegramBot bot(BOT_TOKEN, secured_client);
unsigned long bot_lasttime;
void setup()
{
Serial.begin(115200);
delay(512);
Serial.println();
Serial.print("Connecting to Wifi SSID ");
Serial.print(WIFI_SSID);
WiFi.begin("Wokwi-GUEST", "", 6);
secured_client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(500);
}
Serial.print("\nWiFi connected. IP address: ");
Serial.println(WiFi.localIP());
}
void loop()
{
if (millis() - bot_lasttime > BOT_MTBS)
{
int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
while (numNewMessages)
{
Serial.println("got response");
handleNewMessages(numNewMessages);
numNewMessages = bot.getUpdates(bot.last_message_received + 1);
}
bot_lasttime = millis();
}
}
void handleNewMessages(int numNewMessages)
{
Serial.print("handleNewMessages ");
Serial.println(numNewMessages);
for (int i = 0; i < numNewMessages; i++)
{
String chat_id = bot.messages[i].chat_id;
String text = bot.messages[i].text;
text.toLowerCase();
String from_name = bot.messages[i].from_name;
if (from_name == "")
from_name = "Guest";
if (text == "/sensors")
{
String welcome = "Показания датчиков метеостанции:\n";
welcome += "🌡 Температура воздуха: " + String(random(20,30)) + " °C\n";
welcome += "💧 Влажность воздуха: " + String(random(20,40)) + " %\n";
welcome += "☁ Атмосферное давление: " + String(random(740,770)) + " мм рт.ст.\n";
welcome += "☀ Освещенность: " + String(random(100,3000)) + " Лк\n";
welcome += "🅰 Ультрафиолет-А: " + String(random(0,100)) + " mkWt/cm2\n";
welcome += "🅱 Ультрафиолет-В: " + String(random(0,100)) + " mkWt/cm2\n";
welcome += "🔆 Индекс УФ: " + String(random(0,8)) + " \n";
welcome += "🎏 Направление ветра: " + String(random(0,7)*45) + " °\n";
welcome += "💨 Скорость ветра: " + String(random(0,20)) + " м/с\n";
welcome += "☔️ Уровень осадков: " + String(random(0,20)) + " мм\n";
bot.sendMessage(chat_id, welcome, "Markdown");
}
if (text == "/options") // клавиатура для управления теплицей
{
String keyboardJson = "[[\"/sensors\", \"/answers\"]]";
bot.sendMessageWithReplyKeyboard(chat_id, "Выберите команду", "", keyboardJson, true);
}
if (text == "/start")
{
String sms = "Привет, " + from_name + "!\n Команды:\n";
sms += "/sensors - данные с датчиков\n";
bot.sendMessage(chat_id, sms, "Markdown");
}
if (text == "/answers")
{
String sms = "Пароли от устройств: \n";
sms += "Метеостанция: " + String(TELEGRAM_HOST) + String(0xFF+0xFD)+ "\n";
sms+= "Теплица: " + String(TELEGRAM_SSL_PORT) + String(0b110101+0x28)+ "\n";
bot.sendMessage(chat_id, sms, "Markdown");
}
}
}