Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*******************************************************************
- Modul: NodeMCU 1.0 (ESP-12E Module)
- Telegram Bot Machbarkeitsstudie
- von:
- https://raw.githubusercontent.com/witnessmenow/Universal-Arduino-Telegram-Bot/master/examples/ESP8266/FlashLED/FlashLED.ino
- Repo:
- https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot
- und:
- https://core.telegram.org/bots/api#making-requests
- Man braucht das Repo komplett als ZIP, Einbinden mit: Sketch > Include Library > Add .ZIP Library
- Dazu noch ueber Tools > Manage Libraries... die ArduinoJson suchen und installieren. Siehe:
- https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot#installing
- Features:
- https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot#features
- Um die ESP8266 Lib. dazu zu kriegen: Files > Preferences > Additional Boards Manager URLs:
- http://arduino.esp8266.com/stable/package_esp8266com_index.json
- Dann im Lib. Manager (Tools > Manage Libraries...) nach esp8266 suchen und installieren
- --
- A telegram bot for your ESP8266 that controls the
- onboard LED. The LED in this example is active low.
- Parts:
- D1 Mini ESP8266 (or any ESP8266 board)
- Written by Brian Lough
- YouTube: https://www.youtube.com/brianlough
- Tindie: https://www.tindie.com/stores/brianlough/
- Twitter: https://twitter.com/witnessmenow
- *******************************************************************/
- #include <ESP8266WiFi.h>
- #include <WiFiClientSecure.h>
- #include <UniversalTelegramBot.h>
- // Wifi network station credentials
- #define WIFI_SSID "myAP"
- #define WIFI_PASSWORD "AP-password"
- // Telegram BOT Token (Get from Botfather)
- #define BOT_TOKEN "token"
- // 2022-04-10: fuer Debug Ausgaben im Serial Monitor (Tools >) debug auf true setzen
- bool debug = false;
- const unsigned long BOT_MTBS = 1000; // mean time between scan messages
- X509List cert(TELEGRAM_CERTIFICATE_ROOT);
- WiFiClientSecure secured_client;
- UniversalTelegramBot bot(BOT_TOKEN, secured_client);
- unsigned long bot_lasttime; // last time messages' scan has been done
- const int ledPin = LED_BUILTIN;
- int ledStatus = 0;
- // relaisDelay (open_time) can be changed by command but cannot be more than relaisMaxDelay
- int relaisDelay = 3000;
- int relaisMaxDelay = 10000;
- // wrong from_name or chat_id gives a delay for the next command
- int nagDelay = 10000;
- // fcw: 2022-04-06: von: https://www.smarthome-tricks.de/esp8266/relais-schalten/
- int pinRelais1 = D1;
- int relaisStatus = 0;
- // fcw: 2022-04-09: trusted_chat_ids und temp_trusted_chat_ids
- String trusted_chat_id1 = "1234567890";
- String trusted_chat_id2 = "0987654321";
- // mit trusted_chat_ids.length() dann ein loop o.ae. durchlaufen
- // temp. chat_id default auf 1234567890 gesetzt, zur Laufzeit ueberschreibbar durch Befehl
- String temp_trusted_chat_id = "1234567890";
- String temp_trusted_from_name = "556beda6725423548245093854f167ac"; // irgendwas nicht zu erratendes
- // function to check if a string is a valid number (for relaisDelay setting by command)
- boolean isNumber(String str)
- {
- for(byte i=0;i<str.length();i++)
- {
- if(!isDigit(str.charAt(i))) return false;
- }
- return true;
- }
- void handleNewMessages(int numNewMessages)
- {
- if (debug) Serial.print("handleNewMessages ");
- if (debug) Serial.println(numNewMessages);
- for (int i = 0; i < numNewMessages; i++)
- {
- String chat_id = bot.messages[i].chat_id;
- String text = bot.messages[i].text;
- String from_name = bot.messages[i].from_name;
- if (from_name == "") from_name = "Guest";
- // die Eigenschaften der Struktur telegramMessage des Objekts UniversalTelegramBot ausgeben
- // von: https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot/blob/master/src/UniversalTelegramBot.h
- // debug auf true zum Auslesen
- if (debug)
- {
- Serial.print("text: ");
- Serial.println(text);
- Serial.print("chat_id: ");
- Serial.println(chat_id);
- String chat_title = bot.messages[i].chat_title;
- Serial.print("chat_title: ");
- Serial.println(chat_title);
- String from_id = bot.messages[i].from_id;
- Serial.print("from_id: ");
- Serial.println(from_id);
- Serial.print("from_name: ");
- Serial.println(from_name);
- String date = bot.messages[i].date;
- Serial.print("date: ");
- Serial.println(date);
- String type = bot.messages[i].type;
- Serial.print("type: ");
- Serial.println(type);
- String file_caption = bot.messages[i].file_caption;
- Serial.print("file_caption: ");
- Serial.println(file_caption);
- String file_path = bot.messages[i].file_path;
- Serial.print("file_path: ");
- Serial.println(file_path);
- String file_name = bot.messages[i].file_name;
- Serial.print("file_name: ");
- Serial.println(file_name);
- // Bool hasDocument = bot.messages[i].hasDocument;
- // Serial.print("hasDocument: ");
- // Serial.println(String(hasDocument));
- int file_size = bot.messages[i].file_size;
- Serial.print("file_size: ");
- Serial.println(String(file_size));
- Serial.print("trusted_chat_id1: ");
- Serial.println(trusted_chat_id1);
- Serial.print("trusted_chat_id2: ");
- Serial.println(trusted_chat_id2);
- Serial.print("temp_trusted_chat_id: ");
- Serial.println(temp_trusted_chat_id);
- }
- /*
- die paar fehlen noch:
- struct telegramMessage {
- ...
- float longitude;
- float latitude;
- int update_id;
- int message_id;
- int reply_to_message_id;
- String reply_to_text;
- String query_id;
- };
- */
- // 1234567890 (bzw trusted_chat_id1) oder 0987654321 (bzw trusted_chat_id2) oder temp. chat_id (initial 1234567890) oder tem_trusted_from_name
- if ((chat_id == trusted_chat_id1) || (chat_id == trusted_chat_id2) || (chat_id == temp_trusted_chat_id) || (from_name == temp_trusted_from_name))
- {
- if (debug) Serial.print("chat_id OK - Befehlsabfrage...\n");
- if ((text == "/info") || (text == "/help"))
- {
- String help = "Welcome to Universal Arduino Telegram Bot library, " + from_name + ".\n";
- help += "/info or /help: show this text\n";
- help += "/debug : Switch serial outputs on or off (sets debug = !debug)\n";
- // help += "/ledon : to switch the Led ON\n";
- // help += "/ledoff : to switch the Led OFF\n";
- // help += "/ledstatus : Returns current status of LED\n\n";
- // welcome += "fcw: 2022-04-06: PoC: Relais ueber D1 schalten\n";
- /* fcw: 2022-04-10: auskommentiert, zu gefaehrlich
- help += "/relaison : to switch the relais on\n";
- help += "/relaisoff : to switch the relais off\n";
- help += "/relaisstatus : Returns current status of Relais\n";
- */
- help += "/open_time:<ms> : Sets open-time in ms (max 10000) of Relais\n";
- help += "/chat_id:<Chat-ID> : allows this Chat-ID for commands till reboot\n";
- help += "/from_name:<Telegram-Name> : allows this Telegram Name for commands till reboot\n";
- help += "/open : Switch Relais on for " + String(relaisDelay) + " ms\n";
- help += "/open_short : Switch Relais on for 1 second\n";
- // welcome += "chat_id: " + chat_id;
- if (debug) Serial.print("help: \n");
- if (debug) Serial.println(help);
- bot.sendMessage(chat_id, help, "");
- }
- // Befehle nur zum Testen
- if (text == "/ledon")
- {
- digitalWrite(ledPin, LOW); // turn the LED on (HIGH is the voltage level)
- ledStatus = 1;
- bot.sendMessage(chat_id, "Led is ON", "");
- }
- if (text == "/ledoff")
- {
- ledStatus = 0;
- digitalWrite(ledPin, HIGH); // turn the LED off (LOW is the voltage level)
- bot.sendMessage(chat_id, "Led is OFF", "");
- }
- if (text == "/ledstatus")
- {
- if (ledStatus)
- {
- bot.sendMessage(chat_id, "Led is ON", "");
- }
- else
- {
- bot.sendMessage(chat_id, "Led is OFF", "");
- }
- }
- /* fcw: 2022-04-10: auskommentiert, zu gefaehrlich
- // fcw: 2022-04-06: von: https://www.smarthome-tricks.de/esp8266/relais-schalten/
- if (text == "/relaison")
- {
- digitalWrite(pinRelais1, LOW); // turn the Relais on (HIGH is the voltage level)
- relaisStatus = 1;
- bot.sendMessage(chat_id, "Relais is ON", "");
- }
- if (text == "/relaisoff")
- {
- digitalWrite(pinRelais1, HIGH); // turn the Relais off (LOW is the voltage level)
- relaisStatus = 0;
- bot.sendMessage(chat_id, "Relais is OFF", "");
- }
- if (text == "/relaisstatus")
- {
- if (relaisStatus)
- {
- bot.sendMessage(chat_id, "Relais is ON", "");
- }
- else
- {
- bot.sendMessage(chat_id, "Relais is OFF", "");
- }
- }
- */
- if (text == "/open")
- {
- String command = "Relais ON for " + String(relaisDelay) + " ms...";
- bot.sendMessage(chat_id, command, "");
- digitalWrite(pinRelais1, LOW); // turn the Relais on
- delay(relaisDelay);
- digitalWrite(pinRelais1, HIGH); // turn the Relais off again
- // command = "Relais was ON for " + String(relaisDelay) + " ms\n\nTo open press: \n/open";
- // bot.sendMessage(chat_id, command, "");
- String keyboardJson = "[[\"/open_short\", \"/open\"]]";
- bot.sendMessageWithReplyKeyboard(chat_id, "Tueroeffner Willi", "", keyboardJson, true);
- }
- if (text == "/open_short")
- {
- String command = "Relais ON for 1 second ...";
- bot.sendMessage(chat_id, command, "");
- digitalWrite(pinRelais1, LOW); // turn the Relais on
- delay(1000);
- digitalWrite(pinRelais1, HIGH); // turn the Relais off again
- // command = "Relais was ON for " + String(relaisDelay) + " ms\n\nTo open press: \n/open";
- // bot.sendMessage(chat_id, command, "");
- String keyboardJson = "[[\"/open_short\", \"/open\"]]";
- bot.sendMessageWithReplyKeyboard(chat_id, "TΓΌrΓΆffner", "", keyboardJson, true);
- }
- // temporaere chat_id zulassen
- if (text.substring(0, 9) == "/chat_id:")
- {
- if (debug) Serial.print("text.substring(0,9): ");
- if (debug) Serial.println(text.substring(0, 9));
- int length = text.length();
- temp_trusted_chat_id = text.substring(9, length);
- if (debug) Serial.print("length: ");
- if (debug) Serial.println(String(length));
- if (debug) Serial.print("temp_trusted_chat_id: ");
- if (debug) Serial.println(temp_trusted_chat_id);
- String command = "Allow commands from chat_id: " + temp_trusted_chat_id;
- bot.sendMessage(chat_id, command, "");
- }
- if (text.substring(0, 11) == "/from_name:")
- {
- int length = text.length();
- temp_trusted_from_name = text.substring(11, length);
- if (debug) Serial.print("length: ");
- if (debug) Serial.println(String(length));
- if (debug) Serial.print("temp_trusted_from_name: ");
- if (debug) Serial.println(temp_trusted_from_name);
- String command = "Allow commands from Telegram-Name: " + temp_trusted_from_name;
- bot.sendMessage(chat_id, command, "");
- }
- if (text.substring(0, 11) == "/open_time:")
- {
- String command = "";
- int length = text.length();
- String temp_open_time = text.substring(11, length);
- if (debug) Serial.print("length: ");
- if (debug) Serial.println(String(length));
- if (debug) Serial.print("temp_open_time: ");
- if (debug) Serial.println(temp_open_time);
- if (isNumber(temp_open_time))
- {
- int tempRelaisDelay = temp_open_time.toInt();
- if (tempRelaisDelay > relaisMaxDelay) relaisDelay = relaisMaxDelay; // max delay
- else if (tempRelaisDelay < 100) relaisDelay = relaisDelay; // unchanged if less 100 ms
- else relaisDelay = tempRelaisDelay;
- command = "open_time now (till next reboot): " + String(relaisDelay);
- if (debug) Serial.print(command);
- }
- else
- {
- command = "open_time must be a number!";
- if (debug) Serial.print("temp_open_time is not a number! command: " + command);
- }
- bot.sendMessage(chat_id, command, "");
- }
- if (text == "/debug")
- {
- debug = !debug;
- if (debug)
- {
- bot.sendMessage(chat_id, "Debug messages to Serial Monitor enabled (debug = true)", "");
- Serial.print("Debug enabled");
- }
- else
- {
- bot.sendMessage(chat_id, "Debug messages to Serial Monitor disabled (debug = false)", "");
- }
- }
- }
- else
- {
- // wrong chat_id or from_name makes delay
- if (debug) Serial.print("from_name: ");
- if (debug) Serial.println(from_name);
- if (debug) Serial.print("chat_id: ");
- if (debug) Serial.println(chat_id);
- if (debug) Serial.print("wrong chat_id / from_name - delay...");
- delay(nagDelay);
- }
- }
- }
- void setup()
- {
- // muss auch wenn debug aus ist aktiviert werden, sonst kann man nicht mit /debug umschalten
- Serial.begin(115200);
- Serial.println();
- pinMode(ledPin, OUTPUT); // initialize digital ledPin as an output.
- delay(10);
- digitalWrite(ledPin, HIGH); // initialize pin as off (active LOW)
- // fcw: 2022-04-06: von: https://www.smarthome-tricks.de/esp8266/relais-schalten/
- pinMode(pinRelais1 , OUTPUT);
- digitalWrite(pinRelais1, HIGH); // initialize pin as off (active LOW)
- // attempt to connect to Wifi network:
- configTime(0, 0, "pool.ntp.org"); // get UTC time via NTP
- secured_client.setTrustAnchors(&cert); // Add root certificate for api.telegram.org
- if (debug) Serial.print("Connecting to Wifi SSID ");
- if (debug) Serial.print(WIFI_SSID);
- WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
- while (WiFi.status() != WL_CONNECTED)
- {
- if (debug) Serial.print(".");
- delay(500);
- }
- if (debug) Serial.print("\nWiFi connected. IP address: ");
- if (debug) Serial.println(WiFi.localIP());
- // Check NTP/Time, usually it is instantaneous and you can delete the code below.
- if (debug) Serial.print("Retrieving time: ");
- time_t now = time(nullptr);
- while (now < 24 * 3600)
- {
- if (debug) Serial.print(".");
- delay(100);
- now = time(nullptr);
- }
- if (debug) Serial.println(now);
- String keyboardJson = "[[\"/open_short\", \"/open\"]]";
- bot.sendMessageWithReplyKeyboard("1234567890", "NodeMCU: tueroeffner.ino Startup", "", keyboardJson, true);
- }
- void loop()
- {
- if (millis() - bot_lasttime > BOT_MTBS)
- {
- int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
- while (numNewMessages)
- {
- if (debug) Serial.println("got response");
- handleNewMessages(numNewMessages);
- numNewMessages = bot.getUpdates(bot.last_message_received + 1);
- }
- bot_lasttime = millis();
- }
- }
Add Comment
Please, Sign In to add comment