-
Notifications
You must be signed in to change notification settings - Fork 0
/
firebase.js
55 lines (49 loc) · 1.59 KB
/
firebase.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
require("dotenv").config();
var firebaseAdmin = require("firebase-admin");
var serviceAccount = {
type: "service_account",
project_id: process.env.PROJECT_ID,
private_key_id: process.env.PRIVATE_KEY_ID,
private_key: process.env.PRIVATE_KEY,
client_email: process.env.CLIENT_EMAIL,
client_id: process.env.CLIENT_ID,
auth_uri: "https://accounts.google.com/o/oauth2/auth",
token_uri: "https://oauth2.googleapis.com/token",
auth_provider_x509_cert_url: "https://www.googleapis.com/oauth2/v1/certs",
client_x509_cert_url:
"https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-zvqgh%40piwatering-80e6c.iam.gserviceaccount.com"
};
firebaseAdmin.initializeApp({
credential: firebaseAdmin.credential.cert(serviceAccount),
databaseURL: "https://piwatering-80e6c.firebaseio.com"
});
// setup firebase refs
const rootRef = firebaseAdmin.database().ref("wateringStatus");
const envRef = rootRef.child("wellEnvironment");
const envHistoryRef = rootRef.child("wellEnvironmentHistory");
const historyTimer = 60 * 60 * 1000; //store once per minute
let counter = 0;
function updateDatabase(data, timeDelay = 4000) {
// console.log(pin, data);
var timestamp = Date.now();
for (var key in data) {
if (data.hasOwnProperty(key)) {
console.log(key + " -> " + data[key]);
envRef.child(key).set(data[key]);
if (counter == 0) {
envHistoryRef
.child(timestamp)
.child(key)
.set(data[key]);
}
}
}
if (counter > historyTimer / timeDelay) {
counter = 0;
} else {
counter++;
}
}
module.exports = {
updateDatabase
};