/* temperato.py - Driver of querying service Copyright (C) 2021,2022 William R. Moore 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 . */ 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 { ctx.body = `{"temperature": ${currentSensorReading}}`; } 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); let currentSensorReading=0.0 async function temperatoTick() { try { const sensor = await fetch(SENSOR_URL); const reading = await sensor.json(); currentSensorReading = reading.temperature; 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);