2022-05-23 18:53:41 +00:00
|
|
|
/*
|
|
|
|
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 {
|
2022-05-27 01:24:35 +00:00
|
|
|
ctx.body = `{"temperature": ${currentSensorReading}}`;
|
2022-05-23 18:53:41 +00:00
|
|
|
} 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);
|
|
|
|
|
2022-05-27 01:24:35 +00:00
|
|
|
let currentSensorReading=0.0
|
|
|
|
|
2022-05-23 18:53:41 +00:00
|
|
|
async function temperatoTick() {
|
|
|
|
try {
|
|
|
|
const sensor = await fetch(SENSOR_URL);
|
|
|
|
const reading = await sensor.json();
|
2022-05-27 01:24:35 +00:00
|
|
|
currentSensorReading = reading.temperature;
|
2022-05-23 18:53:41 +00:00
|
|
|
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);
|