lestoitsduval-alerting/index.js

74 lines
2.1 KiB
JavaScript
Raw Normal View History

2024-09-09 18:01:24 +02:00
import Mailjet from 'node-mailjet'
const monitoringUrl = "https://monitoringapi.solaredge.com/site/2516130/overview?api_key=GVF1BZAAM74IRDZ2WRWT32A5V0CY9G4Z&format=json"
async function getData() {
const response = await fetch(monitoringUrl);
return response.json();
}
async function getCurrentPower(data) {
return data.overview.currentPower.power
}
async function getLastUpdateTime(data) {
return data.overview.lastUpdateTime
}
async function sendAlert() {
console.log("sendAlert start")
const mailjet = Mailjet.apiConnect(
process.env.MJ_APIKEY_PUBLIC,
process.env.MJ_APIKEY_PRIVATE,
);
const request = mailjet
.post('send', { version: 'v3.1' })
.request({
Messages: [
{
From: {
Email: "admin@lestoitsduval.fr",
Name: "Les Toits du Val - Salle Greyzollon Duluth"
},
To: [
{
Email: "simon@lestoitsduval.fr",
Name: "Conseil de gestion"
}
],
Subject: "😱 Alert sur la production",
TextPart: "La production est de 0 watt !",
}
]
})
request
.then((result) => {
console.log("result")
console.log(result.body)
})
.catch((err) => {
console.log("err")
console.log(err)
})
console.log("sendAlert end")
return
}
const data = await getData();
const now = new Date();
const currentPower = await getCurrentPower(data);
const lastUpdateTime = await getLastUpdateTime(data);
console.log(`[${lastUpdateTime}] La salle Greyzollon Duluth produissait ${currentPower} watt${currentPower>0?'s':''} !`)
const secondDifference = Math.ceil(Math.abs(now.getTime() - new Date(lastUpdateTime).getTime()) / 1000);
if (secondDifference > (6 * 60)) {
console.log(`❌ L'installation n'a pas répondu depuis '${lastUpdateTime}' ça fait ${secondDifference} secondes !`);
await sendAlert();
} else {
console.log(`✅ L'installation répond correctement dernière mise à jour il y a ${secondDifference} secondes.`);
}