Files
beidou-satellite-data-monitor/src/main/load-serialport.js

50 lines
1.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { SerialPort } from 'serialport';
import { InterByteTimeoutParser } from '@serialport/parser-inter-byte-timeout';
import config from './config.js';
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;
const serialPort = new SerialPort({ path, baudRate });
const parser = serialPort.pipe(new InterByteTimeoutParser({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)
);