Skip to content

Commit cd4fda1

Browse files
committed
added index.js and code to test connecting to serialport
1 parent b8fdd12 commit cd4fda1

File tree

3 files changed

+1177
-0
lines changed

3 files changed

+1177
-0
lines changed

index.js

+84
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
const _ = require('lodash');
2+
const SerialPort = require('serialport');
3+
const StringDecoder = require('string_decoder').StringDecoder;
4+
const decoder = new StringDecoder('ascii');
5+
6+
const SERIAL_PORT_SETTINGS = {
7+
baudRate: 115200
8+
};
9+
10+
const getPortList = (callback) => {
11+
console.log('getPortList');
12+
13+
SerialPort.list((err, ports) => {
14+
if (!err) {
15+
let nPorts = [];
16+
17+
if (ports.length) {
18+
console.log('ports', ports);
19+
20+
ports.map((port) => {
21+
nPorts.push({
22+
key: port.comName,
23+
value: port.comName,
24+
text: port.comName
25+
});
26+
});
27+
}
28+
29+
callback(null, nPorts);
30+
} else {
31+
callback();
32+
}
33+
});
34+
};
35+
36+
getPortList((err, ports) => {
37+
if (!err) {
38+
if (ports && ports.length > 0) {
39+
// try connecting to each port
40+
let index = 0;
41+
42+
tryConnect(index, ports);
43+
}
44+
}
45+
});
46+
47+
const tryConnect = (index, ports, callback) => {
48+
const port = ports[index];
49+
50+
if (port && port.value) {
51+
console.log('try connecting to port: ' + port.value);
52+
let serialport = new SerialPort(port.value, SERIAL_PORT_SETTINGS);
53+
54+
serialport.write('V\r');
55+
56+
serialport.on('data', (data) => {
57+
//console.log('onData:', data);
58+
let textChunk = decoder.write(data);
59+
60+
// check if textChunk starts with V1
61+
if (textChunk.substring(0, 2) === 'V1') {
62+
// disconnect
63+
serialport.close();
64+
65+
// log port connected to
66+
console.log('verified connection to port: ' + port.value);
67+
}
68+
});
69+
70+
// wait for data to be received
71+
_.delay(() => {
72+
// try next port
73+
tryConnect(index + 1, ports, callback);
74+
}, 2500);
75+
76+
// receive error
77+
serialport.on('error', (error) => {
78+
//console.log('onError: ', error);
79+
});
80+
} else {
81+
console.log('ENDING CHECK');
82+
process.exit();
83+
}
84+
};

package.json

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
{
2+
"name": "node-serial-test",
3+
"version": "1.0.0",
4+
"main": "index.js",
5+
"repository": "https://github.com/nyoung697/node-serial-test.git",
6+
"author": "Nick Young <[email protected]>",
7+
"license": "MIT",
8+
"dependencies": {
9+
"lodash": "^4.17.10",
10+
"serialport": "^6.2.2",
11+
"string_decoder": "^1.1.1"
12+
}
13+
}

0 commit comments

Comments
 (0)