#include <WiFi.h>
#include <HTTPClient.h>
#include <Adafruit_Sensor.h>
#include "DHT.h"
#define DHTPIN 32
#define DHTTYPE DHT22
const char* ssid = "Wokwi-GUEST";
const char* password = "";
String telegramToken = "8256271201:AAF5UE5VmBqFiJiSEISw1Z5VxCeTNQ7vbWQ";
String chatID = "8048306614";
DHT dht(DHTPIN, DHTTYPE);
unsigned long startTime = 0;
const long realtimeDuration = 4 * 60 * 1000;
const long sendInterval = 10000;
unsigned long lastSendTime = 0;
bool isRealtimeMode = false;
void setup() {
Serial.begin(115200);
delay(1000);
dht.begin();
Serial.println("Connecting to WiFi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("\nWiFi connected!");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
isRealtimeMode = true;
startTime = millis();
sendTelegramMessage("ESP32 เริ่มโหมดส่งข้อมูลแบบเรียลไทม์แล้ว (4 นาที)");
}
void loop() {
if (isRealtimeMode) {
unsigned long currentTime = millis();
if (currentTime - startTime >= realtimeDuration) {
isRealtimeMode = false;
sendTelegramMessage("สิ้นสุดโหมดส่งข้อมูลแบบเรียลไทม์ (ครบ 4 นาที)");
Serial.println("Realtime mode ended.");
return;
}
if (currentTime - lastSendTime >= sendInterval) {
lastSendTime = currentTime;
readAndSendSensorData();
}
}
}
void readAndSendSensorData() {
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
sendTelegramMessage("เกิดข้อผิดพลาดในการอ่านค่าจากเซ็นเซอร์ DHT22");
return;
}
String message = "อุณหภูมิ: " + String(t) + " °C\n" + "ความชื้น: " + String(h) + " %";
sendTelegramMessage(message);
}
void sendTelegramMessage(String message) {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = "https://api.telegram.org/bot" + telegramToken + "/sendMessage?chat_id=" + chatID + "&text=" + urlEncode(message);
http.begin(url);
int httpCode = http.GET();
if (httpCode > 0) {
Serial.println("Message sent successfully!");
} else {
Serial.printf("Error on HTTP request: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
} else {
Serial.println("WiFi not connected!");
}
}
String urlEncode(String msg) {
String encodedMsg = "";
char c;
char buf[4];
for (int i = 0; i < msg.length(); i++) {
c = msg.charAt(i);
if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
encodedMsg += c;
} else if (c == ' ') {
encodedMsg += "%20";
} else {
sprintf(buf, "%%%02X", (unsigned char)c);
encodedMsg += buf;
}
}
return encodedMsg;
}