前言
使用 Web Serial API
来实现与外接设备之间的串口通信
一、Web Serial API 是什么?
Web Serial API是一组允许网站与连接到用户计算机的外设通信的API。 它提供了连接到设备的能力,操作系统需要通过串口API进行通信。
二、使用步骤
1.检查浏览器是否支持 Web Serial API
if ("serial" in navigator) {
// 浏览器支持串口通信
}
2.提示用户选择一个串口
// 提示用户选择一个串口
const port = await navigator.serial.requestPort();
3.打开串口
//打开串口
await this.port.open({
baudRate: 9600, // 波特率
dataBits: 8, // 每帧的数据位数(7或8)
stopBits: 1, // 停止位数(1或2)
parity: 'none', // 校验模式,可以是none,偶数,奇数
flowControl: 'none' // 流控模式(none或hardware)。
})
3.读取数据
const reader = port.readable.getReader();
// 监听来自串口的数据
while (true) {
const { value, done } = await reader.read();
if (done) {
// 允许稍后关闭串口
reader.releaseLock();
break;
}
// value 是一个 Uint8Array
console.log(value);
}
总结
因为业务需求没做写入数据