44 lines
1,004 B
TypeScript
44 lines
1,004 B
TypeScript
import express from "express";
|
|
import dotenv from 'dotenv';
|
|
import * as fs from "node:fs";
|
|
import {Agent} from "undici";
|
|
|
|
if (fs.existsSync(".env")) {
|
|
dotenv.config({ path: '.env'});
|
|
}
|
|
|
|
const URI = `${process.env.DOMAIN}/api/states`;
|
|
|
|
async function getSensorValue(sensor: string): Promise<number> {
|
|
const result = await fetch(`${URI}/${sensor}`, {
|
|
dispatcher: new Agent({
|
|
connect: {
|
|
rejectUnauthorized: false
|
|
}
|
|
}),
|
|
headers: [
|
|
['Authorization', `Bearer ${process.env.TOKEN}`]
|
|
]
|
|
});
|
|
if (!result.ok) {
|
|
console.error(result)
|
|
return -1;
|
|
}
|
|
const data: unknown = await result.json();
|
|
return parseFloat(data.state);
|
|
}
|
|
|
|
const server = express()
|
|
|
|
server.use("/", express.static("public"));
|
|
|
|
server.get('/get', async (req, res) => {
|
|
const result = {
|
|
temperature: await getSensorValue(process.env.TEMPERATURE_SENSOR ?? ''),
|
|
moisture: await getSensorValue(process.env.MOISTURE_SENSOR ?? '')
|
|
}
|
|
|
|
res.json(result)
|
|
})
|
|
|
|
server.listen(8080);
|