1. 简介
项目名称 | Node SerialPort |
---|---|
主页 | https://serialport.io/ |
开源协议 | MIT |
github | https://github.com/serialport/node-serialport |
github Star | 5.2k stars(2022-6-30) |
github Fork | 989 forks(2022-6-30) |
github git地址 | https://github.com/serialport/node-serialport.git |
通过一个例子来介绍一下Node的串口通信库【SerialPort】。同时也是Electron应用程序与硬件设备通过串口进行通信的例子。文末附有完整代码。本例不会涉及任何UI框架,只使用HTML、CSS、JavaScript编写代码。重点关注就是如何进行通信。
2. 开发环境
硬件:
- 单片机: Arduino UNO
- Arudino IDE版本: v 1.8.19
- OS: windows 10
软件:
- Electron版本:v19.0.4
- Node版本:v14.19.3
- npm版本:v6.14.17
- VS Code版本:v1.68.1
- SerialPort版本:v10.4.0
3. 程序说明
本例子主要有以下功能:
- 遍历串口设备
- 打开与关闭设备
- 向设备发送数据
- 接收设备发送的数据
请先看下方的程序示意图,讲解程序将根据示意图从上往下说明如何实现的。
先放上预加载脚本preload.js
的代码,此脚本是渲染器进程与主进程IPC通信的关键。
const {
contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld('aeIo', {
/**
* 获取串口设备列表
*/
async list() {
return await ipcRenderer.invoke('aeio-list') },
/**
* 打开串口设备
* @param {串口地址} path
* @param {波特率} baudRate
*/
open: (path, baudRate = 9600) => {
ipcRenderer.send('aeio-open', path, baudRate) },
/**
* 关闭设备
*/
close:()=>{
ipcRenderer.send('aeio-close')},
/**
* 发送数据
* @param {向arduino发送的数据} data
*/
write: (data) => {
ipcRenderer.send('aeio-write', data) },
/**
* 从arduino接收数据
* @param {*} callback
*/
read: (callback) => {
ipcRenderer.on('aeio-read', callback) },
/**
* 接收消息 这个消息内容大部分都是main.js发出的,主要是用作提示
* @param {*} callback
*/
message: (callback) => {
ipcRenderer.on('aeio-message', callback) },
});
3.1 遍历串口设备
index.html
<div><button id="mBtnList" onclick="getList()">获取串口设备列表</button>设备列表:<span id="dListInfo"></span></div>
<script>
/**
* 向主进程发送获取串口设备的消息,并等待串口设备集合
**/
function getList() {
window.aeIo.list().then((list) => {
let dListInfo = document.getElementById('dListInfo');
dListInfo.innerHTML = JSON.stringify(list);
});
}
</script>
main.js
/**
* 获取串口列表
*/
ipcMain.handle('aeio-list', (ev, args) => {
return SerialPort.list().then((info, err) => {
if (err) {
sendToRenderer(error(`设备列表获取失败:${
err}`))
return [];
}
//将集合返回给界面
return info;
})
})
SerialPort.list()
方法会返回已连接的串口设备。返回的是一个集合。返回的数据集合中,每一个代表串口设备的对象都有一个path
属性,这个属性的值就是要传给打开方法。
3.2 打开与关闭设备
index.html
<div>串口设备:<input type="text" id="mInputDevPath" placeholder="请从设备列表上复制" width="200px" />波特率:<input type="text"
id="mInputDevPort" placeholder="波特率" width="200px" value="115200" /><button id="mBtnOpen"
onclick="openDevice()">打开设备</button><button id="mBtnClose" onclick="