-
Notifications
You must be signed in to change notification settings - Fork 1
/
suncalc.js
73 lines (59 loc) · 2.51 KB
/
suncalc.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
var SunCalc = require('suncalc');
var moment = require('moment');
var logging = require('./logging.js');
const suncalcConfig = {
"lat": null,
"lon": null
};
configure = (latitude, longitude) => {
suncalcConfig.lat = parseFloat(latitude);
suncalcConfig.lon = parseFloat(longitude);
logging.add("Suncalc Location Configured "+suncalcConfig.lat+" "+suncalcConfig.lon);
};
const suncalcStringToTime = (configString) => {
newJob = {
time: configString
};
// Try to convert the string to an actual time to plan the cronjob for
const regexTime = /^([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])$/;
const regexSun = /^(sunrise|sunriseEnd|goldenHourEnd|solarNoon|goldenHour|sunsetStart|sunset|dusk|nauticalDusk|night|nadir|nightEnd|nauticalDawn|dawn)([+-]\d+)$/i;
var h = null;
var m = null;
// Is it a simple time? 00-23:00:59
if (found = configString.match(regexTime)) {
h = parseInt(found[1]);
m = parseInt(found[2]);
return {h: h,m: m};
}
// Is it a suncalc offset?
else if (found = configString.match(regexSun)) {
let suncalcObj = found[1]; // Which Suncalc Object is required (e.g. sunset, sunrise)
let offsetMin = parseInt(found[2]); // The minute offset
if(!isNaN(suncalcConfig.lat) && !isNaN(suncalcConfig.lon)) {
// Get the Date for the required Suncalc Parameter
suncalcObjDate = SunCalc.getTimes(new Date(), suncalcConfig.lat, suncalcConfig.lon)[suncalcObj];
// Add the offset, convert it to local time
actionDate = moment(suncalcObjDate).add(offsetMin, 'minutes').local();
// Only process if the actionDate actually makes sense
if (actionDate.isValid()) {
// Get Hours and Minutes
h = actionDate.format('H');
m = actionDate.format('m');
return {h: h,m: m};
}
else {
// TODO: Add Error logging, that suncalcObj could not be determined (wrong location?)
logging.add("Suncalc Determination failed. Invalid Location?","warn")
}
}
else {
logging.add("Suncalc determination failed. Please specificy location.lat and .lon in the config to use sun related timings","warn")
}
}
else {
logging.add("Suncalc determination failed. Invalid time "+configString,"warn")
}
return false;
};
exports.configure = configure;
exports.suncalcStringToTime = suncalcStringToTime;