62 lines
2.4 KiB
JavaScript
62 lines
2.4 KiB
JavaScript
const { initializeApp, cert } = require("firebase-admin/app");
|
|
const { getDatabase } = require("firebase-admin/database");
|
|
const { getFirestore, FieldValue } = require("firebase-admin/firestore");
|
|
|
|
const serviceAccount = require("./serviceAccountKey.json");
|
|
|
|
initializeApp({
|
|
credential: cert(serviceAccount),
|
|
databaseURL: "https://tugas-akhir-9947b-default-rtdb.asia-southeast1.firebasedatabase.app"
|
|
});
|
|
|
|
const rtdb = getDatabase();
|
|
const firestore = getFirestore();
|
|
|
|
console.log("Script penyalin aktif! Memantau Sensor & Riwayat Notifikasi...");
|
|
|
|
// ==========================================
|
|
// 1. PENYALIN DATA SENSOR (Tetap Berjalan)
|
|
// ==========================================
|
|
const sensorRef = rtdb.ref("Kebun/Sensor");
|
|
sensorRef.on("value", (snapshot) => {
|
|
const dataSensor = snapshot.val();
|
|
if (dataSensor) {
|
|
dataSensor.waktu_masuk_firestore = FieldValue.serverTimestamp();
|
|
|
|
firestore.collection("sensor_data").add(dataSensor)
|
|
.then((docRef) => console.log(`[SENSOR] Data masuk ID: ${docRef.id}`))
|
|
.catch((error) => console.error("[SENSOR ERROR]", error));
|
|
}
|
|
});
|
|
|
|
// ==========================================
|
|
// 2. MENGAMBIL DARI "Kebun/Riwayat"
|
|
// ==========================================
|
|
const riwayatRef = rtdb.ref("Kebun/Riwayat");
|
|
|
|
// Menggunakan 'child_added' agar HANYA data yang baru masuk ke riwayat yang diproses
|
|
riwayatRef.on("child_added", (snapshot) => {
|
|
const dataRiwayat = snapshot.val();
|
|
|
|
// Cek apakah data ini valid dan deteksinya adalah "burung"
|
|
if (dataRiwayat && dataRiwayat.deteksi === "burung") {
|
|
|
|
// Menyusun format notifikasi untuk aplikasi Android
|
|
const dataNotifikasiBurung = {
|
|
judul: "Peringatan Hama Burung!",
|
|
pesan: `Burung terdeteksi pada jarak ${dataRiwayat.jarak} cm dengan tingkat suara ${Math.round(dataRiwayat.db)} dB.`,
|
|
waktu_kejadian: dataRiwayat.waktu, // Waktu asli dari alat Anda
|
|
jarak: dataRiwayat.jarak,
|
|
suara_db: dataRiwayat.db,
|
|
status_baca: false, // Untuk tanda "Belum Dibaca" di aplikasi
|
|
waktu_masuk_firestore: FieldValue.serverTimestamp() // Waktu masuk ke server
|
|
};
|
|
|
|
// Simpan ke dalam tabel "data_burung" di Firestore
|
|
firestore.collection("data_burung").add(dataNotifikasiBurung)
|
|
.then((docRef) => {
|
|
console.log(`[NOTIFIKASI] Data Riwayat Burung berhasil disalin! ID: ${docRef.id}`);
|
|
})
|
|
.catch((error) => console.error("[FIRESTORE ERROR]", error));
|
|
}
|
|
}); |