|
| 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 | +}; |
0 commit comments