forked from DheerajKhajuria/pimatic-mysensors
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ethernet.coffee
executable file
·60 lines (46 loc) · 1.3 KB
/
ethernet.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
events = require 'events'
net = require 'net'
Promise = require 'bluebird'
class EthernetDriver extends events.EventEmitter
constructor: (protocolOptions)->
@port = protocolOptions.port
@host = protocolOptions.host
connect: (timeout, retries) ->
# Create connection
@connection = net.createConnection @port, @host
# cleanup
@ready = no
# reject promise on close
@connection.on 'close', () =>
@emit('close')
# setup data listener
@connection.on 'data', (data) =>
# Sanitize data
data = data.toString()
line = data.replace(/(\r\n|\n|\r)/gm,"")
@emit('line', line)
# reject promise on error
@connection.on 'error', (error) =>
@emit('error', error)
#resolve promise on connect
@connection.on 'connect', () =>
@ready = yes
@emit 'ready'
return
return new Promise( (resolve, reject) =>
@once("ready", resolve)
@once("error", reject)
)
disconnect: ->
@connection.end()
return Promise.resolve()
write: (data) ->
if not @connection.write(data, 'utf-8', () =>
@emit "done"
)
@emit "error"
return new Promise( (resolve, reject) =>
@once("done", resolve)
@once("error", reject)
)
module.exports = EthernetDriver