2020年8月11日 星期二

ESP32 NodeMCU 32S Telegram控制ESP32

資料來源:

程式碼:


/*
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/telegram-control-esp32-esp8266-nodemcu-outputs/
  
  Project created using Brian Lough's Universal Telegram Bot Library: https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot
  Example based on the Universal Arduino Telegram Bot Library: https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot/blob/master/examples/ESP8266/FlashLED/FlashLED.ino
*/

#ifdef ESP32
  #include <WiFi.h>
#else
  #include <ESP8266WiFi.h>
#endif
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>   // Universal Telegram Bot Library written by Brian Lough: https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot
#include <ArduinoJson.h>

// Replace with your network credentials
const char* ssid = "book";
const char* password = "12345678";

// Initialize Telegram BOT
#define BOTtoken "1200000018:AAG5zyCsy-000000_iZFi7dde-6X8fk-D-o"  // your Bot Token (Get from Botfather)將您從Botfather獲得的Telegram Bot Token 插入到 BOTToken  變量。

// Use @myidbot to find out the chat ID of an individual or a group
// Also note that you need to click "start" on a bot before it can
// message you
#define CHAT_ID "100000007"

WiFiClientSecure client;  //使用創建一個新的WiFi客戶端
UniversalTelegramBot bot(BOTtoken, client);  //創建一個 機器人 使用之前定義的Token和客戶端

// Checks for new messages every 1 second.
int botRequestDelay = 1000;
unsigned long lastTimeBotRan;    //每1秒檢查一次新的電報消息

const int ledPin = 2;
bool ledState = LOW;

// Handle what happens when you receive new messages 
//利用handleNewMessages() 函數處理收到的訊息。
void handleNewMessages(int numNewMessages) {
  Serial.println("handleNewMessages");
  Serial.println(String(numNewMessages));

//檢查是否為可用訊息
  for (int i=0; i<numNewMessages; i++) {
    // Chat id of the requester
    String chat_id = String(bot.messages[i].chat_id);
    //檢查聊天室ID是否正確。
    //如果 聊天室ID與您的聊天室ID不同,則表示某人(不是您)已向您的漫遊器發送了一條消息。如果是這種情況,請忽略該消息,然後等待下一條消息。
    if (chat_id != CHAT_ID){
      bot.sendMessage(chat_id, "Unauthorized user", "");
      continue;
    }
    
    // Print the received message
    String text = bot.messages[i].text;   //發送的訊息
    Serial.println(text);

    String from_name = bot.messages[i].from_name;  //發送者的名字

 

 //如果收到/start消息,我們將發送有效命令來控制ESP32。如果您碰巧忘記了控制主板的命令,這將很有用。
    if (text == "/start") {
      String welcome = "Welcome, " + from_name + ".\n";
      welcome += "Use the following commands to control your outputs.\n\n";
      welcome += "/led_on to turn GPIO ON \n";
      welcome += "/led_off to turn GPIO OFF \n";
      welcome += "/state to request current GPIO state \n";
      bot.sendMessage(chat_id, welcome, "");  //發送消息回Telegram
    }

    if (text == "/led_on") {
      bot.sendMessage(chat_id, "LED state set to ON", "");
      ledState = HIGH;
      digitalWrite(ledPin, ledState);
    }
    
    if (text == "/led_off") {
      bot.sendMessage(chat_id, "LED state set to OFF", "");
      ledState = LOW;
      digitalWrite(ledPin, ledState);
    }
    
    if (text == "/state") {
      if (digitalRead(ledPin)){
        bot.sendMessage(chat_id, "LED is ON", "");
      }
      else{
        bot.sendMessage(chat_id, "LED is OFF", "");
      }
    }
  }
}

void setup() {
  Serial.begin(115200);

//如果您使用的是ESP8266,則需要使用以下代碼行:
  #ifdef ESP8266
    client.setInsecure();
  #endif

//將LED設置為輸出,並在ESP首次啟動時將其設置為LOW
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, ledState);
  
  // Connect to Wi-Fi
//初始化Wi-Fi,並使用前面定義的SSID和密碼將ESP連接到本地網絡
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }
  // Print ESP32 Local IP Address
  Serial.println(WiFi.localIP());
}

void loop() {
  if (millis() > lastTimeBotRan + botRequestDelay)  {
    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);
    }
    lastTimeBotRan = millis();
  }
}

沒有留言:

張貼留言

聲寶卡式濾心頭蓋

 https://www.ruten.com.tw/item/show?22027794089976 在這裡買的接頭 https://www.ruten.com.tw/item/show?21814839221595 【品名】台製優質濾心頭蓋 (適用3M、EVERPURE濾心)功...