2021-11-16 15:52:09 +08:00
|
|
|
|
const { ipcMain } = require('electron')
|
|
|
|
|
|
const SerialPort = require('serialport')
|
2021-11-22 11:58:54 +08:00
|
|
|
|
const InterByteTimeout = require('@serialport/parser-inter-byte-timeout')
|
2021-11-16 15:52:09 +08:00
|
|
|
|
const config = require('./config')
|
|
|
|
|
|
|
2021-11-22 11:58:54 +08:00
|
|
|
|
const NMEAHandler = require('./api/NMEAHandler')
|
|
|
|
|
|
|
2021-11-16 15:52:09 +08:00
|
|
|
|
const DEFAULT_BAUDRATE = 9600
|
|
|
|
|
|
const getSerialPortConstructorArguments = (ports) => {
|
|
|
|
|
|
let 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 }
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2021-11-23 21:02:43 +08:00
|
|
|
|
const senders = []
|
2021-11-16 15:52:09 +08:00
|
|
|
|
ipcMain.on("APP_MOUNTED", (event) => {
|
2021-11-23 21:02:43 +08:00
|
|
|
|
const { sender } = event
|
|
|
|
|
|
senders.push(sender)
|
|
|
|
|
|
|
|
|
|
|
|
sender.once('destroyed', () => {
|
|
|
|
|
|
const index = senders.indexOf(sender)
|
|
|
|
|
|
if (index >= 0) senders.splice(index, 1)
|
|
|
|
|
|
})
|
2021-11-16 15:52:09 +08:00
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
|
|
const sendMsg = (channel, msg) => {
|
2021-11-23 21:02:43 +08:00
|
|
|
|
if (senders.length <= 0) return
|
|
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
|
senders.forEach((sender) => {
|
|
|
|
|
|
sender.send(channel, msg)
|
|
|
|
|
|
})
|
|
|
|
|
|
} catch (error) {
|
|
|
|
|
|
console.error(error)
|
|
|
|
|
|
}
|
2021-11-16 15:52:09 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
SerialPort.list().then((ports, err) => {
|
|
|
|
|
|
if (err) {
|
|
|
|
|
|
console.log(err)
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2021-11-22 11:58:54 +08:00
|
|
|
|
// console.log(ports, '=====================')
|
2021-11-16 15:52:09 +08:00
|
|
|
|
|
2021-11-22 11:58:54 +08:00
|
|
|
|
// 过滤掉COM1口,很多电脑自带COM1接口
|
2021-11-16 15:52:09 +08:00
|
|
|
|
ports.filter((port) => port.path != 'COM1')
|
|
|
|
|
|
if (ports.length == 0) {
|
|
|
|
|
|
console.error('设备为连接')
|
|
|
|
|
|
return
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
|
const { path, baudRate } = getSerialPortConstructorArguments(ports)
|
|
|
|
|
|
const serialPort = new SerialPort(path, { baudRate })
|
2021-11-22 11:58:54 +08:00
|
|
|
|
|
|
|
|
|
|
const parser = serialPort.pipe(new InterByteTimeout({interval: 30}))
|
|
|
|
|
|
|
|
|
|
|
|
NMEAHandler.on('handled' , (nmeaObj) => {
|
|
|
|
|
|
sendMsg('nmea', JSON.stringify(nmeaObj))
|
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
|
|
parser.on('data', (data) => NMEAHandler.handle(data.toString()))
|
2021-11-16 15:52:09 +08:00
|
|
|
|
} catch (error) {
|
|
|
|
|
|
console.error(error);
|
|
|
|
|
|
}
|
|
|
|
|
|
})
|