#include <WiFi.h>
#include <HTTPClient.h>
const char* ssid = "Wokwi-GUEST";  // Wokwi 模擬的免費 WiFi
const char* password = "";
#define PIR_PIN 34
const char* firebase_host = "project-6678b-default-rtdb.firebaseio.com";
void setup() {
  Serial.begin(115200);
  pinMode(PIR_PIN, INPUT);
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nWiFi connected");
}
void loop() {
  int motionDetected = digitalRead(PIR_PIN);
  if (motionDetected == HIGH) {
    sendMotion(true);
    Serial.println("Motion detected!");
    delay(5000); // 偵測到時延遲避免連續送資料過快
  } else {
    sendMotion(false);
    Serial.println("No motion.");
  }
  delay(2000);
}
void sendMotion(bool detected) {
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    WiFiClient client;
    String url = String("https://") + firebase_host + "/motion.json";
    http.begin(client, url);
    http.addHeader("Content-Type", "application/json");
    String body = String("{\"detected\":") + (detected ? "true" : "false") + "}";
    int httpResponseCode = http.PUT(body);
    if (httpResponseCode > 0) {
      Serial.printf("Firebase updated: %d\n", httpResponseCode);
    } else {
      Serial.printf("Error updating Firebase: %s\n", http.errorToString(httpResponseCode).c_str());
    }
    http.end();
  } else {
    Serial.println("WiFi disconnected");
  }
}