#include <WiFi.h> // 讓ESP32連上WiFi的工具
#include <HTTPClient.h> // 讓ESP32發送網路請求的工具
#include <ArduinoJson.h> // 讓ESP32理解網路回應內容的工具
const char* ssid = "502PC2"; // 你的WiFi名稱
const char* password = "29912391"; // 你的WiFi密碼
const char* apiKey = "CWA-E71FE4DF-418D-4638-8B8E-15D8B1E282A2"; // 你的中央氣象局API金鑰
const char* apiUrl = "https://opendata.cwb.gov.tw/api/v1/rest/datastore/F-C0032-001?Authorization=";
// 中央氣象局API網址
void setup() {
Serial.begin(115200); // 打開ESP32的顯示屏
WiFi.begin(ssid, password); // 讓ESP32連上你的WiFi
while (WiFi.status() != WL_CONNECTED) { // 等待WiFi連接成功
delay(1000); // 每隔一秒檢查一次
Serial.println("正在連接WiFi..."); // 顯示連接狀態
}
Serial.println("WiFi連接成功"); // 顯示WiFi連接成功
if (WiFi.status() == WL_CONNECTED) { // 確認WiFi已連接
HTTPClient http; // 創建一個工具來發送網路請求
String url = String(apiUrl) + apiKey + "&locationName=新北市";
// 拼出請求的完整網址
http.begin(url); // 開始準備發送請求
int httpCode = http.GET(); // 發送請求,並獲取回應的狀態碼
if (httpCode > 0) { // 檢查請求是否成功
String payload = http.getString(); // 取得回應的內容
Serial.println(payload); // 顯示回應的內容
// 分析回應的內容
DynamicJsonDocument doc(1024);
deserializeJson(doc, payload); // 將回應的內容轉換成可以理解的資料
float pop = doc["records"]["location"][0]["weatherElement"][1]["time"][0]["parameter"]["parameterName"].as<float>(); // 取得降雨機率
if (pop > 50.0) { // 如果降雨機率大於50%
sendLineNotify("降雨機率大於50%,出門記得帶傘!"); // 發送通知告訴你帶傘
} else {
sendLineNotify("降雨機率小於50%,無需帶傘。"); // 發送通知告訴你不需要帶傘
}
} else {
Serial.println("HTTP請求出錯"); // 如果請求失敗,顯示錯誤信息
}
http.end(); // 結束網路請求
}
}
void sendLineNotify(String message) {
WiFiClientSecure client; // 創建一個安全的網路連接
if (!client.connect("notify-api.line.me", 443)) { // 連接到Line Notify的伺服器
Serial.println("連接失敗!"); // 如果連接失敗,顯示錯誤信息
return;
}
String token = "539Os2jVAJHFBiJMSqS9SWogf51Q379RhRPIPva2y1Q"; // 填寫你的Line Notify權杖
String data = "message=" + message; // 要發送的消息內容
client.println("POST /api/notify HTTP/1.1"); // 發送一個POST請求
client.println("Host: notify-api.line.me"); // 設定伺服器地址
client.println("Authorization: Bearer " + token); // 設定授權信息
client.println("Content-Type: application/x-www-form-urlencoded"); // 設定內容類型
client.println("Content-Length: " + String(data.length())); // 設定內容長度
client.println(); // 發送一個空行,表示頭部結束
client.print(data); // 發送消息內容
int statusCode = client.readStringUntil('\n').substring(9, 12).toInt(); // 讀取回應的狀態碼
if (statusCode == 200) {
Serial.println("通知發送成功!"); // 如果狀態碼是200,表示發送成功
} else {
Serial.println("通知發送失敗。"); // 否則表示發送失敗
}
}