teasense/src/index.ts

72 lines
2.3 KiB
TypeScript

/*
temperato.ts - Driver of querying service
Copyright (C) 2021,2022 William R. Moore <william@nerderium.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import 'dotenv/config';
import fetch from 'node-fetch';
import { Gotify, gotify } from 'gotify';
import { isBefore } from 'date-fns';
const PORT = parseInt(process.env.PORT) || 3000;
const SET_POINT = parseFloat(process.env.SET_POINT);
const MESSAGE = process.env.MESSAGE;
const EARLY_WARNING = parseFloat(process.env.EARLY_WARNING ?? process.env.SET_POINT);
const EARLY_WARNING_MESSAGE = process.env.EARLY_WARNING_MESSAGE;
const ENDPOINT = process.env.ENDPOINT;
const GOTIFY_HOST = process.env.GOTIFY_HOST;
const GOTIFY_TOKEN = process.env.GOTIFY_TOKEN;
const TICK_THRESHOLD = parseInt(process.env.TICK_THRESHOLD ?? '15');
const SLEEP_TIMER = 3000;
async function temperatoTick() {
try {
const response = await fetch(ENDPOINT, {
timeout: 5000,
});
const data: any = await response.json();
const value = data
.reduce((accum: any, datum: any) => (((accum && isBefore(new Date(accum?.timestamp), new Date(datum?.timestamp))) || !accum) ? datum : accum))
.value;
if (value < SET_POINT && value >= EARLY_WARNING) {
await gotify({
server: GOTIFY_HOST,
app: GOTIFY_TOKEN,
title: 'Warning!',
message: EARLY_WARNING_MESSAGE,
priority: 10,
});
}
if (value >= SET_POINT) {
await gotify({
server: GOTIFY_HOST,
app: GOTIFY_TOKEN,
title: 'Alert!',
message: MESSAGE,
priority: 10,
});
}
} catch (e) {
console.error(new Date(), e);
} finally {
setTimeout(() => temperatoTick(), SLEEP_TIMER);
}
}
setTimeout(() => temperatoTick(), SLEEP_TIMER);