添加串口处理
This commit is contained in:
46
src/main/load-serialport.js
Normal file
46
src/main/load-serialport.js
Normal file
@@ -0,0 +1,46 @@
|
||||
const { ipcMain } = require('electron')
|
||||
const SerialPort = require('serialport')
|
||||
const Readline = require('@serialport/parser-readline')
|
||||
const config = require('./config')
|
||||
|
||||
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 }
|
||||
}
|
||||
|
||||
let sender = null
|
||||
ipcMain.on("APP_MOUNTED", (event) => {
|
||||
sender = event.sender
|
||||
})
|
||||
|
||||
const sendMsg = (channel, msg) => {
|
||||
if (sender) sender.send(channel, msg)
|
||||
}
|
||||
|
||||
SerialPort.list().then((ports, err) => {
|
||||
if (err) {
|
||||
console.log(err)
|
||||
return
|
||||
}
|
||||
|
||||
console.log(ports, '=====================')
|
||||
|
||||
// 过滤到COM1口,很多电脑自带COM1接口
|
||||
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 })
|
||||
const parser = serialPort.pipe(new Readline({ delimiter: '\r\n' }))
|
||||
parser.on('data', (data) => { sendMsg('NMEA', data) })
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user