2026年11月11日 星期三

【ESP32 物聯網實戰 08】預警:結合 LINE Notify,實作環境異常自動推播

今天,我們要為 ESP32 的大腦加入主動預警功能!我們將串接台灣最普及的通訊軟體服務 —— LINE Notify。一旦設備偵測到環境數據超過我們設定的警戒值,便會立刻自動發送即時警報訊息到你的手機裡,實現零時差的雲端防災預警!

ESP32 異常偵測與 LINE Notify 自動推播流程 📟 ESP32 邊緣端 🚨 偵測到異常! Temp: 31.5°C HTTP POST LINE LINE Notify LINE 警報推播 LINE Notify [設備1號] 警報!
▲ ESP32 ✕ LINE Notify 異常推播架構示意圖

2. ESP32 實作:異常判定與 POST 請求推播

import network
import urequests
import dht
from machine import Pin
import time

SSID = "Your_WiFi_SSID"
PASSWORD = "Your_WiFi_Password"
LINE_TOKEN = "請替換成你的_LINE_Notify_Token"  

sensor = dht.DHT11(Pin(4))

wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PASSWORD)
while not wlan.isconnected():
    time.sleep(0.5)

def send_line_message(token, msg):
    url = "https://notify-api.line.me/api/notify"
    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/x-www-form-urlencoded"
    }
    payload = f"message={msg}"
    
    try:
        response = urequests.post(url, headers=headers, data=payload)
        print("LINE 推送回應:", response.text)
        response.close()
    except Exception as e:
        print("發送 LINE 失敗:", e)

alarm_sent = False

while True:
    try:
        sensor.measure()
        t = sensor.temperature()
        h = sensor.humidity()
        
        # 異常條件判定:使用 > 確保 HTML 正常顯示
        if t > 30 and not alarm_sent:
            alert_msg = f"\n⚠️ [機房警報] 溫度異常過高!\n溫度: {t}°C"
            send_line_message(LINE_TOKEN, alert_msg)
            alarm_sent = True 
            
        # 恢復條件判定:使用 <= 確保 HTML 正常顯示
        elif t <= 29 and alarm_sent:
            normal_msg = f"\n✅ [機房通知] 溫度已降回正常範圍。\n溫度: {t}°C"
            send_line_message(LINE_TOKEN, normal_msg)
            alarm_sent = False
            
    except OSError as e:
        print("感測器讀取或網路異常:", e)
        
    time.sleep(5)

沒有留言:

張貼留言

熱門文章