@tbowmo/node-red-small-timer
Version:
Small timer node for Node-RED with support for sunrise, sunset etc. timers
99 lines (98 loc) • 3.64 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SunAndMoon = void 0;
const date_fns_1 = require("date-fns");
const suncalc_1 = __importDefault(require("suncalc"));
const utils_1 = require("./utils");
class SunAndMoon {
constructor(latitude, longitude) {
this.latitude = latitude;
this.longitude = longitude;
this.sunTimes = undefined;
this.moonTimes = undefined;
this.lastSunCalcUpdate = -1;
this.sunLookup = {
5000: 'dawn',
5001: 'dusk',
5002: 'solarNoon',
5003: 'sunrise',
5004: 'sunset',
5005: 'night',
5006: 'nightEnd',
5007: 'rise',
5008: 'set',
5101: 'sunrise',
5102: 'sunriseEnd',
5103: 'goldenHourEnd',
5104: 'solarNoon',
5105: 'goldenHour',
5106: 'sunsetStart',
5107: 'sunset',
5108: 'dusk',
5109: 'nauticalDusk',
5110: 'night',
5111: 'nadir',
5112: 'nightEnd',
5113: 'nauticalDawn',
5114: 'dawn',
5115: 'rise',
5116: 'set',
};
}
getTimes(now = new Date()) {
if (!this.latitude || !this.longitude) {
return [];
}
this.sunTimes = suncalc_1.default.getTimes(now, this.latitude, this.longitude);
this.moonTimes = suncalc_1.default.getMoonTimes(now, this.latitude, this.longitude);
return Object.entries(this.sunLookup).map(([id, key]) => {
if (Number(id) < 5100) {
return;
}
const labelParts = key.split(/(?=[A-Z])/);
let label = labelParts.join(' ').toLocaleLowerCase();
if (this.sunTimes && key in this.sunTimes) {
label = (0, utils_1.capitalizeFirstLetter)(label);
const date = this.sunTimes[key];
return { id, label, date };
}
if (this.moonTimes && key in this.moonTimes) {
label = `Moon${label}`;
const date = this.moonTimes[key];
if (typeof date === 'object') {
return { id, label, date };
}
else {
return { id, label, date: key === 'rise' ? (0, date_fns_1.startOfDay)(Date.now()) : (0, date_fns_1.endOfDay)(Date.now()) };
}
}
}).filter(utils_1.isNotUndefinedOrNull);
}
getSunOrMoonTime(time, now = new Date()) {
const v = this.sunLookup[time];
if (this.sunTimes && v in this.sunTimes) {
const z = this.sunTimes[v];
return z;
}
if (this.moonTimes && v in this.moonTimes) {
const z = this.moonTimes[v];
if (typeof z === 'object') {
return z;
}
return v === 'set' ? (0, date_fns_1.startOfDay)(now) : (0, date_fns_1.endOfDay)(now);
}
return undefined;
}
updateSunCalc(now = new Date()) {
if (this.lastSunCalcUpdate === now.getDay() || !this.latitude || !this.longitude) {
return;
}
this.lastSunCalcUpdate = now.getDay();
this.sunTimes = suncalc_1.default.getTimes(now, this.latitude, this.longitude);
this.moonTimes = suncalc_1.default.getMoonTimes(now, this.latitude, this.longitude);
}
}
exports.SunAndMoon = SunAndMoon;