forked from DheerajKhajuria/pimatic-mysensors
-
Notifications
You must be signed in to change notification settings - Fork 0
/
serialport.coffee
executable file
·73 lines (59 loc) · 2.23 KB
/
serialport.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
module.exports = (env) ->
events = require 'events'
serialport = require("serialport")
SerialPort = serialport.SerialPort
Promise = env.require 'bluebird'
Promise.promisifyAll(SerialPort.prototype)
class SerialPortDriver extends events.EventEmitter
constructor: (protocolOptions)->
env.logger.debug "initializing SerialPortDriver"
@serialPort = new SerialPort(protocolOptions.serialDevice, {
baudRate: protocolOptions.baudrate,
parser: serialport.parsers.readline("\n")
}, openImmediately = no)
connect: (timeout, retries) ->
# cleanup
@ready = no
@serialPort.removeAllListeners('error')
@serialPort.removeAllListeners('data')
@serialPort.removeAllListeners('close')
@serialPort.on('error', (error) => @emit('error', error) )
@serialPort.on('close', => @emit 'close' )
return @serialPort.openAsync().then( =>
#resolver = null
# setup data listener
@serialPort.on("data", (data) =>
# Sanitize data
line = data.replace(/\0/g, '').trim()
@emit('data', data)
#if line is "ready"
# @ready = yes
# @emit 'ready'
#return
#unless @ready
# got, data but was not ready => reset
# @serialPort.writeAsync("RESET\n").catch( (error) -> @emit("error", error) )
# return
@emit('line', line)
)
#return new Promise( (resolve, reject) =>
# write ping to force reset (see data listerner) if device was not reseted probably
# Promise.delay(1000).then( =>
# @serialPort.writeAsync("PING\n").catch(reject)
# ).done()
# resolver = resolve
# @once("ready", resolver)
#).timeout(timeout).catch( (err) =>
# @removeListener("ready", resolver)
# @serialPort.removeAllListeners('data')
# if err.name is "TimeoutError" and retries > 0
# @emit 'reconnect', err
# try to reconnect
# return @connect(timeout, retries-1)
# else
# throw err
#)
)
disconnect: -> @serialPort.closeAsync()
write: (data) -> @serialPort.writeAsync(data)
module.exports = SerialPortDriver