2024-09-23 11:54:31 +08:00
|
|
|
|
import { SerialPort } from 'serialport'
|
|
|
|
|
|
import { InterByteTimeoutParser } from '@serialport/parser-inter-byte-timeout'
|
|
|
|
|
|
import config from './config.js'
|
2024-02-22 11:22:19 +08:00
|
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
2024-09-23 11:54:31 +08:00
|
|
|
|
const serialPort = new SerialPort({ path, baudRate })
|
|
|
|
|
|
const parser = serialPort.pipe(new InterByteTimeoutParser({interval: 300}))
|
2024-02-22 11:22:19 +08:00
|
|
|
|
|
|
|
|
|
|
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)
|
|
|
|
|
|
)
|