顯示具有 ESP32 Telegram 標籤的文章。 顯示所有文章
顯示具有 ESP32 Telegram 標籤的文章。 顯示所有文章

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.
}

Send a Telegram message using ESP32

 Send a Telegram message using ESP32







<<WOKWI ESP32程式>>

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

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

// --- Telegram Bot Configuration ---
#define BOTtoken "801227100986:AAGymymK9_d1HcTGJWl3mtqHmilxB64_5Zw" // your Bot Token (Get from Botfather)
#define CHAT_ID "7925218469"
//需修改


WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);

// Task handle for the periodic message task
TaskHandle_t messageTaskHandle = NULL;

// Function for the periodic message task
void sendPeriodicMessage(void *pvParameters) {
  for (;;) {
    bot.sendMessage(CHAT_ID, "Hello World!");
    Serial.println("bot.sendMessage Hello World!");
    vTaskDelay(pdMS_TO_TICKS(20000)); // Delay for 20 seconds
  }
}

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

  // Connect to Wi-Fi
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // For ESP32/ESP8266

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Create the periodic message task
  // INCREASE STACK SIZE HERE from 2048 to something larger, e.g., 4096 or 8192
  xTaskCreate(
    sendPeriodicMessage,     // Task function
    "MessageTask",           // Name of the task
    4096,                    // <--- INCREASED STACK SIZE (try 4096 first, if still error, try 8192)
    NULL,                    // Parameter to pass to the task
    1,                       // Priority (0 is the lowest)
    &messageTaskHandle       // Task handle
  );
}

void loop() {
  // FreeRTOS tasks manage their own scheduling, so the loop can be empty.
}

MQTT 協定與 Modbus 通訊的遠端監控與控制系統架構

MQTT 協定與 Modbus 通訊的遠端監控與控制系統架構 這張圖片展示了一個 結合 MQTT 協定與 Modbus 通訊的遠端監控與控制系統架構 (主要透過 Node-RED 進行資料整合)。 系統包含三個核心部分,其運作功能說明如下: 1. ESP32 終端設備(硬體控制層...