主要版本
This commit is contained in:
51
src/main/load-serialport.js
Normal file
51
src/main/load-serialport.js
Normal file
@@ -0,0 +1,51 @@
|
||||
import SerialPort from 'serialport'
|
||||
import InterByteTimeout from '@serialport/parser-inter-byte-timeout'
|
||||
import config from './config'
|
||||
import sendMsg from './ipcRendererManager'
|
||||
import NMEAHandler from './api/NMEAHandler'
|
||||
|
||||
const DEFAULT_BAUDRATE = 115200
|
||||
const getSerialPortConstructorArguments = (ports) => {
|
||||
// 很多电脑自带COM1接口,过滤掉COM1口
|
||||
ports = ports.filter((port) => port.path != 'COM1')
|
||||
if (ports.length == 0) return
|
||||
|
||||
// console.log(ports, '=====================')
|
||||
const serialport = config.get('serialport')
|
||||
const path = ( serialport && serialport.path ) ? serialport.path : ports[0].path
|
||||
const baudRate = ( serialport && serialport.baudRate ) ? serialport.baudRate : DEFAULT_BAUDRATE
|
||||
return { path, baudRate }
|
||||
}
|
||||
|
||||
const openSerialport = (ports) => {
|
||||
try {
|
||||
const constructorArguments = getSerialPortConstructorArguments(ports)
|
||||
if (!constructorArguments) {
|
||||
console.error('设备未连接')
|
||||
return
|
||||
}
|
||||
|
||||
const { path, baudRate } = constructorArguments
|
||||
|
||||
// console.log(path, baudRate, '++++++++++++++===');
|
||||
const serialPort = new SerialPort(path, { baudRate })
|
||||
const parser = serialPort.pipe(new InterByteTimeout({interval: 300}))
|
||||
|
||||
NMEAHandler.on('received' , (nmeaStr) => {
|
||||
sendMsg('NMEA_RECEIVED', nmeaStr)
|
||||
})
|
||||
|
||||
NMEAHandler.on('handled' , (nmeaObj) => {
|
||||
sendMsg('NMEA_HANDLED', JSON.stringify(nmeaObj))
|
||||
})
|
||||
|
||||
parser.on('data', (data) => NMEAHandler.handle(data.toString()))
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
|
||||
SerialPort.list().then(
|
||||
ports => openSerialport(ports),
|
||||
err => console.error(err)
|
||||
)
|
||||
Reference in New Issue
Block a user