This commit is contained in:
William Moore 2024-03-21 17:39:22 -05:00
parent 9e929daa9a
commit 0b7350ec57

View File

@ -1,8 +1,5 @@
import 'dotenv/config' import 'dotenv/config'
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase-admin/app";
import { getMessaging } from "firebase-admin/messaging";
import axios from 'axios'; import axios from 'axios';
import { isBefore } from 'date-fns'; import { isBefore } from 'date-fns';
@ -22,9 +19,7 @@ const firebaseConfig = {
measurementId: process.env.measurementId, measurementId: process.env.measurementId,
}; };
// Initialize Firebase let hasAlerted = false;
const app = initializeApp(firebaseConfig);
const messaging = getMessaging(app);
export type DataPoint = { export type DataPoint = {
id: string; id: string;
@ -37,10 +32,10 @@ let tempValue = 0.;
async function pullTempFromBackend() { async function pullTempFromBackend() {
try { try {
hasAlerted = false;
const response = await axios.get( const response = await axios.get(
process.env.TEASENSE_URL ?? '' process.env.TEASENSE_URL ?? ''
); );
const result = response.data.reduce( const result = response.data.reduce(
(accum: DataPoint, datum: DataPoint) => (accum: DataPoint, datum: DataPoint) =>
(accum && (accum &&
@ -55,31 +50,21 @@ async function pullTempFromBackend() {
); );
if (result?.value && result?.value >= parseInt(process.env.TEASENSE_TEMP ?? '100.0')) { if (result?.value && result?.value >= parseInt(process.env.TEASENSE_TEMP ?? '100.0')) {
tempValue = result?.value;
}
} catch (e) {
console.error(e);
} finally {
setTimeout(() => pullTempFromBackend(), 2000);
}
}
(async function () {
await pullTempFromBackend();
setInterval(async () => {
if (tempValue > 0.) {
try { try {
await messaging.send({ axios.get(process.env.TEASENSE_ALERT_URL ?? '');
notification: { hasAlerted = true;
body: `♨️ ${tempValue} C`,
},
topic: 'teasense',
});
} catch (e) { } catch (e) {
console.error(e); console.error(e);
} }
tempValue = 0.; tempValue = 0.;
} }
}, 5000); } catch (e) {
console.error(e);
} finally {
setTimeout(() => pullTempFromBackend(), hasAlerted ? 60000 : 5000);
}
}
(async function () {
await pullTempFromBackend();
})(); })();