天天看點

electron結合serialport插件開發硬體指令操作項目

    electron可以開發桌面系統,serialport包是node環境下連接配接序列槽裝置的依賴,如果是用electron做硬體檢測項目,需要考慮加入serialport包,但是我們直接npm install安裝的serialport依賴,會因為binding的問題,在運作的時候報錯,是以,一般會在下載下傳安裝依賴包之後,通過electron-rebuild再次編譯,用來與electron比對。

    這裡通過實際操作來示範一個簡單的入門demo。

    本執行個體需要一些準備環境,node10.20.0 版本,另外需要安裝一個windows-build-tools,就是vc+python2.7的環境。有了這些環境,我們才能更友善的進行後續的操作。

    準備package.json

{
	"name": "electronserialport",
	"version": "0.0.1",
	"description": "",
	"main": "index.js",
	"author": "buejee",
	"license": "ISC",
	"scripts": {
		"dev": ".\\node_modules\\.bin\\electron ."
	},
	"dependencies": {
		"serialport": "^8.0.7"
	},
	"devDependencies": {
		"electron": "^2.0.4",
		"electron-rebuild": "^1.10.1"
	}
}
           

    electron主檔案index.js

const {app,BrowserWindow,dialog} = require("electron")
const path = require("path")
const url = require("url")
let win;
app.on("ready",()=>{
	win = new BrowserWindow()
	win.on("close",()=>{
		win = null;
	})
	win.loadURL(url.format({
		pathname:path.join(__dirname,'index.html'),
		protocol:'file',
		slashes:true
	}))
	win.webContents.openDevTools();
})

app.on("window-all-closed",()=>{
	app.quit();
})
           

    序列槽測試子產品檔案serialportmodule.js

const Serialport = require("serialport");
Serialport.list().then((ports)=>{
	console.log(ports);
})

const $ = (id)=>{
	return document.getElementById(id);
}

let cnt = 0;
setInterval(()=>{
	$("count").textContent = cnt;
	cnt++;
},1000);
           

    主界面 index.html

<!doctype html>
<html>
	<head>
		<meta charset="utf-8"/>
		<title>demo</title>
	</head>
	<body>
		<h2>hello,electron,serialport.</h2>
		<div id="count"></div>
	</body>
	<script>
		require("./serialportmodule.js");
	</script>
</html>
           

    以上檔案準備好了,可以進入項目所在的目錄下的指令行。

    1、npm install

    2、.\node_modules\.bin\electron-rebuild -f -w serialport

    3、 npm run dev

    以上第一步是安裝依賴,包括項目依賴和運作依賴,第二步是對第一步中安裝的serialport依賴做重新編譯,因為預設運作會報錯。第三步是進行啟動項目的操作。具體會執行package.json檔案中的scripts下的dev指令。

    最後,運作界面截圖:

electron結合serialport插件開發硬體指令操作項目

    控制台隻是列印了一個空數組,因為電腦沒有連接配接序列槽裝置, 但是沒有報錯,證明electron與serialport結合是沒有問題的。

繼續閱讀