-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
111 lines (95 loc) · 2.48 KB
/
main.js
File metadata and controls
111 lines (95 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
const { app, BrowserWindow, ipcMain, shell } = require('electron');
const { SerialPort } = require('serialport');
const path = require('path');
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: path.join(__dirname, 'preload.js')
}
});
// 隐藏菜单栏
mainWindow.setMenuBarVisibility(false);
mainWindow.loadFile('dist/index.html');
}
app.whenReady().then(createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
// Serial port operations
let serialPort = null;
ipcMain.handle('list-ports', async () => {
try {
const ports = await SerialPort.list();
return ports.map(port => ({
path: port.path,
description: port.manufacturer || port.friendlyName || port.pnpId || ''
}));
} catch (error) {
console.error('Error listing ports:', error);
return [];
}
});
ipcMain.handle('open-port', async (event, { path, baudRate }) => {
try {
if (serialPort) {
await serialPort.close();
}
serialPort = new SerialPort({ path, baudRate: parseInt(baudRate) });
serialPort.on('data', (data) => {
mainWindow.webContents.send('serial-data', data);
});
return { success: true };
} catch (error) {
return { success: false, error: error.message };
}
});
ipcMain.handle('close-port', async () => {
try {
if (serialPort) {
await serialPort.close();
serialPort = null;
}
return { success: true };
} catch (error) {
return { success: false, error: error.message };
}
});
ipcMain.handle('send-data', async (event, { data, isHex }) => {
try {
if (!serialPort) {
throw new Error('Serial port not opened');
}
let buffer;
if (isHex) {
// Convert hex string to buffer
buffer = Buffer.from(data.replace(/\s/g, ''), 'hex');
} else {
buffer = Buffer.from(data);
}
await serialPort.write(buffer);
return { success: true };
} catch (error) {
return { success: false, error: error.message };
}
});
// 添加打开外部链接的处理
ipcMain.handle('open-external', async (event, url) => {
try {
await shell.openExternal(url);
return { success: true };
} catch (error) {
return { success: false, error: error.message };
}
});