You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
97 lines
2.3 KiB
97 lines
2.3 KiB
/* |
|
* @Author: 李皓 hao_li_work@163.com |
|
* @Date: 2026-07-28 15:22:20 |
|
* @LastEditors: 李皓 hao_li_work@163.com |
|
* @LastEditTime: 2026-07-28 16:59:56 |
|
* @FilePath: \pc\main.js |
|
* @Description: |
|
* @Version: 1.0.0 |
|
*/ |
|
const { app, BrowserWindow, ipcMain } = require('electron') |
|
const path = require('path') |
|
const fs = require('fs') |
|
const { WitMotionSensor } = require('./sensor') |
|
|
|
// 缓存文件路径(存储在应用用户数据目录下) |
|
const cacheDir = app.getPath('userData') |
|
const cacheFile = path.join(cacheDir, 'app-cache.json') |
|
|
|
// 确保缓存目录存在 |
|
function ensureCacheDir() { |
|
try { |
|
if (!fs.existsSync(cacheDir)) { |
|
fs.mkdirSync(cacheDir, { recursive: true }) |
|
} |
|
} catch { /* 忽略 */ } |
|
} |
|
|
|
// 读取缓存文件 |
|
function readCache() { |
|
try { |
|
if (fs.existsSync(cacheFile)) { |
|
const raw = fs.readFileSync(cacheFile, 'utf-8') |
|
return JSON.parse(raw) |
|
} |
|
} catch { /* 忽略解析错误 */ } |
|
return {} |
|
} |
|
|
|
// 写入缓存文件 |
|
function writeCache(data) { |
|
try { |
|
ensureCacheDir() |
|
fs.writeFileSync(cacheFile, JSON.stringify(data, null, 2), 'utf-8') |
|
} catch { /* 忽略写入错误 */ } |
|
} |
|
|
|
let sensor = null |
|
|
|
const createWindow = () => { |
|
const win = new BrowserWindow({ |
|
width: 800, |
|
height: 600, |
|
webPreferences: { |
|
preload: path.join(__dirname, 'preload.js'), |
|
contextIsolation: true, |
|
nodeIntegration: false, |
|
sandbox: false |
|
} |
|
}) |
|
|
|
win.loadFile('./dist/index.html') |
|
|
|
// 窗口创建后连接传感器 |
|
sensor = new WitMotionSensor({ |
|
onData: (data) => { |
|
if (!win.isDestroyed()) { |
|
win.webContents.send('sensor-data', data) |
|
} |
|
}, |
|
onLog: (level, msg) => { |
|
console.log(`[sensor] ${msg}`) |
|
// 也发送到渲染进程,方便静态页面查看日志 |
|
if (win && !win.isDestroyed()) { |
|
try { win.webContents.send('sensor-log', { level, msg }) } catch {} |
|
} |
|
} |
|
}) |
|
sensor.connect() |
|
} |
|
|
|
app.whenReady().then(() => { |
|
// 注册 IPC 处理器:获取缓存 |
|
ipcMain.handle('get-cache', (_event, key) => { |
|
const cache = readCache() |
|
return key ? cache[key] : cache |
|
}) |
|
|
|
// 注册 IPC 处理器:设置缓存 |
|
ipcMain.handle('set-cache', (_event, key, value) => { |
|
const cache = readCache() |
|
cache[key] = value |
|
writeCache(cache) |
|
return true |
|
}) |
|
|
|
createWindow() |
|
})
|
|
|