-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
80 lines (64 loc) · 2.46 KB
/
index.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
74
75
76
77
78
79
80
module.exports = init
var Emitter = require('events').EventEmitter
, sunCalc = require('suncalc')
, Sunwatcher = require('sunwatcher')
function init(callback) {
callback(null, 'time', Time)
}
function Time(automait, logger, config) {
Emitter.call(this)
this.automait = automait
this.logger = logger
this.config = config
determineSunTimesForLocations.call(this, config)
// run this one a day (TODO: Really needs to be start of day)
setInterval(determineSunTimesForLocations.bind(this, config), 3600000)
}
Time.prototype = Object.create(Emitter.prototype)
Time.prototype.init = function () {
setupSunEvents.call(this, this.config)
}
Time.prototype.isAfterSunset = function (locationName, callback) {
if (!this.sunTimes[locationName]) return callback(new Error('Unknown location'))
var now = new Date()
callback(null, now > this.sunTimes[locationName].sunsetStart)
}
Time.prototype.isBeforeSunset = function (locationName, callback) {
if (!this.sunTimes[locationName]) return callback(new Error('Unknown location'))
var now = new Date()
callback(null, now < this.sunTimes[locationName].sunsetStart)
}
Time.prototype.isAfterSunrise = function (locationName, callback) {
if (!this.sunTimes[locationName]) return callback(new Error('Unknown location'))
var now = new Date()
callback(null, now > this.sunTimes[locationName].sunrise)
}
Time.prototype.isBeforeSunrise = function (locationName, callback) {
if (!this.sunTimes[locationName]) return callback(new Error('Unknown location'))
var now = new Date()
callback(null, now < this.sunTimes[locationName].sunriseStart)
}
function determineSunTimesForLocations(config) {
// THIS NEEDS TO BE RE-RUN EVERYDAY (AT THE START OF THE DAY)
var sunTimes = {}
config.locations.forEach(function (location) {
var times = sunCalc.getTimes(new Date(), location.latitude, location.longitude);
sunTimes[location.name] = times
})
this.sunTimes = sunTimes
}
function setupSunEvents(config) {
config.locations.forEach(function (location) {
var sunwatcher = new Sunwatcher(location.latitude, location.longitude)
sunwatcher.on('sunrise', function() {
this.emit('sunrise:location:' + location.name)
}.bind(this))
sunwatcher.on('sunset', function() {
this.emit('sunset:location:' + location.name)
}.bind(this))
sunwatcher.on('nauticalDusk', function() {
this.emit('nauticalDusk:location:' + location.name)
}.bind(this))
sunwatcher.startSunWatch()
}.bind(this))
}