2026-03-18 16:40:36 +08:00
|
|
|
|
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';
|
2024-02-22 11:22:19 +08:00
|
|
|
|
|
2026-03-18 16:40:36 +08:00
|
|
|
|
const DEFAULT_BAUDRATE = 115200;
|
2024-02-22 11:22:19 +08:00
|
|
|
|
const getSerialPortConstructorArguments = (ports) => {
|
|
|
|
|
|
// 很多电脑自带COM1接口,过滤掉COM1口
|
2026-03-18 16:40:36 +08:00
|
|
|
|
ports = ports.filter((port) => port.path != 'COM1');
|
|
|
|
|
|
if (ports.length == 0) return;
|
2024-02-22 11:22:19 +08:00
|
|
|
|
|
2026-03-18 16:40:36 +08:00
|
|
|
|
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 };
|
|
|
|
|
|
};
|
2024-02-22 11:22:19 +08:00
|
|
|
|
|
|
|
|
|
|
const openSerialport = (ports) => {
|
|
|
|
|
|
try {
|
2026-03-18 16:40:36 +08:00
|
|
|
|
const constructorArguments = getSerialPortConstructorArguments(ports);
|
2024-02-22 11:22:19 +08:00
|
|
|
|
if (!constructorArguments) {
|
2026-03-18 16:40:36 +08:00
|
|
|
|
console.error('设备未连接');
|
|
|
|
|
|
return;
|
2024-02-22 11:22:19 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-03-18 16:40:36 +08:00
|
|
|
|
const { path, baudRate } = constructorArguments;
|
2024-02-22 11:22:19 +08:00
|
|
|
|
|
2026-03-18 16:40:36 +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) => {
|
2026-03-18 16:40:36 +08:00
|
|
|
|
sendMsg('NMEA_RECEIVED', nmeaStr);
|
|
|
|
|
|
});
|
2024-02-22 11:22:19 +08:00
|
|
|
|
|
|
|
|
|
|
NMEAHandler.on('handled' , (nmeaObj) => {
|
2026-03-18 16:40:36 +08:00
|
|
|
|
sendMsg('NMEA_HANDLED', JSON.stringify(nmeaObj));
|
|
|
|
|
|
});
|
2024-02-22 11:22:19 +08:00
|
|
|
|
|
2026-03-18 16:40:36 +08:00
|
|
|
|
parser.on('data', (data) => NMEAHandler.handle(data.toString()));
|
2024-02-22 11:22:19 +08:00
|
|
|
|
} catch (error) {
|
|
|
|
|
|
console.error(error);
|
|
|
|
|
|
}
|
2026-03-18 16:40:36 +08:00
|
|
|
|
};
|
2024-02-22 11:22:19 +08:00
|
|
|
|
|
|
|
|
|
|
SerialPort.list().then(
|
|
|
|
|
|
ports => openSerialport(ports),
|
|
|
|
|
|
err => console.error(err)
|
2026-03-18 16:40:36 +08:00
|
|
|
|
);
|