On my connected device, i have a bit of code that sends an alert to a server through a bananaPi when battery is low
if ([batt_level] < batt_min){
this.emit('Battery Alert', msg)
}
Alert is then sent to the server and if it registers successfully to the database, it will be sent to the mailer so the user can get a notification that they need to charge their devices:
battery.js:
connection.query(stmt, [body.tag], err => {
if (err) {
res.status(400).send("battery can't be registered")
} else {
try {
mailer.sendMail(body)
res.status(200).send("battery was registered")
} catch (error) {
res.status(400).send("an error occured")
}
}
})
mailer.js:
async sendMail(message) {
try {
await this.transporter.sendMail(
{
from: process.env.MAIL_FROM,
to: process.env.MAIL_TO,
subject: `Alert on device ${message.tag}`,
text: `foo`,
html: ` </p>`
}, (err, info) => {
if (err) {
console.log(err);
}
console.log("response => %s", info);
})
} catch (error) {
console.log(error);
}
}
Now when battery gets lower than 10%, it will send 1 email alert and it is fine, but every time data gets sent to the server (5 requests per minute) and the battery is between 10% and 0% it will send a new email until battery goes back higher than 10% and that's my issue.
Is there some sort of a javascript cooldown I could implement to only send the email/alert once and where would it be the best to implement it (on the device, server, nodemailer?)? I basically want to have the sendMail function stop working for a few hours once one email is sent.
But I cannot implement a general cooldown on the sendMail function because there are a 6 different devices that go through the same mailer, so each cooldown would need to be specific to the device.
(I do not want to have a condition that only sends an alert if battery === 10% or if battery < 10% && battery > 9%, in case the charge level drops from 11% to 8% for exemple).
Thanks in advance