From 2d99c150e4a5dd93e355680ddde658a096eabba3 Mon Sep 17 00:00:00 2001 From: Dnovak043 Date: Thu, 12 Nov 2026 17:00:39 -0800 Subject: [PATCH 1/2] Add local sun events (sunrise, sunset, dusk, dawn...) as schedule times --- node_helper.js | 48 +++++++++---- package-lock.json | 8 ++- package.json | 3 +- sun_scheduler.js | 176 ++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 221 insertions(+), 14 deletions(-) create mode 100644 sun_scheduler.js diff --git a/node_helper.js b/node_helper.js index ede50d5..a141feb 100644 --- a/node_helper.js +++ b/node_helper.js @@ -7,6 +7,7 @@ var NodeHelper = require("node_helper"); var CronJob = require("cron").CronJob; +var Sun = require("./sun_scheduler"); // MODULE CONSTANTS const SCHEDULE_TYPE_GLOBAL = "global"; @@ -34,6 +35,7 @@ module.exports = NodeHelper.create({ this.log(this.name + " is setting the config"); this.config = payload; this.removeScheduledJobs(); + this.sunSettings = Sun.configure(payload.sun, console.log); return true; } if (notification === "CREATE_NOTIFICATION_SCHEDULE") { @@ -88,7 +90,7 @@ module.exports = NodeHelper.create({ // Create cronJobs this.log(this.name + " is scheduling " + notificationSchedule.notification + ' using "' + notificationSchedule.schedule); - var notificationJob = this.createCronJob(SCHEDULE_TYPE_NOTIFICATION, notificationSchedule.schedule, JOB_ACTION_SEND, { target: notificationSchedule.notification, payload: notificationSchedule.payload }); + var notificationJob = this.createCronJob(SCHEDULE_TYPE_NOTIFICATION, notificationSchedule.schedule, JOB_ACTION_SEND, { target: notificationSchedule.notification, payload: notificationSchedule.payload }, notificationSchedule.recalculate); if (!notificationJob) { break; } @@ -115,13 +117,13 @@ module.exports = NodeHelper.create({ // Create cronJobs this.log(this.name + " is scheduling " + module.name + ' using "' + moduleSchedule.from + '" and "' + moduleSchedule.to + '" with dim level ' + moduleSchedule.dimLevel); - var showJob = this.createCronJob(SCHEDULE_TYPE_MODULE, moduleSchedule.from, JOB_ACTION_SHOW, { target: module.id }); + var showJob = this.createCronJob(SCHEDULE_TYPE_MODULE, moduleSchedule.from, JOB_ACTION_SHOW, { target: module.id }, moduleSchedule.recalculate); if (!showJob) { break; } var hideJobAction = moduleSchedule.dimLevel ? JOB_ACTION_DIM : JOB_ACTION_HIDE; - var hideJob = this.createCronJob(SCHEDULE_TYPE_MODULE, moduleSchedule.to, hideJobAction, { target: module.id, dimLevel: moduleSchedule.dimLevel }); + var hideJob = this.createCronJob(SCHEDULE_TYPE_MODULE, moduleSchedule.to, hideJobAction, { target: module.id, dimLevel: moduleSchedule.dimLevel }, moduleSchedule.recalculate); if (!hideJob) { showJob.stop(); break; @@ -171,12 +173,12 @@ module.exports = NodeHelper.create({ // Create cronJobs this.log(this.name + " is creating a global schedule for " + groupOrAll + ' modules using "' + globalSchedule.from + '" and "' + globalSchedule.to + '" with dim level ' + globalSchedule.dimLevel); - var showJob = this.createCronJob(SCHEDULE_TYPE_GLOBAL, globalSchedule.from, JOB_ACTION_SHOW, { target: globalSchedule.groupClass, ignoreModules: globalSchedule.ignoreModules }); + var showJob = this.createCronJob(SCHEDULE_TYPE_GLOBAL, globalSchedule.from, JOB_ACTION_SHOW, { target: globalSchedule.groupClass, ignoreModules: globalSchedule.ignoreModules }, globalSchedule.recalculate); if (!showJob) { break; } var hideJobAction = globalSchedule.dimLevel ? JOB_ACTION_DIM : JOB_ACTION_HIDE; - var hideJob = this.createCronJob(SCHEDULE_TYPE_GLOBAL, globalSchedule.to, hideJobAction, { dimLevel: globalSchedule.dimLevel, target: globalSchedule.groupClass, ignoreModules: globalSchedule.ignoreModules }); + var hideJob = this.createCronJob(SCHEDULE_TYPE_GLOBAL, globalSchedule.to, hideJobAction, { dimLevel: globalSchedule.dimLevel, target: globalSchedule.groupClass, ignoreModules: globalSchedule.ignoreModules }, globalSchedule.recalculate); if (!hideJob) { showJob.stop(); break; @@ -211,10 +213,11 @@ module.exports = NodeHelper.create({ * @param {object} cronTime a cron expression which determines when the job will fire * @param {string} action the action which should be performed (either show, hide, dim or send) * @param {object} options an object containing the options for the job (e.g. target, dimLevel, ignoreModules) - * @returns {object} the scheduled cron job + * @param {string} [recalculate] for sun events: cron expression for when the event time is recalculated (overrides sun.recalculate) + * @returns {object} the scheduled cron job (or a SunCronJob for sun events) * @see CronJob */ - createCronJob: function (type, cronTime, action, options) { + createCronJob: function (type, cronTime, action, options, recalculate) { var self = this; // Validate Action @@ -227,14 +230,35 @@ module.exports = NodeHelper.create({ notification += type === SCHEDULE_TYPE_NOTIFICATION ? "_NOTIFICATION" : "_MODULE"; notification += type === SCHEDULE_TYPE_GLOBAL ? "S" : ""; + var onTick = function () { + self.log(self.name + " is sending " + notification + " to " + options.target); + self.sendSocketNotification(notification, options); + self.log(self.name + " will next send " + notification + " to " + options.target + " at " + new Date(this.nextDate()) + ' based on "' + cronTime + '"'); + }; + + // Sun event ("sunset", "dusk+15", "dawn-1h", ...) instead of a cron expression + var parsed = Sun.parse(cronTime); + if (parsed) { + if (Sun.eventNames().indexOf(parsed.event) === -1) { + console.error(this.name + ': unknown sun event "' + parsed.event + '" in "' + cronTime + '". Valid events: ' + Sun.eventNames().join(", ")); + return null; + } + if (!this.sunSettings || this.sunSettings.lat === null) { + console.error(this.name + ': "' + cronTime + '" needs a location - set sun: { lat, lon } in the MMM-ModuleScheduler config'); + return null; + } + try { + return new Sun.SunCronJob({ expression: cronTime, parsed: parsed, settings: this.sunSettings, recalculate: recalculate, onTick: onTick, log: console.log }); + } catch (ex) { + console.error(this.name + ' could not create sun schedule for "' + cronTime + '" - check the recalculate expression: "' + (recalculate || this.sunSettings.recalculate) + '"'); + return null; + } + } + try { var job = new CronJob( cronTime, - function () { - self.log(self.name + " is sending " + notification + " to " + options.target); - self.sendSocketNotification(notification, options); - self.log(self.name + " will next send " + notification + " to " + options.target + " at " + new Date(this.nextDate()) + ' based on "' + cronTime + '"'); - }, + onTick, function () { self.log(self.name + " has completed the " + action + " job for " + options.target + ' based on "' + cronTime + '"'); }, diff --git a/package-lock.json b/package-lock.json index 13ae286..1a2683b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,7 +9,8 @@ "version": "1.5.1", "license": "MIT", "dependencies": { - "cron": "^4.3.0" + "cron": "^4.3.0", + "suncalc": "^2.0.2" }, "devDependencies": { "chai": "^5.2.0", @@ -2206,6 +2207,11 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/suncalc": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/suncalc/-/suncalc-2.1.4.tgz", + "integrity": "sha512-V7oSdbSezigEpbqnNWKujDlZaE/QA/0w5IbP/vXX+eIF+EtiE8e9BkSapsOFZc84jJkI3QlklYTWtMqzj9tZQg==" + }, "node_modules/synckit": { "version": "0.9.2", "resolved": "https://registry.npmjs.org/synckit/-/synckit-0.9.2.tgz", diff --git a/package.json b/package.json index 6af3062..139b28e 100644 --- a/package.json +++ b/package.json @@ -37,6 +37,7 @@ "prettier": "^3.5.3" }, "dependencies": { - "cron": "^4.3.0" + "cron": "^4.3.0", + "suncalc": "^2.0.2" } } diff --git a/sun_scheduler.js b/sun_scheduler.js new file mode 100644 index 0000000..6269f6e --- /dev/null +++ b/sun_scheduler.js @@ -0,0 +1,176 @@ +/* Magic Mirror + * Node Helper: MMM-ModuleScheduler - local sun events + * + * Lets a schedule's `from` / `to` / `schedule` be a sun event such as "sunset", "dusk+15" + * or "dawn-1h" instead of a cron expression. Times are calculated locally with suncalc. + * + * At every recalculation (a cron expression, default daily at 00:05) the event's next + * time is worked out and scheduled as a daily cron job at that time of day. Between + * recalculations that time of day is used unchanged. + * + * MIT Licensed. + */ + +const SunCalc = require("suncalc"); +const CronJob = require("cron").CronJob; + +const DEFAULT_RECALCULATE = "0 5 0 * * *"; // every day at 00:05:00 +const EXPRESSION = /^([A-Za-z][A-Za-z0-9_]*)\s*(?:([+-])\s*(\d+(?:\.\d+)?)\s*(m|min|h)?)?$/; +const addedEvents = new Set(); // custom events already registered with suncalc (survives browser reloads) + +/** + * Names of every sun event suncalc can calculate (built-in + custom), read from its + * table of events - no sun calculation is done. + * @returns {string[]} event names + */ +function eventNames() { + const names = ["solarNoon", "nadir"]; + for (const t of SunCalc.times) names.push(t[1], t[2]); + return names; +} + +/** + * Parses "event", "event+N", "event-N" (minutes) or "event+Nh" (hours). + * @param {string} expression the from/to value + * @returns {object|null} { event, offsetMs } or null when it does not look like a sun expression + */ +function parse(expression) { + if (typeof expression !== "string") return null; + const m = expression.trim().match(EXPRESSION); + if (!m) return null; + const amount = m[3] ? Number(m[3]) * (m[4] === "h" ? 3600000 : 60000) : 0; + return { event: m[1], offsetMs: m[2] === "-" ? -amount : amount }; +} + +/** + * Reads the location and registers custom events. Called on INITIALISE_SCHEDULER. + * The location comes only from this module's own `sun.lat` / `sun.lon` config. + * @param {object} sunConfig the module's `sun` config (may be undefined) + * @param {Function} log logger + * @returns {object} settings: { lat, lon, recalculate } (lat/lon null when not set or invalid) + */ +function configure(sunConfig, log) { + const cfg = sunConfig || {}; + const settings = { lat: null, lon: null, recalculate: cfg.recalculate || DEFAULT_RECALCULATE }; + + const latOk = typeof cfg.lat === "number" && cfg.lat >= -90 && cfg.lat <= 90; + const lonOk = typeof cfg.lon === "number" && cfg.lon >= -180 && cfg.lon <= 180; + if (latOk && lonOk) { + settings.lat = cfg.lat; + settings.lon = cfg.lon; + } else if (cfg.lat !== undefined || cfg.lon !== undefined) { + console.error("MMM-ModuleScheduler: sun.lat must be a number from -90 to 90 and sun.lon a number from -180 to 180 (got " + cfg.lat + ", " + cfg.lon + ")"); + } + + for (const ev of cfg.events || []) { + if (typeof ev.angle !== "number" || !ev.rise || !ev.set) { + console.error("MMM-ModuleScheduler: custom sun event needs angle, rise and set: " + JSON.stringify(ev)); + continue; + } + const key = ev.angle + "|" + ev.rise + "|" + ev.set; + if (!addedEvents.has(key)) { + SunCalc.addTime(ev.angle, ev.rise, ev.set); + addedEvents.add(key); + } + } + + if (settings.lat !== null) log("MMM-ModuleScheduler: sun events use " + settings.lat + ", " + settings.lon + " from sun.lat / sun.lon"); + return settings; +} + +/** + * The next time the parsed event (plus offset) happens after `now`. + * @param {object} parsed result of parse() + * @param {object} settings result of configure() + * @param {Date} now reference time + * @returns {Date|null} next occurrence, or null if the event doesn't happen in the next few days (polar day/night) + */ +function nextOccurrence(parsed, settings, now) { + // Yesterday's event can only still be ahead when a positive offset pushes it past midnight (e.g. "sunset+8h") + for (let dayOffset = parsed.offsetMs > 0 ? -1 : 0; dayOffset <= 3; dayOffset++) { + const day = new Date(now.getFullYear(), now.getMonth(), now.getDate() + dayOffset, 12, 0, 0); // local noon + const t = SunCalc.getTimes(day, settings.lat, settings.lon)[parsed.event]; + if (!t || isNaN(t)) continue; + const when = new Date(Math.round((t.getTime() + parsed.offsetMs) / 1000) * 1000); + if (when > now) return when; + } + return null; +} + +/** + * Drop-in replacement for CronJob (start/stop/nextDate) that fires at a sun event. + */ +class SunCronJob { + /** + * @param {object} opts job options + * @param {string} opts.expression the original from/to value, e.g. "dusk+15" + * @param {object} opts.parsed result of parse() + * @param {object} opts.settings result of configure() + * @param {string} [opts.recalculate] cron expression for recalculation (defaults to settings.recalculate) + * @param {Function} opts.onTick called (with this job as `this`) when the event happens + * @param {Function} opts.log logger + */ + constructor({ expression, parsed, settings, recalculate, onTick, log }) { + this.expression = expression; + this.parsed = parsed; + this.settings = settings; + this.recalculateTime = recalculate || settings.recalculate; + this.onTick = onTick; + this.log = log; + this.eventJob = null; + this.cronTime = null; + // throws on an invalid recalculate expression -> caught by createCronJob + this.recalcJob = new CronJob(this.recalculateTime, () => this.recalculate(), null, true); + this.recalculate(); + } + + /** + * Works out the event's next time and (re)schedules the daily job at that time of day. + * @param {Date} now reference time (for tests) + */ + recalculate(now = new Date()) { + const next = nextOccurrence(this.parsed, this.settings, now); + if (!next) { + console.warn('MMM-ModuleScheduler: "' + this.expression + '" does not happen in the next few days at this location' + (this.eventJob ? "; keeping " + this.cronTime : "; nothing scheduled")); + return; + } + const cronTime = next.getSeconds() + " " + next.getMinutes() + " " + next.getHours() + " * * *"; + if (cronTime === this.cronTime) return; // unchanged since the last recalculation + if (this.eventJob) this.eventJob.stop(); + const self = this; + this.eventJob = new CronJob( + cronTime, + function () { + self.onTick.call(self); + }, + null, + true + ); + this.cronTime = cronTime; + this.log('MMM-ModuleScheduler: "' + this.expression + '" set to ' + pad(next.getHours()) + ":" + pad(next.getMinutes()) + ":" + pad(next.getSeconds()) + " daily (next " + next.toString() + '), recalculated on "' + this.recalculateTime + '"'); + } + + nextDate() { + return this.eventJob ? this.eventJob.nextDate() : NaN; + } + + start() { + this.recalcJob.start(); + if (this.eventJob) this.eventJob.start(); + } + + stop() { + this.recalcJob.stop(); + if (this.eventJob) this.eventJob.stop(); + } +} + +/** + * @param {number} n number + * @returns {string} two-digit string + */ +function pad(n) { + return String(n).padStart(2, "0"); +} + +module.exports = { SunCronJob, parse, configure, nextOccurrence, eventNames, DEFAULT_RECALCULATE }; From 88f7a721e76317a1e9d9264e4737500e9a6fb250 Mon Sep 17 00:00:00 2001 From: Dnovak043 Date: Thu, 12 Nov 2026 17:24:34 -0800 Subject: [PATCH 2/2] update README.md --- README.md | 87 ++++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 79 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 5e36bf8..8e9f593 100755 --- a/README.md +++ b/README.md @@ -30,14 +30,15 @@ Add the module to the modules array in the `config/config.js` file: ## Config Options -| **Option** | **Default** | **Description** | -| ----------------------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `schedulerClass` | 'scheduler' | **Optional** The name of the class which should be used to identify the modules which have an individual schedule. | -| `animationSpeed` | 1000 | **Optional** The speed of the show and hide animations in milliseconds | -| `notification_schedule` | | **Optional** A single, or array of multiple definitions to schedule when notifications should be sent. See [Scheduling Notifications](#scheduling-notifications) | -| `global_schedule` | | **Optional** A single, or array of multiple definitions to schedule when all modules should be shown/hidden/dimmed. See [Global Schedules](#global-schedules) | -| `uselock` | `true` | **Optional** If set to `false`, scheduler don't lock the hidden modules. Other modules can then be used to show the modules if they are hidden by the scheduler. | -| `debug` | `true` | **Optional** Outputs messages to the console/log when set to `true` | +| **Option** | **Default** | **Description** | +| ----------------------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `schedulerClass` | 'scheduler' | **Optional** The name of the class which should be used to identify the modules which have an individual schedule. | +| `animationSpeed` | 1000 | **Optional** The speed of the show and hide animations in milliseconds | +| `notification_schedule` | | **Optional** A single, or array of multiple definitions to schedule when notifications should be sent. See [Scheduling Notifications](#scheduling-notifications) | +| `global_schedule` | | **Optional** A single, or array of multiple definitions to schedule when all modules should be shown/hidden/dimmed. See [Global Schedules](#global-schedules) | +| `sun` | | **Optional** Location and settings for sun events such as `'sunset'` or `'dusk+15'`. Only needed if you use them. See [Sun Event Schedules](#sun-event-schedules) | +| `uselock` | `true` | **Optional** If set to `false`, scheduler don't lock the hidden modules. Other modules can then be used to show the modules if they are hidden by the scheduler. | +| `debug` | `true` | **Optional** Outputs messages to the console/log when set to `true` | ## Config Examples @@ -56,6 +57,10 @@ Module Display - [Multiple schedules](#multiple-schedules) - [Ignoring Modules](#ignoring-modules) +Sun Events + +- [Scheduling by sunrise, sunset, dusk, dawn...](#sun-event-schedules) + ### Scheduling Notifications To schedule the sending of a notification to other modules, add a `notification_schedule` definition to the MMM-ModuleScheduler config, e.g. @@ -292,12 +297,78 @@ To ignore modules from being shown, hidden or dimmed by a global schedules, add - Modules are ignored based on their name, as defined in the config file. If multiple instances of a single module are defined in the `config.js` file, all instances will be ignored using this option. +### Sun Event Schedules + +Instead of a cron expression, `from`, `to` (in `global_schedule` and `module_schedule`) and `schedule` (in `notification_schedule`) can be a sun event such as `'sunset'`, `'dusk+15'` or `'dawn-1h'`. The times are calculated locally for your location with [suncalc](https://github.com/mourner/suncalc), so they follow the seasons automatically and no internet connection or other module is needed. + +Add your location as the `sun` option, e.g. + +```javascript + { + module: 'MMM-ModuleScheduler', + config: { + sun: { lat: 47.61, lon: -122.33 }, + global_schedule: [ + // SHOW MODULES WITH THE CLASS 'night_scheduler' FROM CIVIL DUSK UNTIL CIVIL DAWN + {from: 'dusk', to: 'dawn', groupClass: 'night_scheduler'}, + // SHOW MODULES WITH THE CLASS 'daytime_scheduler' FROM 30 MINUTES AFTER SUNRISE UNTIL 1 HOUR BEFORE SUNSET + {from: 'sunrise+30', to: 'sunset-1h', groupClass: 'daytime_scheduler'}, + // CRON EXPRESSIONS STILL WORK ALONGSIDE SUN EVENTS + {from: '0 9 * * *', to: '0 17 * * *', groupClass: 'work_scheduler'} + ], + // SHOW AN ALERT AT SUNSET + notification_schedule: {notification: 'SHOW_ALERT', schedule: 'sunset', payload: {type: 'notification', title: 'Sunset'}} + } + }, +``` + +The `sun` option accepts: + +| **Option** | **Default** | **Description** | +| ------------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `lat` | | **Required for sun events** Your latitude in decimal degrees (-90 to 90, south is negative). | +| `lon` | | **Required for sun events** Your longitude in decimal degrees (-180 to 180, west is negative). | +| `recalculate` | `'0 5 0 * * *'` | **Optional** A cron expression for when sun times are recalculated. The default is every day at 00:05. Can be overridden per schedule (see below). | +| `events` | | **Optional** Custom events defined by the sun's angle, e.g. `[{angle: -3, rise: 'lateDawn', set: 'earlyDusk'}]`. The `rise` and `set` names can then be used like any other event. | + +**Sun expressions** + +An expression is an event name, optionally followed by an offset: `+` or `-`, a number, and an optional unit. No unit or `m`/`min` means minutes, and `h` means hours, e.g. `'sunset'`, `'dusk+15'`, `'dawn-30'`, `'sunset-1.5h'`. + +| **Event** | **Sun's position** | +| ------------------------------- | ------------------------------------------------- | +| `nightEnd` / `night` | 18° below the horizon (astronomical dawn / dusk) | +| `nauticalDawn` / `nauticalDusk` | 12° below the horizon | +| `dawn` / `dusk` | 6° below the horizon (civil dawn / dusk) | +| `sunrise` / `sunset` | Top edge of the sun at the horizon | +| `sunriseEnd` / `sunsetStart` | Bottom edge of the sun at the horizon | +| `goldenHourEnd` / `goldenHour` | 6° above the horizon (end / start of golden hour) | +| `solarNoon` / `nadir` | Sun at its highest / lowest | + +**Recalculation** + +At each recalculation, the next time of each sun event is worked out and the event is scheduled daily at that time of day until the next recalculation. With the default (daily), the times are always that day's. To recalculate less often for a particular schedule, add the `recalculate` option to it, e.g. + +```javascript + // RECALCULATE THESE SUN TIMES ON MONDAYS AT 03:00 INSTEAD OF DAILY + {from: 'sunrise', to: 'sunset', groupClass: 'daytime_scheduler', recalculate: '0 0 3 * * 1'} +``` + +**Notes** + +- `lat` and `lon` are only needed if a sun event is used. Without sun events, no sun times are calculated and no extra timers are created. +- Sun times use the system time zone of the device running MagicMirror, so make sure it is set correctly. +- The calculated times are logged when MagicMirror starts and whenever they change, e.g. `"dusk" set to 17:09:26 daily ... recalculated on "0 5 0 * * *"`. +- A misspelled event name or a missing location is logged as an error and that schedule is not created. As with an invalid cron expression, the remaining definitions in the same array are not scheduled either, so check the log after changing your config. +- If an event does not happen on a day (e.g. no `dusk` during summer near the poles), a warning is logged and the previous time is kept. + ## Updating To update the module to the latest version, use your terminal to go to your MMM-ModuleScheduler module folder and type the following command: ``` git pull +npm install --omit=dev ``` If you haven't changed the modules, this should work without any problems.