Skip to content

Instantly share code, notes, and snippets.

@swissmanu
Last active April 20, 2023 06:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save swissmanu/9dc40291ecf20883603cf6bbf906bd11 to your computer and use it in GitHub Desktop.
Save swissmanu/9dc40291ecf20883603cf6bbf906bd11 to your computer and use it in GitHub Desktop.
Awtrix Light Countdown App with Node-RED. Paste code to a function node and customize the schedule on line 6 to your liking. Node will execute on any incoming message.
const prefix = "awtrix1";
const appName = "countdown";
const now = new Date();
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const schedule = [
{
date: { day: 1, month: 1 },
text: "First of January every year",
icon: "14004",
},
{
date: { day: 1, month: 2, year: 2024 },
text: "First of January at a given year",
icon: "14004",
},
];
function createNextDate({ day, month, year }, today) {
if (day && month && year) {
return new Date(year, month - 1, day);
} else if (day && month) {
if (
month < today.getMonth() + 1 ||
(day < today.getDate() && month <= today.getMonth() + 1)
) {
return new Date(today.getFullYear() + 1, month - 1, day); // Project date to next year
}
return new Date(today.getFullYear(), month - 1, day);
}
return undefined; // Skip unknown date structure
}
function findNext(schedule, today) {
return schedule
.map((s) => [createNextDate(s.date, today), s])
.sort(([a], [b]) => a - b)
.find(([date]) => {
return date && today <= date;
});
}
const next = findNext(schedule, today);
if (next) {
const [date, schedule] = next;
const daysUntil = Math.ceil((date - today) / 1000 / 60 / 60 / 24);
const hoursUntil = Math.ceil((date - today) / 1000 / 60 / 60);
const until =
hoursUntil === 0
? `Heute`
: hoursUntil < 24
? `${hoursUntil} Stunden`
: `${daysUntil} Tage`;
return {
topic: `${prefix}/custom/${appName}`,
payload: JSON.stringify({
text: `${schedule.text}: ${until}`,
icon: schedule.icon,
rainbow: next.rainbow ?? false,
}),
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment