2025年7月14日 星期一

ESP32 Telegram Bot to Control LED

ESP32 Telegram Bot to Control LED





#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>

// --- WiFi Configuration ---
const char* ssid = "Wokwi-GUEST"; // Replace with your network credentials
const char* password = "";

// --- Telegram Bot Configuration ---
#define BOTtoken "8022700986:AAGymymK9_d1HcTGJWl3mtqHmilxB64_5Zw" // your Bot Token (Get from Botfather)
#define CHAT_ID "7965218469"

WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);

// Checks for new messages every 1 second.
int botRequestDelay = 1000;
unsigned long lastTimeBotRan;

const int ledPin = 2;
bool ledState = LOW;

// Handle what happens when you receive new messages
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);
    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;

    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, "");
    }

    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);

  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, ledState);
 
  // Connect to Wi-Fi
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }
  // Print ESP32 Local IP Address
  Serial.println(WiFi.localIP());
  Serial.println("Start telegram Led control command");
}

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();
  }
}





<<freeRTOS 寫法>>

#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h> // Make sure this is included for handleNewMessages (even if not explicitly used in your provided snippet, it's common for bot libraries)

// --- WiFi Configuration ---
const char* ssid = "Wokwi-GUEST"; // Replace with your network credentials
const char* password = "";

// --- Telegram Bot Configuration ---
#define BOTtoken "8022700986:AAGymymK9_d1HcTGJWl3mtqHmilxB64_5Zw" // your Bot Token (Get from Botfather)
#define CHAT_ID "7965218469"

WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);

// Checks for new messages every 1 second.
int botRequestDelay = 1000;

const int ledPin = 2;
bool ledState = LOW;

// Task handle for the bot update task
TaskHandle_t botUpdateTaskHandle = NULL;

// Handle what happens when you receive new messages
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);
    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;

    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, "");
    } else if (text == "/led_on") {
      bot.sendMessage(chat_id, "LED state set to ON", "");
      ledState = HIGH;
      digitalWrite(ledPin, ledState);
    } else if (text == "/led_off") {
      bot.sendMessage(chat_id, "LED state set to OFF", "");
      ledState = LOW;
      digitalWrite(ledPin, ledState);
    } else if (text == "/state") {
      if (digitalRead(ledPin)) {
        bot.sendMessage(chat_id, "LED is ON", "");
      } else {
        bot.sendMessage(chat_id, "LED is OFF", "");
      }
    }
  }
}

// FreeRTOS Task for handling Telegram Bot updates
void telegramBotTask(void *pvParameters) {
  unsigned long lastTimeBotRan = 0; // Initialize inside the task for its own scope

  for (;;) {
    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();
    }
    // Give control back to the scheduler, or yield, to allow other tasks to run
    // This is crucial for collaborative multitasking, especially if the if condition is frequently false
    vTaskDelay(pdMS_TO_TICKS(50)); // Check every 50ms (or adjust based on responsiveness needed)
  }
}


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

  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, ledState);

  // Connect to Wi-Fi
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org

  Serial.print("Connecting to WiFi..");
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000); // Using delay here is acceptable as it's during initial setup
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.print("ESP32 Local IP Address: ");
  Serial.println(WiFi.localIP());
  Serial.println("Start telegram Led control command");

  // Create the Telegram Bot update task
  // Allocate a larger stack size for the bot task, as network operations and JSON parsing can be memory intensive.
  // 4096 or 8192 bytes is a good starting point to avoid stack overflows.
  xTaskCreate(
    telegramBotTask,       // Task function
    "TelegramBotTask",     // Name of the task
    8192,                  // Stack size in words (ESP32 uses 4-byte words, so 8192 * 4 = 32KB) - This is a safe large value
    NULL,                  // Parameter to pass to the task
    5,                     // Priority (higher number = higher priority)
    &botUpdateTaskHandle   // Task handle
  );
}

void loop() {
  // The loop can be empty as FreeRTOS tasks handle the continuous operations.
  // You can add other independent, non-blocking code here if needed.
}

沒有留言:

張貼留言

WOKWI ESP32 模擬RFID ,LED + Python TKinter SQLite

 WOKWI ESP32 模擬RFID ,LED + Python TKinter SQLite  WOKWI ESP32程式 #include <SPI.h> #include <MFRC522.h> #include <WiFi.h> #i...