Change the blink pattern to use a pattern specified by an object.

This commit is contained in:
Pagan Gazzard 2014-12-17 17:44:34 +00:00 committed by Pablo Carranza Vélez
parent c218adb09e
commit cd2603f228

View File

@ -3,37 +3,41 @@ fs = Promise.promisifyAll require 'fs'
# Helps in blinking the LED from the given end point. # Helps in blinking the LED from the given end point.
module.exports = exports = (ledFile) -> module.exports = exports = (ledFile) ->
blink = (ms = 200) -> ledOn = ->
fs.writeFileAsync(ledFile, 1) fs.writeFileAsync(ledFile, 1)
ledOff = ->
fs.writeFileAsync(ledFile, 0)
blink = (ms = 200) ->
ledOn()
.delay(ms) .delay(ms)
.then -> fs.writeFileAsync(ledFile, 0) .then(ledOff)
blink.pattern = do -> blink.pattern = do ->
started = false pattern =
interval = null onDuration: 200
timeout = null offDuration: 200
# This function lets us have sensible param orders, blinks: 4
# and always have a timeout we can cancel. pause: 1000
delay = (ms, fn) -> blinking = null
timeout = setTimeout(fn, ms)
start = -> start = ->
interval = setInterval(blink, 400) Promise.resolve([0...pattern.blinks]).cancellable()
delay 2000, -> .each ->
# Clear the blinks after 2 second blink(pattern.onDuration)
clearInterval(interval) .delay(pattern.offDuration)
delay 2000, -> .delay(pattern.pause)
# And then repeat again after another 2 seconds .then ->
start() start()
return { return {
start: -> start: ->
return false if started return false if blinking?
started = true blinking = start()
start() return
stop: -> stop: ->
return false if not started return false if not blinking?
started = false blinking.cancel().catch(Promise.CancellationError, ->)
clearInterval(interval) ledOff()
clearTimeout(timeout) blinking = null
} }
return blink return blink