原文地址:https://blog.halberd.cn/artic...
成果展现
最近用 electron 做了一个利用,用于在树莓派小屏上显示一些实时信息。次要是想学习应用 electron。波及到的工具:electron, vue3, vite, flask, websocket。
这是实际效果,买的树莓派屏幕很烂:
制作过程
第一步当然是做一个可拆卸可调节的支架了,之前买的热熔胶派上用场:
- 起一个 electron 我的项目,依照网上的教程,很简略,electron.js 长这样:
const path = require('path');const { app, BrowserWindow } = require('electron');const isDev = process.env.IS_DEV === "true";function createWindow() { const mainWindow = new BrowserWindow({ fullscreen: true, webPreferences: { preload: path.join(__dirname, 'preload.js'), nodeIntegration: true, }, }); // and load the index.html of the app. // win.loadFile("index.html"); mainWindow.loadURL( isDev ? 'http://localhost:3000' : `file://${path.join(__dirname, '../dist/index.html')}` ); // Open the DevTools. if (isDev) { mainWindow.webContents.openDevTools(); }}// This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.app.whenReady().then(() => { createWindow() app.on('activate', function () { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (BrowserWindow.getAllWindows().length === 0) createWindow() })});// Quit when all windows are closed, except on macOS. There, it's common// for applications and their menu bar to stay active until the user quits// explicitly with Cmd + Q.app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit(); }});
- 前后端代码也挺简略,开源在 github: https://github.com/yunyuyuan/...。有一个 ignore 掉的配置文件./config.json 如下:
{ "host": "127.0.0.1", "port": 9876, "caiyun_token": "彩云api的token", "todo-pwd": "明码,与todo list加密明码统一", "gh_token": "github token用于获取todolist"}
- 次要是如何把前后端都跑起来,我找到了个办法,在 nodejs 里运行 python 子过程,实测不行,我也没认真钻研。看到_package.json_里
electron:dev
有一个concurrently -k "cross-env BROWSER=none yarn dev" "yarn electron"
貌似是运行多个过程,于是我把它改成concurrently -k "py/venv/bin/python py/main.py" "cross-env BROWSER=none yarn dev" "yarn electron"
,先运行 python 后端,再运行前端,能够失常运行。
其余
- 天气查问用的彩云api。
- 待办事项还是用的 github api,我专门用 react 写了一个网页 https://info.halberd.cn/ 去更新待办,树莓派每距离一分钟获取一次最新待办,其实这里能够用 github action,配合 frp 打洞(我有一台云服务器),实现更新待办后主动触发树莓派更新,不必轮询,就放个 todo 在那前面做吧sticker。
- Todo list 是用 cryptojs 加密的,尽管存在 github 上,但无需放心泄露。