前提:必須通過木子天禾打包網(wǎng)頁的桌面exe軟件才可以
1. 在JS代碼里引用SerialPort類 (需要打包的時候勾選啟用api)
const SerialPort = HTMLPackHelper.getSerialPort().SerialPort;
2. 詳細(xì)使用的細(xì)節(jié)參考 “串口通信的html代碼例子.html” 文件
3. 串口類移植于node serialport, 官方英文文檔: https://serialport.io/docs/10.x.x/guide-usage
4. 一些可以參考的中文文檔:
https://www.cnblogs.com/reachteam/p/17696071.html
https://blog.csdn.net/Naisu_kun/article/details/125146766
連接DEMO如下:
<html>
<head>
<script>
const SerialPort = HTMLPackHelper.getSerialPort().SerialPort;
let port;
let isOpened;
async function showPorts() {
let ports = await SerialPort.list();
document.getElementById("textArea").value += ports.map(port => port.path + ":" + port.friendlyName).join("\n") + "\n";
}
async function openPort() {
const portName = document.getElementById("portName").value;
port = new SerialPort({ path: portName, baudRate: 9600, autoOpen: false });
if (port.isOpened) {
try {
await port.close()
}
catch (err) {
document.getElementById("textArea").value += '端口關(guān)閉失敗!' + err.message + "\n";
return;
}
}
port.on('error', err => {
document.getElementById("textArea").value += '發(fā)生錯誤: ' + err.message + "\n";
});
port.on('data', data => {
document.getElementById("textArea").value += '收到數(shù)據(jù): ' + data + "\n";
});
port.open(function (err) {
if (err) {
document.getElementById("textArea").value += '端口打開失敗: ' + err.message + "\n";
return;
}
isOpened = true;
document.getElementById("textArea").value += '打開端口成功' + "\n";
});
}
async function sendData() {
const data = document.getElementById("data").value;
try {
port.write(data + "\n");
document.getElementById("textArea").value += '發(fā)送數(shù)據(jù)成功\n';
}
catch (err) {
document.getElementById("textArea").value += '發(fā)送數(shù)據(jù)失敗: ' + err.message+'\n';
}
}
</script>
</head>
<body>
<button onclick="showPorts()">顯示所有串口信息</button>
<div>
<textarea id="textArea" style="width: 800px;height: 600px;"></textarea>
</div>
<br>
<button onclick="openPort()">連接串口</button>
<label>串口名稱</label>
<input id="portName" type="text"></input>
<button onclick="sendData()">發(fā)送數(shù)據(jù)</button>
<input id="data" type="text"></input>
</body>
</html>