-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSerialChannel.js
73 lines (56 loc) · 1.55 KB
/
SerialChannel.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
const _ = require('lodash')
const Readline = require('serialport').parsers.Readline
module.exports = class SerialChannel {
constructor(serialPort, options) {
this.options = options || {}
this.promiseQueue = []
this.serialPort = serialPort
// Bufferize Line and use as dataReceived
let lineBuffer = new Readline({
delimiter: '\r\n',
})
serialPort.pipe(lineBuffer)
lineBuffer.on('data', (data) => this.dataReceived(data))
serialPort.on('open', () => this.resetQueue())
serialPort.on('close', () => this.resetQueue())
}
resetQueue() {
let promise
while(promise = this.promiseQueue.shift())
promise.reject('Connection opening')
// this.promiseQueue = []
}
dataReceived(data) {
if (!data)
return
if (this.options.debug)
console.log('>', data)
// Make sure it's a string
data = data.toString()
// Only packets starting with `:` are responses
if (!data.startsWith(':')) {
// console.log('>', data)
return
}
// console.log('end: ', data)
let promise = this.promiseQueue.shift()
if (!promise)
return
promise.resolve(data)
}
execute(command) {
this.serialPort.write(command)
let promise = new Promise((resolve, reject) => {
let queued = {resolve, reject}
this.promiseQueue.push(queued)
// Timeout command
setTimeout(() => {
// Remove from queue
_.pull(this.promiseQueue, queued)
// Reject
reject('Timeout action')
}, 10000)
})
return promise
}
}