#include <DHT.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#define WIFI_SSID "OPPO A31"
#define WIFI_PASS "0965565178"
#define LINE_NOTIFY_TOKEN "RdGRIYv67YLzIX9q3qjtrshNP9bbpm92UqIc2Ml96NS"
#define DHTPIN 21 // DHT22 連接到 ESP32 的腳位
#define DHTTYPE DHT22 // 使用 DHT22 感測器
DHT dht(DHTPIN, DHTTYPE);
bool smartMonitoringEnabled = false;
WiFiClient client;
void setup() {
Serial.begin(115200);
delay(2000);
// 連接 WiFi
connectToWiFi();
// 初始化 DHT 感應器
dht.begin();
}
void loop() {
// 檢查溫濕度達到設定值
if (smartMonitoringEnabled) {
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
if ((temperature < 18 || temperature > 32) || humidity > 70) {
// 溫濕度達到條件,發送 Line 通知
sendLineNotification(temperature, humidity);
smartMonitoringEnabled = false; // 一次性通知,避免重複通知
}
}
delay(1000);
}
void connectToWiFi() {
Serial.println("Connecting to WiFi...");
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting...");
}
Serial.println("Connected to WiFi");
}
void sendLineNotification(float temperature, float humidity) {
Serial.println("Sending Line Notification...");
HTTPClient http;
String url = "https://notify-api.line.me/api/notify";
String message = "Alert! Temperature: " + String(temperature) + "°C, Humidity: " + String(humidity) + "%";
http.begin(url);
http.addHeader("Authorization", "Bearer " + String(LINE_NOTIFY_TOKEN));
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
int httpResponseCode = http.POST("message=" + message);
if (httpResponseCode > 0) {
Serial.print("Line Notify Success, Response code: ");
Serial.println(httpResponseCode);
} else {
Serial.print("Error on Line Notify, Response code: ");
Serial.println(httpResponseCode);
}
http.end();
}