-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
77 lines (66 loc) · 1.61 KB
/
index.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
74
75
76
77
var SerialPort = require('serialport');
const deviceByComName = (portList, comName) => {
const device = portList.filter((device) => {
return (device.comName === comName.toUpperCase() ||
device.comName === comName);
})
return device
}
const deviceByProductId = (portList, vendorId, productId) => {
const device = portList.filter((device) => {
return ((device.vendorId === vendorId.toUpperCase() ||
device.vendorId === vendorId) && device.productId === productId);
})
return device
}
// dispatcher based on one argument to ids or two
const getDevice = (portList, comVendorName, productId) => {
if (productId === undefined) {
return deviceByComName(portList, comVendorName)
} else {
return deviceByProductId(portList, comVendorName, productId)
}
}
const isPort = async (comVendorName, productId) => {
let portList
try {
portList = await SerialPort.list()
} catch {
return false
}
const device = getDevice(portList, comVendorName, productId)
if (device.length === 1) {
return true
}
else {
return false
}
}
const getPort = async (comVendorName, productId) => {
let portList
try {
portList = await SerialPort.list()
} catch {
return false
}
const device = getDevice(portList, comVendorName, productId)
try {
const path = device[0].comName;
const port = new SerialPort(path)
return port
} catch {
return false
}
}
const sendToPort = async (port, event_code) => {
try {
port.write(Buffer.from([event_code]))
} catch (e) {
throw e
}
}
module.exports = {
isPort,
getPort,
sendToPort
}