71 lines
2.2 KiB
JavaScript
71 lines
2.2 KiB
JavaScript
|
/*
|
||
|
temperato.py - 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 Koa from 'koa';
|
||
|
import Router from '@koa/router';
|
||
|
|
||
|
const PORT = process.env.PORT || 3000;
|
||
|
const SET_POINT = parseFloat(process.env.SET_POINT);
|
||
|
const USERNAME = process.env.USERNAME;
|
||
|
const PASSWORD = process.env.PASSWORD;
|
||
|
const NOTIF_URL = process.env.NOTIF_URL;
|
||
|
const MESSAGE = process.env.MESSAGE;
|
||
|
const SENSOR_URL = process.env.SENSOR_URL;
|
||
|
const SLEEP_TIMER = 1000;
|
||
|
|
||
|
const app = new Koa();
|
||
|
const router = new Router();
|
||
|
|
||
|
router.get('/', async ctx => {
|
||
|
try {
|
||
|
const sensor = await fetch(SENSOR_URL);
|
||
|
const reading = await sensor.json();
|
||
|
ctx.body = reading;
|
||
|
} catch (e) {
|
||
|
ctx.body = 'There was an error retrieving the sensor data.';
|
||
|
ctx.status = 500;
|
||
|
}
|
||
|
});
|
||
|
|
||
|
app
|
||
|
.use(router.routes())
|
||
|
.use(router.allowedMethods());
|
||
|
|
||
|
app.listen(PORT);
|
||
|
|
||
|
async function temperatoTick() {
|
||
|
try {
|
||
|
const sensor = await fetch(SENSOR_URL);
|
||
|
const reading = await sensor.json();
|
||
|
if (reading.temperature >= SET_POINT) {
|
||
|
const basicAuth = Buffer.from(`${USERNAME}:${PASSWORD}`).toString('base64');
|
||
|
await fetch(NOTIF_URL, {
|
||
|
method: 'post',
|
||
|
body: `{"message": "${MESSAGE}"}`,
|
||
|
headers: { 'Content-Type': 'application/json', 'Authorization': `Basic ${basicAuth}` },
|
||
|
});
|
||
|
}
|
||
|
} catch (e) {
|
||
|
console.error(e);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
setInterval(() => temperatoTick(), SLEEP_TIMER);
|