2026年2月21日 星期六

ESP32 Telegram「長輪詢 (Long Polling)」

ESP32 Telegram「長輪詢 (Long Polling)」



/*******************************************************************

*  An example of setting a long poll, this will mean the request
*  for new messages will wait the specified amount of time before
*  returning with no messages
*
*  This should reduce amount of data used by the bot
 *******************************************************************/
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>

// Wifi network station credentials
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
// Telegram BOT Token (Get from Botfather)
#define BOT_TOKEN "7738940254:AAHbrWu9ovb1BKPQyWsbNSjNxfCGCrEWU-o"
const unsigned long BOT_MTBS = 1000; // mean time between scan messages

unsigned long bot_lasttime;          // last time messages' scan has been done
WiFiClientSecure secured_client;
UniversalTelegramBot bot(BOT_TOKEN, secured_client);

void handleNewMessages(int numNewMessages)
{
  for (int i = 0; i < numNewMessages; i++)
  {
    bot.sendMessage(bot.messages[i].chat_id, bot.messages[i].text, "");
  }
}

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

  // attempt to connect to Wifi network:
  Serial.print("Connecting to Wifi SSID ");
  Serial.print(WIFI_SSID);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  secured_client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(500);
  }
  Serial.print("\nWiFi connected. IP address: ");
  Serial.println(WiFi.localIP());

  Serial.print("Retrieving time: ");
  configTime(0, 0, "pool.ntp.org"); // get UTC time via NTP
  time_t now = time(nullptr);
  while (now < 24 * 3600)
  {
    Serial.print(".");
    delay(100);
    now = time(nullptr);
  }
  Serial.println(now);

  bot.longPoll = 60;
}

void loop()
{
  if (millis() - bot_lasttime > BOT_MTBS)
  {
    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);
    }

    Serial.println("I will happen much less often with a long poll");
    bot_lasttime = millis();
  }
}



這段程式碼的核心主題是 「長輪詢 (Long Polling)」。相較於一般的快速輪詢,長輪詢能大幅減少網路流量與資源消耗,對使用電池供電或有流量限制的 ESP32 專案來說非常重要。

以下是詳細的逐行解說:


1. 核心技術:什麼是 Long Polling?

setup() 函式中,這行是重點:

C++
bot.longPoll = 60; // 設定長輪詢時間為 60 秒
  • 一般輪詢 (Short Polling):ESP32 問伺服器「有新訊息嗎?」,伺服器立刻回答「有」或「沒有」。這會產生大量的空封包交換。

  • 長輪詢 (Long Polling):ESP32 問伺服器「有新訊息嗎?」。如果沒有,伺服器會「握著請求不放」,直到有新訊息進來或是 60 秒時間到才回覆。


2. 處理新訊息 (handleNewMessages)

這部分維持最基礎的 Echo 功能:

C++
void handleNewMessages(int numNewMessages) {
  for (int i = 0; i < numNewMessages; i++) {
    // 收到什麼文字,就回傳給同一個 chat_id
    bot.sendMessage(bot.messages[i].chat_id, bot.messages[i].text, "");
  }
}

3. 初始化設定 (setup)

  • WiFi 連線:連上模擬器的 Wokwi-GUEST。

  • 憑證設定secured_client.setCACert 用於 HTTPS 安全通訊。

  • 網路對時configTime 同步 NTP 時間。

  • 設定 Long Poll:如前所述,設定為 60 秒,這意味著 bot.getUpdates 函式在最糟情況下會讓程式卡住 60 秒等待回應(但這期間伺服器會保持連線,不會浪費流量)。


4. 主迴圈邏輯 (loop)

你會發現這個迴圈的行為與之前的範例大不相同:

C++
void loop() {
  if (millis() - bot_lasttime > BOT_MTBS) {
    // 這行會因為 longPoll = 60,而在此處停留等待最高 60 秒
    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);
    }

    // 只有在收到訊息或 60 秒超時後,這行才會被印出
    Serial.println("I will happen much less often with a long poll");
    bot_lasttime = millis();
  }
}

5. 長輪詢的優缺點分析

特性優點缺點
流量消耗極低。減少了大量的重複請求標頭。無。
反應速度。有訊息時伺服器會立刻推播回傳。無。
程式架構適合單純的機器人。會阻塞程式。因為 bot.getUpdates 會等待,你的 loop 其他功能(如感測器讀取)也會跟著停擺。

ESP32 Telegram 地理位置 (Location Data)

ESP32 Telegram 地理位置 (Location Data)




/*******************************************************************
 An example of receiving location Data
 *******************************************************************/
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>

// Wifi network station credentials
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
// Telegram BOT Token (Get from Botfather)
#define BOT_TOKEN "7738940254:AAHbrWu9ovb1BKPQyWsbNSjNxfCGCrEWU-o"
const unsigned long BOT_MTBS = 1000; // mean time between scan messages
unsigned long bot_lasttime;          // last time messages' scan has been done
WiFiClientSecure secured_client;
UniversalTelegramBot bot(BOT_TOKEN, secured_client);

void handleNewMessages(int 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";

    if (bot.messages[i].longitude != 0 || bot.messages[i].latitude != 0)
    {
      Serial.print("Long: ");
      Serial.println(String(bot.messages[i].longitude, 6));
      Serial.print("Lat: ");
      Serial.println(String(bot.messages[i].latitude, 6));

      String message = "Long: " + String(bot.messages[i].longitude, 6) + "\n";
      message += "Lat: " + String(bot.messages[i].latitude, 6) + "\n";
      bot.sendMessage(chat_id, message, "Markdown");
    }
    else if (text == "/start")
    {
      String welcome = "Welcome to Universal Arduino Telegram Bot library, " + from_name + ".\n";
      welcome += "Share a location or a live location and the bot will respond with the co-ords\n";

      bot.sendMessage(chat_id, welcome, "Markdown");
    }
  }
}

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

  // attempt to connect to Wifi network:
  Serial.print("Connecting to Wifi SSID ");
  Serial.print(WIFI_SSID);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  secured_client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(500);
  }
  Serial.print("\nWiFi connected. IP address: ");
  Serial.println(WiFi.localIP());

  Serial.print("Retrieving time: ");
  configTime(0, 0, "pool.ntp.org"); // get UTC time via NTP
  time_t now = time(nullptr);
  while (now < 24 * 3600)
  {
    Serial.print(".");
    delay(100);
    now = time(nullptr);
  }
  Serial.println(now);
}

void loop()
{
  if (millis() - bot_lasttime > BOT_MTBS)
  {
    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);
    }

    bot_lasttime = millis();
  }
}


這段程式碼展示了如何讓 Telegram 機器人接收並解析使用者傳送的 地理位置 (Location Data)。當你在 Telegram 手機版點選「分享位置」後,ESP32 就能讀取到精確的經緯度。

以下為您逐行解說:


1. 核心邏輯:地理位置解析 (handleNewMessages)

這是此範例與其他範例最不同的地方,它檢查訊息中是否包含坐標資訊:

C++
// 檢查訊息中的經度 (longitude) 或緯度 (latitude) 是否不為 0
if (bot.messages[i].longitude != 0 || bot.messages[i].latitude != 0) 
{
  // 在序列號監控器 (Serial Monitor) 印出經緯度,精確度設定為小數點後 6 位
  Serial.print("Long: ");
  Serial.println(String(bot.messages[i].longitude, 6));
  Serial.print("Lat: ");
  Serial.println(String(bot.messages[i].latitude, 6));

  // 將經緯度組合字串
  String message = "Long: " + String(bot.messages[i].longitude, 6) + "\n";
  message += "Lat: " + String(bot.messages[i].latitude, 6) + "\n";
  
  // 機器人回傳這組坐標訊息給使用者
  bot.sendMessage(chat_id, message, "Markdown");
}
  • 關鍵屬性bot.messages[i].longitudebot.messages[i].latitudeUniversalTelegramBot 自動解析出的浮點數。

  • 精確度:使用 String(..., 6) 是因為地理坐標通常需要精確到小數點後六位才能達到公尺等級的誤差範圍。


2. 啟動指令 (/start)

C++
else if (text == "/start")
{
  String welcome = "Welcome..., " + from_name + ".\n";
  welcome += "Share a location or a live location and the bot will respond with the co-ords\n";
  bot.sendMessage(chat_id, welcome, "Markdown");
}

當使用者剛開始使用機器人時,它會主動引導使用者傳送「即時位置 (Live Location)」或「定點位置」。


3. 初始化設定 (setup)

這部分確保硬體準備就緒:

  • 連線 WiFi:連上指定的模擬環境網路。

  • 同步時間:透過 pool.ntp.org 獲取網路時間。這對處理位置訊息非常重要,因為 Telegram 的地理位置訊息具有時效性,如果 ESP32 時間偏差太大,可能無法正確處理即時位置。

  • SSL 憑證:載入根憑證以確保能與 Telegram 的 HTTPS 伺服器安全溝通。


4. 主迴圈 (loop)

C++
if (millis() - bot_lasttime > BOT_MTBS) 
{
  // 輪詢新訊息
  int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
  while (numNewMessages) 
  {
    handleNewMessages(numNewMessages);
    numNewMessages = bot.getUpdates(bot.last_message_received + 1);
  }
  bot_lasttime = millis();
}

每隔 1 秒 (BOT_MTBS) 檢查一次伺服器。如果使用者持續開啟「即時位置分享」,機器人會不斷收到更新的坐標,並一直回傳給使用者。


💡 應用場景

這個功能在物聯網專案中非常強大,例如:

  1. 電子圍籬:當使用者傳送位置後,ESP32 計算使用者是否已經接近家門口,若是則自動打開車庫門。

  2. 物流追蹤:如果將 ESP32 裝在車上並搭配 GPS 模組,它可以反過來將位置傳送給你的 Telegram 頻道。

  3. 環境監測:紀錄特定地點的感測器數值(如:空氣品質)。

ESP32 Telegram FlashLED

ESP32 Telegram FlashLED 


/*******************************************************************
    A telegram bot for your ESP32 that controls the
    onboard LED. The LED in this example is active low.
 *******************************************************************/
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>

// Wifi network station credentials
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
// Telegram BOT Token (Get from Botfather)
#define BOT_TOKEN "7738940254:AAHbrWu9ovb1BKPQyWsbNSjNxfCGCrEWU-o"

const unsigned long BOT_MTBS = 1000; // mean time between scan messages

WiFiClientSecure secured_client;
UniversalTelegramBot bot(BOT_TOKEN, secured_client);
unsigned long bot_lasttime; // last time messages' scan has been done

const int ledPin = 2;
int ledStatus = 0;

void handleNewMessages(int numNewMessages)
{
  Serial.print("handleNewMessages ");
  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";

    if (text == "/ledon")
    {
      digitalWrite(ledPin, HIGH); // 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, LOW); // turn the LED off (LOW is the voltage level)
      bot.sendMessage(chat_id, "Led is OFF", "");
    }

    if (text == "/status")
    {
      if (ledStatus)
      {
        bot.sendMessage(chat_id, "Led is ON", "");
      }
      else
      {
        bot.sendMessage(chat_id, "Led is OFF", "");
      }
    }

    if (text == "/start")
    {
      String welcome = "Welcome to Universal Arduino Telegram Bot library, " + from_name + ".\n";
      welcome += "This is Flash Led Bot example.\n\n";
      welcome += "/ledon : to switch the Led ON\n";
      welcome += "/ledoff : to switch the Led OFF\n";
      welcome += "/status : Returns current status of LED\n";
      bot.sendMessage(chat_id, welcome, "Markdown");
    }
  }
}


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

  pinMode(ledPin, OUTPUT); // initialize digital ledPin as an output.
  delay(10);
  digitalWrite(ledPin, LOW); // initialize pin as off (active LOW)

  // attempt to connect to Wifi network:
  Serial.print("Connecting to Wifi SSID ");
  Serial.print(WIFI_SSID);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  secured_client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(500);
  }
  Serial.print("\nWiFi connected. IP address: ");
  Serial.println(WiFi.localIP());

  Serial.print("Retrieving time: ");
  configTime(0, 0, "pool.ntp.org"); // get UTC time via NTP
  time_t now = time(nullptr);
  while (now < 24 * 3600)
  {
    Serial.print(".");
    delay(100);
    now = time(nullptr);
  }
  Serial.println(now);
}

void loop()
{
  if (millis() - bot_lasttime > BOT_MTBS)
  {
    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);
    }

    bot_lasttime = millis();
  }
}
程式碼是一個透過 Telegram 遠端控制 ESP32 硬體(LED 燈)的經典範例。

這段程式碼與前一版非常相似,但在 LED 電位邏輯上做了修改。這次的程式改為使用 HIGH 來開燈,LOW 來關燈(即 Active High 邏輯)。

以下是詳細的逐行解說:


1. 硬體定義與全域變數

C++
const int ledPin = 2;              // 定義 LED 接在 GPIO 2 (ESP32 內建 LED)
int ledStatus = 0;                 // 變數:記錄燈狀態 (0=關, 1=開)
const unsigned long BOT_MTBS = 1000; // 掃描新訊息的間隔 (1秒)

2. 核心處理函式:handleNewMessages

當機器人收到新訊息時,會進入此迴圈判斷指令:

  • 讀取資訊

    • chat_id: 誰傳來的(用來回傳訊息)。

    • text: 傳了什麼指令(如 /ledon)。

    • from_name: 使用者的稱呼。

  • 指令判斷

    • /ledon:執行 digitalWrite(ledPin, HIGH)。此時 GPIO 輸出 3.3V,點亮 LED。

    • /ledoff:執行 digitalWrite(ledPin, LOW)。輸出 0V,熄滅 LED。

    • /status:檢查 ledStatus 變數,並回傳目前的狀態文字。

    • /start:傳送歡迎訊息與「指令選單」清單。


3. 初始化設定:setup

這部分負責程式啟動時的硬體與網路準備:

C++
pinMode(ledPin, OUTPUT);    // 設定 GPIO 2 為輸出模式
digitalWrite(ledPin, LOW);  // 初始化:預設為關燈

WiFi.begin(WIFI_SSID, WIFI_PASSWORD); // 啟動 WiFi 連線
secured_client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // 設定 Telegram 安全憑證

// 網路對時:Telegram API 必須確保時間正確才能建立加密連線
configTime(0, 0, "pool.ntp.org"); 

4. 主迴圈:loop

程式會不斷檢查是否有新訊息:

C++
if (millis() - bot_lasttime > BOT_MTBS) {
    // 取得新訊息數量
    int numNewMessages = bot.getUpdates(bot.last_message_received + 1);

    while (numNewMessages) { 
        handleNewMessages(numNewMessages); // 處理訊息
        numNewMessages = bot.getUpdates(bot.last_message_received + 1);
    }
    bot_lasttime = millis(); // 更新檢查時間
}


ESP32 Telegram Echo Bot (回音機器人)

 ESP32 Telegram Echo Bot (回音機器人)



/*******************************************************************
 A telegram bot for your ESP32 that responds
    with whatever message you send it.
 *******************************************************************/
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>

// Wifi network station credentials
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
// Telegram BOT Token (Get from Botfather)
#define BOT_TOKEN "7738940254:AAHbrWu9ovb1BKPQyWsbNSjNxfCGCrEWU-o"
const unsigned long BOT_MTBS = 1000; // mean time between scan messages
WiFiClientSecure secured_client;
UniversalTelegramBot bot(BOT_TOKEN, secured_client);
unsigned long bot_lasttime; // last time messages' scan has been done

void handleNewMessages(int numNewMessages)
{
  for (int i = 0; i < numNewMessages; i++)
  {
    bot.sendMessage(bot.messages[i].chat_id, bot.messages[i].text, "");
  }
}

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

  // attempt to connect to Wifi network:
  Serial.print("Connecting to Wifi SSID ");
  Serial.print(WIFI_SSID);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  secured_client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(500);
  }
  Serial.print("\nWiFi connected. IP address: ");
  Serial.println(WiFi.localIP());

  Serial.print("Retrieving time: ");
  configTime(0, 0, "pool.ntp.org"); // get UTC time via NTP
  time_t now = time(nullptr);
  while (now < 24 * 3600)
  {
    Serial.print(".");
    delay(100);
    now = time(nullptr);
  }
  Serial.println(now);
}

void loop()
{
  if (millis() - bot_lasttime > BOT_MTBS)
  {
    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);
    }

    bot_lasttime = millis();
  }
}

這段程式碼是一個最基礎的 Telegram Echo Bot (回音機器人),其核心邏輯是「收到什麼就回傳什麼」。這通常是所有物聯網 (IoT) 機器人開發的起點。

以下為您逐行解說:


1. 引用與基本定義

C++
#include <WiFi.h>              // 提供 ESP32 連接 WiFi 的功能
#include <WiFiClientSecure.h>  // 提供 SSL/TLS 加密連線,因為 Telegram 要求 HTTPS 
#include <UniversalTelegramBot.h> // Telegram Bot 的核心 API 函式庫
  • WIFI_SSID / PASSWORD: 設定 WiFi 連線資訊(此處為 Wokwi 模擬器環境)。

  • BOT_TOKEN: 您從 Telegram BotFather 取得的專屬權杖 (Token)。

  • BOT_MTBS: 每隔 1000 毫秒(1秒)詢問一次伺服器是否有新訊息。


2. 核心通訊物件

C++
WiFiClientSecure secured_client;             // 建立加密的客戶端
UniversalTelegramBot bot(BOT_TOKEN, secured_client); // 初始化機器人物件
unsigned long bot_lasttime;                  // 記錄最後一次檢查訊息的時間

3. 處理新訊息 (handleNewMessages)

這是機器人接收到訊息後的「反應」邏輯:

C++
void handleNewMessages(int numNewMessages)
{
  for (int i = 0; i < numNewMessages; i++) // 逐一處理收到的訊息包
  {
    // bot.sendMessage(接收者ID, 文字內容, 解析模式)
    // 這裡直接將收到的 text 內容再發送回該 chat_id
    bot.sendMessage(bot.messages[i].chat_id, bot.messages[i].text, "");
  }
}

4. 初始化設定 (setup)

這段程式碼只在 ESP32 啟動時執行一次。

  • 連接 WiFi: 嘗試連上指定 SSID。

  • 設定憑證: secured_client.setCACert(TELEGRAM_CERTIFICATE_ROOT) 是必要的,用來驗證 Telegram 伺服器的安全性。

  • 同步時間: configTime(0, 0, "pool.ntp.org")這非常重要,因為 HTTPS 加密通訊需要正確的時間戳記,否則連線會被 Telegram 拒絕。


5. 主要迴圈 (loop)

程式啟動後會不斷重複執行的部分:

C++
void loop()
{
  // 檢查是否已經超過了設定的間隔時間 (1秒)
  if (millis() - bot_lasttime > BOT_MTBS)
  {
    // 向伺服器要求新訊息,bot.last_message_received + 1 用來確保不重複抓取
    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);
    }
    bot_lasttime = millis(); // 更新最後檢查時間
  }
}

程式運作邏輯總結

  1. 連線階段:ESP32 連上 WiFi 並與網路對時。

  2. 輪詢 (Polling):ESP32 每隔一秒問 Telegram:「嘿,有人跟我說話嗎?」

  3. 解析:如果有人傳訊息(例如傳了 "Hello"),bot.getUpdates 就會抓到資料。

  4. 回應handleNewMessages 被觸發,機器人讀取 "Hello" 並立刻執行 sendMessage 把 "Hello" 傳回去。

EasyBuilder Pro 與 EcoStruxure Machine Expert - Basic 的雙模擬器 -EX7

EasyBuilder Pro 與 EcoStruxure Machine Expert - Basic 的雙模擬器 -EX7 繪製人機介面元件 1. 數值輸入框(設定預設計時器時間) 數值元件 (Numeric Input) : 設定 %MW2 (TM0 時間):讀取/寫入位址...