-
Notifications
You must be signed in to change notification settings - Fork 7
/
sunrise.coffee
317 lines (277 loc) · 10.5 KB
/
sunrise.coffee
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
# #Sunrise plugin
module.exports = (env) ->
Promise = env.require 'bluebird'
assert = env.require 'cassert'
M = env.matcher
_ = env.require 'lodash'
suncalc = require 'suncalc'
moment = require 'moment-timezone'
events = {
sunrise:
name: 'sunrise'
desc: 'top edge of the sun appears on the horizon'
sunriseEnd:
name: 'sunrise ends'
desc: 'bottom edge of the sun touches the horizon'
goldenHourEnd:
name: 'morning golden hour'
desc: 'soft light, best time for photography ends'
solarNoon:
name: 'solar noon'
desc: 'sun is in the highest position'
goldenHour:
name: 'golden hours'
desc: 'evening golden hour starts'
sunsetStart:
name: 'sunset starts'
desc: 'bottom edge of the sun touches the horizon'
sunset:
name: 'sunset'
desc: 'sun disappears below the horizon, evening civil twilight starts'
dusk:
name: 'dusk'
desc: 'evening nautical twilight starts'
nauticalDusk:
name: 'nautical dusk'
desc: 'evening astronomical twilight starts'
night:
name: 'night starts'
desc: 'dark enough for astronomical observations'
nightEnd:
name: 'night ends'
desc: 'morning astronomical twilight starts'
nauticalDawn:
name: 'nautical dawn'
desc: 'morning nautical twilight starts'
dawn:
name: 'dawn'
desc: 'morning nautical twilight ends, morning civil twilight starts'
nadir:
name: 'nadir'
desc: 'darkest moment of the night, sun is in the lowest position'
}
class SunrisePlugin extends env.plugins.Plugin
init: (app, @framework, @config) =>
@framework.ruleManager.addPredicateProvider(new SunrisePredicateProvider @config)
deviceConfigDef = require("./device-config-schema")
@framework.deviceManager.registerDeviceClass("SunriseDevice", {
configDef: deviceConfigDef.SunriseDevice,
createCallback: (config, lastState) =>
new SunriseDevice(config, @, lastState)
})
class SunriseDevice extends env.devices.Device
constructor: (@config, @plugin, lastState) ->
@id = @config.id
@name = @config.name
@latitude = @config.latitude ? @plugin.config.latitude
@longitude = @config.longitude ? @plugin.config.longitude
@localTimezone = @config.localTimezone.trim().replace(/\ /g , "_")
@localTimezone = moment.tz.guess() if @localTimezone is ""
@localUtcOffset = parseInt(@config.localUtcOffset) * -1
@timezone = @config.timezone.trim().replace(/\ /g , "_")
@utcOffset = parseInt(@config.utcOffset) * -1
@attributes = _.cloneDeep(@attributes)
@_initTimes()
for attribute in @config.attributes
do (attribute) =>
label = attribute.name.replace /(^[a-z])|([A-Z])/g, ((match, p1, p2, offset) =>
(if offset>0 then " " else "") + match.toUpperCase())
@attributes[attribute.name] =
description: label
type: "string"
acronym: attribute.label ? label
@_createGetter attribute.name, () =>
return Promise.resolve @_transformTimezone(@eventTimes[attribute.name]).toLocaleTimeString()
super(@config)
scheduleUpdate = () =>
@_updateTimeout = setTimeout =>
if @_destroyed then return
@_initTimes()
for attribute in @config.attributes
do (attribute) =>
@emit attribute.name, @_transformTimezone(@eventTimes[attribute.name]).toLocaleTimeString()
scheduleUpdate()
, @_getTimeTillTomorrow()
scheduleUpdate()
_getTimeTillTomorrow: () ->
now = new Date()
tomorrow = new Date(now)
tomorrow.setDate(now.getDate() + 1)
tomorrow.setHours(0)
tomorrow.setMinutes(0)
tomorrow.setSeconds(0)
tomorrow.setMilliseconds(0)
return tomorrow.getTime() - now.getTime()
_getTimezoneOffsetString: (offset) ->
sign = '+'
if offset < 0
sign = '-'
offset *= -1
hours = '0' + Math.floor(offset).toString()
minutes = '0' + (Math.round(offset % 1 * 60)).toString()
sign + hours.substr(hours.length - 2) + minutes.substr(minutes.length - 2)
_transformTimezone: (date) ->
unless @timezone is ""
if @timezone in moment.tz.names()
target = moment(date).tz(@timezone).utcOffset(@utcOffset, true).format('YYYY-MM-DDTHH:mm:ss')
localTimezoneOffset =
moment.tz.zone(@localTimezone).parse(new Date(target)) + @localUtcOffset * 60
tz = @_getTimezoneOffsetString(localTimezoneOffset / -60)
date = new Date(moment(target + tz).tz('UTC').format())
else
env.logger.warn "Invalid timezone configuration for device. Skipping transformation"
return date
_initTimes: () ->
refDate = new Date()
@eventTimes = suncalc.getTimes(
new Date(refDate.getFullYear(), refDate.getMonth(), refDate.getDate(), 12, 0, 0, 0, 0),
@latitude,
@longitude
)
destroy: () ->
clearTimeout(@_updateTimeout)
super()
class SunrisePredicateProvider extends env.predicates.PredicateProvider
constructor: (@config) ->
env.logger.info """
Your location is set to lat: #{@config.latitude}, long: #{@config.longitude}
"""
return
parsePredicate: (input, context) ->
justNames = (o.name for id, o of events)
allIdsAndNames = _([id, o.name] for id, o of events).flatten().uniq().valueOf()
matchToken = null
fullMatch = null
eventId = null
timeOffset = 0
modifier = null
M(input, context)
.match(['its ', 'it is '], optional: yes)
.match(['before ', 'after '], optional: yes, (m, match) => modifier = match.trim())
.optional( (m) =>
next = m
m.matchTimeDuration((m, tp) =>
m.match([' before ', ' after '], (m, match) =>
next = m
timeOffset = tp.timeMs
if match.trim() is "before"
timeOffset = -timeOffset
)
)
return next
)
.match(allIdsAndNames, {acFilter: (s) => s in justNames}, (m, match) =>
if matchToken? and match.length < matchToken.length then return
matchToken = match
fullMatch = m.getFullMatch()
)
if matchToken?
for id, o of events
if id is matchToken or o.name is matchToken
eventId = id
assert eventId?
unless modifier? then modifier = 'exact'
return {
token: fullMatch
nextInput: input.substring(fullMatch.length)
predicateHandler: new SunrisePredicateHandler(@config, eventId, modifier, timeOffset)
}
else
return null
class SunrisePredicateHandler extends env.predicates.PredicateHandler
constructor: (@config, @eventId, @modifier, @timeOffset) ->
# gets overwritten by tests
_getNow: -> new Date()
_getEventTime: (refDate, eventId = @eventId, timeOffset = @timeOffset)->
# https://github.com/mourner/suncalc/issues/11
eventTimes = suncalc.getTimes(
new Date(refDate.getFullYear(), refDate.getMonth(), refDate.getDate(), 12, 0, 0, 0, 0),
@config.latitude,
@config.longitude
)
# add offset
eventTimeWithOffset = new Date(eventTimes[eventId].getTime() + timeOffset)
return eventTimeWithOffset
_getTimeTillEvent: ->
now = @_getNow()
refDate = new Date(now)
if @timeOffset > 0
refDate = new Date(refDate.getTime() + @timeOffset)
return @_getNextEventDate(now, refDate)
_getNextEventDate: (now, refDate) ->
eventTimeWithOffset = @_getEventTime(refDate)
timediff = eventTimeWithOffset.getTime() - now.getTime()
while timediff <= 0
# get event for next day
refDate.setDate(refDate.getDate()+1)
eventTimeWithOffset = @_getEventTime(refDate)
timediff = eventTimeWithOffset.getTime() - now.getTime()
assert timediff > 0
return timediff
_getTimeTillTomorrow: ->
now = @_getNow()
tomorrow = new Date(now)
tomorrow.setDate(now.getDate() + 1)
tomorrow.setHours(0)
tomorrow.setMinutes(0)
tomorrow.setSeconds(0)
tomorrow.setMilliseconds(0)
return tomorrow.getTime() - now.getTime()
setup: ->
setNextTimeOut = =>
switch @modifier
when 'exact'
timeTillEvent = @_getTimeTillEvent()
@timeoutHandle = setTimeout( (=>
setNextTimeOut()
@emit('change', 'event')
), timeTillEvent)
when 'before'
val = @getValueSync()
if val is true
# If its before the evnet then next change is the event date:
timeTillEvent = @_getTimeTillEvent()
@timeoutHandle = setTimeout( (=>
setNextTimeOut()
@emit('change', false)
), timeTillEvent)
else
# else its after the event, so next event date is 0:00 next day
timeTillTomorrow = @_getTimeTillTomorrow()
@timeoutHandle = setTimeout( (=>
setNextTimeOut()
@emit('change', true)
), timeTillTomorrow)
when 'after'
val = @getValueSync()
if val is false
# If its before the evnet then next change is the event date:
timeTillEvent = @_getTimeTillEvent()
@timeoutHandle = setTimeout( (=>
setNextTimeOut()
@emit('change', true)
), timeTillEvent)
else
# else its after the event, so next event date is 0:00 next day
timeTillTomorrow = @_getTimeTillTomorrow()
@timeoutHandle = setTimeout( (=>
setNextTimeOut()
@emit('change', false)
), timeTillTomorrow)
setNextTimeOut()
getType: -> if @modifier is 'exact' then 'event' else 'state'
getValueSync: ->
if @modifier is 'exact' then return false
now = @_getNow()
eventTime = @_getEventTime(now)
switch @modifier
when 'before' then return now < eventTime
when 'after' then return now > eventTime
getValue: -> Promise.resolve(@getValueSync())
destroy: ->
clearTimeout(@timeoutHandle)
# ###Finally
# Create a instance of sunrise
sunrisePlugin = new SunrisePlugin()
# and return it to the framework.
return sunrisePlugin