G

Untitled

public
Guest Dec 10, 2024 Never 13
Clone
Plaintext paste1.txt 71 lines (58 loc) | 2.4 KB
1
import mongoose from "mongoose";
2
import app from './app.js';
3
import admin from 'firebase-admin';
4
import { firebaseDB } from "./firebase/index.js";
5
import Sensor from "./modules/sensordata/sensor.model.js";
6
// import startPeriodicSync from "./firebase/syncdataFromFirebase.js";
7
// import startPeriodicSync from "./util/syncdataFromFirebase.js";
8
9
const port = process.env.PORT;
10
main().catch(err => console.log(err));
11
12
async function main() {
13
await mongoose.connect(process.env.URL);
14
15
firebaseDB.ref("testConnection").set({ connected: true })
16
.then(() => {
17
console.log("Write test passed. Firebase connected successfully.");
18
// Test read operation
19
return firebaseDB.ref("testConnection").once("value");
20
})
21
.then((snapshot) => {
22
console.log("Read test passed. Data:", snapshot.val());
23
})
24
.catch((error) => {
25
console.error("Firebase connection test failed:", error);
26
});
27
startPeriodicSync();
28
29
app.listen(port, () => {
30
console.log(`Example app listening on port ${port}`)
31
})
32
// await mongoose.connect('mongodb://user:[email protected]:27017/test'); //if your database has auth enabled
33
}
34
35
36
37
// firebase sync every minute
38
const syncSensorDataFromFirebase = async () => {
39
try {
40
console.log("Starting sensor data sync...");
41
42
// Fetch data from Firebase (assuming multiple sensors under a "Tree" node)
43
const firebaseSnapshot = await firebaseDB.ref("Tree1").once("value");
44
const treeData = firebaseSnapshot.val();
45
46
if (!treeData) {
47
console.log("No data available in Firebase under 'Tree1'.");
48
return;
49
}
50
51
// Map Firebase data to MongoDB structure
52
const { manualControl, manualDuration, sensorData, soilMoisture } = treeData;
53
54
// Update MongoDB with new data
55
const filter = { manualControl }; // Change the filter as needed to use a unique identifier
56
const update = { manualControl, manualDuration, sensorData, soilMoisture };
57
58
// Update or insert the data into MongoDB
59
await Sensor.findOneAndUpdate(filter, update, { upsert: true, new: true });
60
61
console.log("Sensor data sync complete.");
62
} catch (error) {
63
console.error("Error syncing sensor data from Firebase:", error);
64
}
65
};
66
const startPeriodicSync = () => {
67
setInterval(() => {
68
console.log("Initiating periodic sync...");
69
syncSensorDataFromFirebase();
70
}, 1 * 60 * 1000); // 10 minutes in milliseconds
71
};
72