#include <WiFi.h>
#include <HTTPClient.h>
#include "DHT.h"
#define DHTPIN 15 // GPIO ของ DHT22
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
// WiFi จำลองใน Wokwi
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// URL ngrok ของคุณ
String webhookURL = "https://webhook.site/025425c5-aa1b-40d8-8e9b-40914dbd57f4";
// String webhookURL = "https://1bb90d00f52b.ngrok-free.app/dewgasohol_beta/sensor_insert.php";
// เก็บค่าล่าสุด
float lastTemp = NAN;
float lastHum = NAN;
void setup() {
Serial.begin(115200);
dht.begin();
// เชื่อมต่อ WiFi
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\n✅ WiFi connected");
}
void loop() {
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
Serial.println("❌ Failed to read from DHT sensor!");
delay(2000);
return;
}
bool needSend = false;
// ส่งครั้งแรกหรือค่ามีการเปลี่ยนแปลง
if (isnan(lastTemp) || isnan(lastHum) || fabs(t - lastTemp) >= 0.5 || fabs(h - lastHum) >= 2.0) {
needSend = true;
}
if (needSend) {
Serial.printf("📤 Sending: Temp=%.1f, Hum=%.1f\n", t, h);
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(webhookURL);
http.addHeader("Content-Type", "application/json");
// JSON payload แบบ Vue.js
String jsonData = "{\"temperature\": " + String(t, 1) +
", \"humidity\": " + String(h, 1) + "}";
int httpResponseCode = http.POST(jsonData);
if (httpResponseCode > 0) {
String response = http.getString();
Serial.printf("✅ Sent successfully: %d\n", httpResponseCode);
Serial.println("📄 Response from server: " + response);
// อ่าน success และ error
if (response.indexOf("\"success\":true") >= 0) {
Serial.println("🎉 Server reported success!");
// แสดง ID ถ้ามี
int idIndex = response.indexOf("\"id\":");
if (idIndex >= 0) {
String idStr = response.substring(idIndex + 5);
int comma = idStr.indexOf(",");
if (comma > 0) idStr = idStr.substring(0, comma);
idStr.trim();
Serial.println("🆔 Inserted ID: " + idStr);
}
} else {
Serial.println("❌ Server reported failure");
}
} else {
Serial.printf("❌ Failed to send: %s\n", http.errorToString(httpResponseCode).c_str());
}
http.end();
} else {
Serial.println("❌ WiFi not connected");
}
lastTemp = t;
lastHum = h;
} else {
Serial.println("ℹ️ No significant change, not sending");
}
delay(2000);
}