ESP32 Telegram 地理位置 (Location Data)
這段程式碼展示了如何讓 Telegram 機器人接收並解析使用者傳送的 地理位置 (Location Data)。當你在 Telegram 手機版點選「分享位置」後,ESP32 就能讀取到精確的經緯度。
以下為您逐行解說:
1. 核心邏輯:地理位置解析 (handleNewMessages)
這是此範例與其他範例最不同的地方,它檢查訊息中是否包含坐標資訊:
// 檢查訊息中的經度 (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].longitude和bot.messages[i].latitude是UniversalTelegramBot自動解析出的浮點數。精確度:使用
String(..., 6)是因為地理坐標通常需要精確到小數點後六位才能達到公尺等級的誤差範圍。
2. 啟動指令 (/start)
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)
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) 檢查一次伺服器。如果使用者持續開啟「即時位置分享」,機器人會不斷收到更新的坐標,並一直回傳給使用者。
💡 應用場景
這個功能在物聯網專案中非常強大,例如:
電子圍籬:當使用者傳送位置後,ESP32 計算使用者是否已經接近家門口,若是則自動打開車庫門。
物流追蹤:如果將 ESP32 裝在車上並搭配 GPS 模組,它可以反過來將位置傳送給你的 Telegram 頻道。
環境監測:紀錄特定地點的感測器數值(如:空氣品質)。


沒有留言:
張貼留言