-
Notifications
You must be signed in to change notification settings - Fork 1
/
serialPort.js
55 lines (47 loc) · 1.22 KB
/
serialPort.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
const SerialPort = require('serialport')
require('events').EventEmitter.defaultMaxListeners = 0;
function buf2hex(buffer) {
return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
}
exports.getComList = () => {
return new Promise((resolve, reject) => {
SerialPort.list().then(comList => {
resolve(comList)
}).catch(err => {
reject(err)
})
})
}
exports.openCom = (comName, openOptions) => {
const port = new SerialPort(comName, openOptions)
closePort(port)
port.open();
return port;
}
function closePort(port) {
if (port.isOpen) port.close();
}
exports.closeCom = closePort;
exports.sendFrame = (port, sendFrame) => {
return port.write(sendFrame, 'hex', (err) => {
console.log(err);
})
}
exports.receiveFrame = (port) => {
return new Promise((resolve, reject) => {
port.on('data', (data) => {
resolve(buf2hex(data).toUpperCase())
})
})
}
exports.sendAndReceive = (port, sendFrame) => {
let sendFlag = port.write(sendFrame, 'hex', (err) => {
return err
})
if (sendFlag) return new Promise((resolve, reject) => {
port.on('data', (data) => {
resolve(buf2hex(data).toUpperCase())
})
})
else return 'error'
}