francwalter

Untitled

Apr 13th, 2022
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 15.29 KB | None | 0 0
  1. /*******************************************************************
  2.    Modul: NodeMCU 1.0 (ESP-12E Module)
  3.  
  4.   Telegram Bot Machbarkeitsstudie
  5.   von:
  6.   https://raw.githubusercontent.com/witnessmenow/Universal-Arduino-Telegram-Bot/master/examples/ESP8266/FlashLED/FlashLED.ino
  7.   Repo:
  8.   https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot
  9.   und:
  10.   https://core.telegram.org/bots/api#making-requests
  11.  
  12.   Man braucht das Repo komplett als ZIP, Einbinden mit: Sketch > Include Library > Add .ZIP Library
  13.   Dazu noch ueber Tools > Manage Libraries... die ArduinoJson suchen und installieren. Siehe:
  14.   https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot#installing
  15.   Features:
  16.   https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot#features
  17.  
  18.   Um die ESP8266 Lib. dazu zu kriegen: Files > Preferences > Additional Boards Manager URLs:
  19.  
  20.   http://arduino.esp8266.com/stable/package_esp8266com_index.json
  21.  
  22.   Dann im Lib. Manager (Tools > Manage Libraries...) nach esp8266 suchen und installieren
  23.  
  24.     --
  25.     A telegram bot for your ESP8266 that controls the
  26.     onboard LED. The LED in this example is active low.
  27.  
  28.     Parts:
  29.     D1 Mini ESP8266 (or any ESP8266 board)
  30.  
  31.     Written by Brian Lough
  32.     YouTube: https://www.youtube.com/brianlough
  33.     Tindie: https://www.tindie.com/stores/brianlough/
  34.     Twitter: https://twitter.com/witnessmenow
  35.  *******************************************************************/
  36.  
  37. #include <ESP8266WiFi.h>
  38. #include <WiFiClientSecure.h>
  39. #include <UniversalTelegramBot.h>
  40.  
  41. // Wifi network station credentials
  42. #define WIFI_SSID "myAP"
  43. #define WIFI_PASSWORD "AP-password"
  44. // Telegram BOT Token (Get from Botfather)
  45. #define BOT_TOKEN "token"
  46.  
  47. // 2022-04-10: fuer Debug Ausgaben im Serial Monitor (Tools >) debug auf true setzen
  48. bool debug = false;
  49.  
  50. const unsigned long BOT_MTBS = 1000; // mean time between scan messages
  51.  
  52. X509List cert(TELEGRAM_CERTIFICATE_ROOT);
  53. WiFiClientSecure secured_client;
  54. UniversalTelegramBot bot(BOT_TOKEN, secured_client);
  55. unsigned long bot_lasttime; // last time messages' scan has been done
  56.  
  57. const int ledPin = LED_BUILTIN;
  58. int ledStatus = 0;
  59.  
  60. // relaisDelay (open_time) can be changed by command but cannot be more than relaisMaxDelay
  61. int relaisDelay = 3000;
  62. int relaisMaxDelay = 10000;
  63.  
  64. // wrong from_name or chat_id gives a delay for the next command
  65. int nagDelay = 10000;
  66.  
  67. // fcw: 2022-04-06: von: https://www.smarthome-tricks.de/esp8266/relais-schalten/
  68. int pinRelais1 = D1;
  69. int relaisStatus = 0;
  70.  
  71. // fcw: 2022-04-09: trusted_chat_ids und temp_trusted_chat_ids
  72. String trusted_chat_id1 = "1234567890";
  73. String trusted_chat_id2 = "0987654321";
  74. // mit trusted_chat_ids.length() dann ein loop o.ae. durchlaufen
  75.  
  76. // temp. chat_id default auf 1234567890 gesetzt, zur Laufzeit ueberschreibbar durch Befehl
  77. String temp_trusted_chat_id = "1234567890";
  78. String temp_trusted_from_name = "556beda6725423548245093854f167ac"; // irgendwas nicht zu erratendes
  79.  
  80. // function to check if a string is a valid number (for relaisDelay setting by command)
  81. boolean isNumber(String str)
  82. {
  83.   for(byte i=0;i<str.length();i++)
  84.   {
  85.     if(!isDigit(str.charAt(i))) return false;
  86.   }
  87.   return true;
  88. }
  89.  
  90. void handleNewMessages(int numNewMessages)
  91. {
  92.   if (debug) Serial.print("handleNewMessages ");
  93.   if (debug) Serial.println(numNewMessages);
  94.  
  95.   for (int i = 0; i < numNewMessages; i++)
  96.   {
  97.     String chat_id = bot.messages[i].chat_id;
  98.     String text = bot.messages[i].text;
  99.     String from_name = bot.messages[i].from_name;
  100.     if (from_name == "") from_name = "Guest";    
  101.  
  102.     // die Eigenschaften der Struktur telegramMessage des Objekts UniversalTelegramBot ausgeben
  103.     // von: https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot/blob/master/src/UniversalTelegramBot.h
  104.     // debug auf true zum Auslesen
  105.  
  106.     if (debug)
  107.     {
  108.       Serial.print("text: ");
  109.       Serial.println(text);
  110.      
  111.       Serial.print("chat_id: ");
  112.       Serial.println(chat_id);  
  113.  
  114.       String chat_title = bot.messages[i].chat_title;
  115.       Serial.print("chat_title: ");
  116.       Serial.println(chat_title);
  117.      
  118.       String from_id = bot.messages[i].from_id;
  119.       Serial.print("from_id: ");
  120.       Serial.println(from_id);
  121.  
  122.       Serial.print("from_name: ");
  123.       Serial.println(from_name);
  124.  
  125.       String date = bot.messages[i].date;
  126.       Serial.print("date: ");
  127.       Serial.println(date);
  128.  
  129.       String type = bot.messages[i].type;
  130.       Serial.print("type: ");
  131.       Serial.println(type);
  132.  
  133.       String file_caption = bot.messages[i].file_caption;
  134.       Serial.print("file_caption: ");
  135.       Serial.println(file_caption);
  136.  
  137.       String file_path = bot.messages[i].file_path;
  138.       Serial.print("file_path: ");
  139.       Serial.println(file_path);
  140.  
  141.       String file_name = bot.messages[i].file_name;
  142.       Serial.print("file_name: ");
  143.       Serial.println(file_name);
  144.  
  145.       //    Bool hasDocument = bot.messages[i].hasDocument;
  146.       //    Serial.print("hasDocument: ");
  147.       //    Serial.println(String(hasDocument));
  148.  
  149.       int file_size = bot.messages[i].file_size;
  150.       Serial.print("file_size: ");
  151.       Serial.println(String(file_size));
  152.  
  153.       Serial.print("trusted_chat_id1: ");
  154.       Serial.println(trusted_chat_id1);
  155.      
  156.       Serial.print("trusted_chat_id2: ");
  157.       Serial.println(trusted_chat_id2);    
  158.      
  159.       Serial.print("temp_trusted_chat_id: ");
  160.       Serial.println(temp_trusted_chat_id);
  161.     }
  162.  
  163.       /*
  164.      
  165.       die paar fehlen noch:
  166.      
  167.       struct telegramMessage {
  168.       ...
  169.         float longitude;
  170.         float latitude;
  171.         int update_id;
  172.         int message_id;  
  173.  
  174.         int reply_to_message_id;
  175.         String reply_to_text;
  176.         String query_id;
  177.       };
  178.       */
  179.  
  180.   // 1234567890 (bzw trusted_chat_id1) oder 0987654321 (bzw trusted_chat_id2) oder temp. chat_id (initial 1234567890) oder tem_trusted_from_name
  181.     if ((chat_id == trusted_chat_id1) || (chat_id == trusted_chat_id2) || (chat_id == temp_trusted_chat_id) || (from_name == temp_trusted_from_name))
  182.     {
  183.       if (debug) Serial.print("chat_id OK - Befehlsabfrage...\n");
  184.          
  185.       if ((text == "/info") || (text == "/help"))
  186.       {
  187.         String help = "Welcome to Universal Arduino Telegram Bot library, " + from_name + ".\n";
  188.         help += "/info or /help: show this text\n";
  189.         help += "/debug : Switch serial outputs on or off (sets debug = !debug)\n";
  190.         // help += "/ledon : to switch the Led ON\n";
  191.         // help += "/ledoff : to switch the Led OFF\n";
  192.         // help += "/ledstatus : Returns current status of LED\n\n";
  193.         // welcome += "fcw: 2022-04-06: PoC: Relais ueber D1 schalten\n";
  194.         /*      fcw: 2022-04-10: auskommentiert, zu gefaehrlich
  195.                 help += "/relaison : to switch the relais on\n";
  196.                 help += "/relaisoff : to switch the relais off\n";
  197.                 help += "/relaisstatus : Returns current status of Relais\n";
  198.         */        
  199.         help += "/open_time:<ms> : Sets open-time in ms (max 10000) of Relais\n";
  200.         help += "/chat_id:<Chat-ID> : allows this Chat-ID for commands till reboot\n";
  201.         help += "/from_name:<Telegram-Name> : allows this Telegram Name for commands till reboot\n";
  202.         help += "/open : Switch Relais on for " + String(relaisDelay) + " ms\n";
  203.         help += "/open_short : Switch Relais on for 1 second\n";
  204.         // welcome += "chat_id: " + chat_id;
  205.         if (debug) Serial.print("help: \n");
  206.         if (debug) Serial.println(help);
  207.         bot.sendMessage(chat_id, help, "");
  208.       }
  209.       // Befehle nur zum Testen
  210.       if (text == "/ledon")
  211.       {
  212.         digitalWrite(ledPin, LOW); // turn the LED on (HIGH is the voltage level)
  213.         ledStatus = 1;
  214.         bot.sendMessage(chat_id, "Led is ON", "");
  215.       }
  216.  
  217.       if (text == "/ledoff")
  218.       {
  219.         ledStatus = 0;
  220.         digitalWrite(ledPin, HIGH); // turn the LED off (LOW is the voltage level)
  221.         bot.sendMessage(chat_id, "Led is OFF", "");
  222.       }
  223.    
  224.       if (text == "/ledstatus")
  225.       {
  226.         if (ledStatus)
  227.         {
  228.           bot.sendMessage(chat_id, "Led is ON", "");
  229.         }
  230.         else
  231.         {
  232.           bot.sendMessage(chat_id, "Led is OFF", "");
  233.         }
  234.       }
  235.  
  236.  
  237.       /* fcw: 2022-04-10: auskommentiert, zu gefaehrlich
  238.       // fcw: 2022-04-06: von: https://www.smarthome-tricks.de/esp8266/relais-schalten/
  239.       if (text == "/relaison")
  240.       {
  241.         digitalWrite(pinRelais1, LOW); // turn the Relais on (HIGH is the voltage level)
  242.         relaisStatus = 1;
  243.         bot.sendMessage(chat_id, "Relais is ON", "");      
  244.       }
  245.       if (text == "/relaisoff")
  246.       {
  247.         digitalWrite(pinRelais1, HIGH); //  turn the Relais off (LOW is the voltage level)
  248.         relaisStatus = 0;
  249.         bot.sendMessage(chat_id, "Relais is OFF", "");      
  250.       }    
  251.       if (text == "/relaisstatus")
  252.       {
  253.         if (relaisStatus)
  254.         {
  255.           bot.sendMessage(chat_id, "Relais is ON", "");
  256.         }
  257.         else
  258.         {
  259.           bot.sendMessage(chat_id, "Relais is OFF", "");
  260.         }
  261.       }
  262.       */    
  263.       if (text == "/open")
  264.       {
  265.         String command = "Relais ON for " + String(relaisDelay) + " ms...";      
  266.         bot.sendMessage(chat_id, command, "");      
  267.         digitalWrite(pinRelais1, LOW); // turn the Relais on
  268.         delay(relaisDelay);
  269.         digitalWrite(pinRelais1, HIGH); // turn the Relais off again
  270.         // command = "Relais was ON for " + String(relaisDelay) + " ms\n\nTo open press: \n/open";      
  271.         // bot.sendMessage(chat_id, command, "");      
  272.         String keyboardJson = "[[\"/open_short\", \"/open\"]]";
  273.         bot.sendMessageWithReplyKeyboard(chat_id, "Tueroeffner Willi", "", keyboardJson, true);
  274.       }
  275.       if (text == "/open_short")
  276.       {
  277.         String command = "Relais ON for 1 second ...";      
  278.         bot.sendMessage(chat_id, command, "");      
  279.         digitalWrite(pinRelais1, LOW); // turn the Relais on
  280.         delay(1000);
  281.         digitalWrite(pinRelais1, HIGH); // turn the Relais off again
  282.         // command = "Relais was ON for " + String(relaisDelay) + " ms\n\nTo open press: \n/open";      
  283.         // bot.sendMessage(chat_id, command, "");      
  284.         String keyboardJson = "[[\"/open_short\", \"/open\"]]";
  285.         bot.sendMessageWithReplyKeyboard(chat_id, "TΓΌrΓΆffner", "", keyboardJson, true);
  286.       }
  287.  
  288.       // temporaere chat_id zulassen
  289.                
  290.       if (text.substring(0, 9) == "/chat_id:")
  291.       {
  292.         if (debug) Serial.print("text.substring(0,9): ");
  293.         if (debug) Serial.println(text.substring(0, 9));
  294.         int length = text.length();
  295.         temp_trusted_chat_id = text.substring(9, length);
  296.         if (debug) Serial.print("length: ");
  297.         if (debug) Serial.println(String(length));
  298.         if (debug) Serial.print("temp_trusted_chat_id: ");
  299.         if (debug) Serial.println(temp_trusted_chat_id);
  300.         String command = "Allow commands from chat_id: " + temp_trusted_chat_id;      
  301.         bot.sendMessage(chat_id, command, "");      
  302.       }
  303.       if (text.substring(0, 11) == "/from_name:")
  304.       {
  305.         int length = text.length();
  306.         temp_trusted_from_name = text.substring(11, length);
  307.         if (debug) Serial.print("length: ");
  308.         if (debug) Serial.println(String(length));
  309.         if (debug) Serial.print("temp_trusted_from_name: ");
  310.         if (debug) Serial.println(temp_trusted_from_name);
  311.         String command = "Allow commands from Telegram-Name: " + temp_trusted_from_name;      
  312.         bot.sendMessage(chat_id, command, "");      
  313.       }    
  314.       if (text.substring(0, 11) == "/open_time:")
  315.       {
  316.         String command = "";
  317.         int length = text.length();
  318.         String temp_open_time = text.substring(11, length);
  319.         if (debug) Serial.print("length: ");
  320.         if (debug) Serial.println(String(length));
  321.         if (debug) Serial.print("temp_open_time: ");
  322.         if (debug) Serial.println(temp_open_time);
  323.         if (isNumber(temp_open_time))
  324.         {
  325.           int tempRelaisDelay = temp_open_time.toInt();
  326.           if (tempRelaisDelay > relaisMaxDelay) relaisDelay = relaisMaxDelay; // max delay
  327.           else if (tempRelaisDelay < 100) relaisDelay = relaisDelay; // unchanged if less 100 ms
  328.           else relaisDelay = tempRelaisDelay;
  329.           command = "open_time now (till next reboot): " + String(relaisDelay);
  330.           if (debug) Serial.print(command);
  331.         }
  332.         else
  333.         {
  334.           command = "open_time must be a number!";
  335.           if (debug) Serial.print("temp_open_time is not a number! command: " + command);
  336.         }
  337.         bot.sendMessage(chat_id, command, "");
  338.       }
  339.       if (text == "/debug")
  340.       {
  341.         debug = !debug;
  342.         if (debug)
  343.         {
  344.           bot.sendMessage(chat_id, "Debug messages to Serial Monitor enabled (debug = true)", "");
  345.           Serial.print("Debug enabled");
  346.         }
  347.         else
  348.         {
  349.           bot.sendMessage(chat_id, "Debug messages to Serial Monitor disabled (debug = false)", "");
  350.         }
  351.       }
  352.     }
  353.     else
  354.     {
  355.       // wrong chat_id or from_name makes delay
  356.       if (debug) Serial.print("from_name: ");
  357.       if (debug) Serial.println(from_name);
  358.       if (debug) Serial.print("chat_id: ");
  359.       if (debug) Serial.println(chat_id);        
  360.       if (debug) Serial.print("wrong chat_id / from_name - delay...");
  361.       delay(nagDelay);
  362.     }
  363.   }
  364. }
  365.  
  366.  
  367. void setup()
  368. {
  369.   // muss auch wenn debug aus ist aktiviert werden, sonst kann man nicht mit /debug umschalten
  370.   Serial.begin(115200);
  371.   Serial.println();
  372.  
  373.   pinMode(ledPin, OUTPUT); // initialize digital ledPin as an output.
  374.   delay(10);
  375.   digitalWrite(ledPin, HIGH); // initialize pin as off (active LOW)
  376.   // fcw: 2022-04-06: von: https://www.smarthome-tricks.de/esp8266/relais-schalten/
  377.   pinMode(pinRelais1 , OUTPUT);
  378.   digitalWrite(pinRelais1, HIGH); // initialize pin as off (active LOW)
  379.  
  380.   // attempt to connect to Wifi network:
  381.   configTime(0, 0, "pool.ntp.org");      // get UTC time via NTP
  382.   secured_client.setTrustAnchors(&cert); // Add root certificate for api.telegram.org
  383.   if (debug) Serial.print("Connecting to Wifi SSID ");
  384.   if (debug) Serial.print(WIFI_SSID);
  385.   WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  386.   while (WiFi.status() != WL_CONNECTED)
  387.   {
  388.     if (debug) Serial.print(".");
  389.     delay(500);
  390.   }
  391.   if (debug) Serial.print("\nWiFi connected. IP address: ");
  392.   if (debug) Serial.println(WiFi.localIP());
  393.  
  394.   // Check NTP/Time, usually it is instantaneous and you can delete the code below.
  395.   if (debug) Serial.print("Retrieving time: ");
  396.   time_t now = time(nullptr);
  397.   while (now < 24 * 3600)
  398.   {
  399.     if (debug) Serial.print(".");
  400.     delay(100);
  401.     now = time(nullptr);
  402.   }
  403.   if (debug) Serial.println(now);
  404.  
  405.   String keyboardJson = "[[\"/open_short\", \"/open\"]]";
  406.   bot.sendMessageWithReplyKeyboard("1234567890", "NodeMCU: tueroeffner.ino Startup", "", keyboardJson, true);
  407. }
  408.  
  409. void loop()
  410. {
  411.   if (millis() - bot_lasttime > BOT_MTBS)
  412.   {
  413.     int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
  414.  
  415.     while (numNewMessages)
  416.     {
  417.       if (debug) Serial.println("got response");
  418.       handleNewMessages(numNewMessages);
  419.       numNewMessages = bot.getUpdates(bot.last_message_received + 1);
  420.     }
  421.  
  422.     bot_lasttime = millis();
  423.   }
  424. }
  425.  
Add Comment
Please, Sign In to add comment