OSD-Frontend/src/plugins/PetMode.js

60 lines
1.6 KiB
JavaScript

import React, { useState, useEffect } from "react";
import PropTypes from "prop-types";
import GenericPageWithIcon from "./GenericPageWithIcon";
import { Sun } from "grommet-icons";
import axios from "axios";
import Telegram from "../utils/telegram";
import { CAR_API, TG_API, TG_USERID } from "../config";
function sendNotification(temp) {
if (window.sendingPetAlert)
return;
window.sendingPetAlert = true;
const bot = new Telegram(TG_API);
bot.sendMessage(TG_USERID, `The temperature in the car is ${temp}°C. Please check your child/pet.`);
window.sendingPetAlert = false;
}
function PetMode(props) {
const [ temp, setTemp ] = useState(null);
const [ , setNotified ] = useState(false);
useEffect(() => {
axios.get(`${CAR_API}data/InsideTemperature`)
.then(resp => setTemp(resp.data.value));
const id = setInterval(
() => axios.get(`${CAR_API}data/InsideTemperature`)
.then(resp => {
setTemp(resp.data.value);
if (resp.data.value > 35 || resp.data.value < 5) {
setNotified(notified => {
if (notified)
return true;
sendNotification(resp.data.value);
return true;
});
}
}),
1000
);
return () => clearInterval(id);
}, []);
if (temp === null)
return <></>;
return (
<GenericPageWithIcon
title={temp === null ? "Fetching temperature": `${temp}°C`}
description={`The temperature inside is ${temp}°C. The pet / child is ${temp > 35 ? "un": ""}safe.`}
icon={<Sun color={temp > 35 ? "status-critical": "plain"} size="xlarge" />}
close={props.close}
/>);
}
PetMode.propTypes = {
close: PropTypes.func
};
PetMode.pluginName = "Temperature";
export default PetMode;