目前原生浏览器支持Web Serial、WebUSB、Web Bluetooth、Web NFC等串口通讯api。
我们以为Web Serial为例:
Web Serial API是一个允许网站通过JavaScript与串行设备进行读写的API。
用户可以通过串行端口连接并与微控制器和3D打印机等设备通信。
这个API也适用于WebUSB的好伙伴,因为操作系统要求他们使用高级的串行API而不是低级的USB API与一些串行端口进行通信。要使用Web Serial API,首先需要检查浏览器是否支持该API:
if ("serial" in navigator) {
// Web Serial API is supported.
}接下来,可以使用`navigator.serial.requestPort()`提示用户选择一个串行端口,或者从`navigator.serial.getPorts()`中获取一个先前授予该网站访问权限的串行端口列表。// Prompt the user to select a port. const port = await navigator.serial.requestPort(); // Get all ports previously granted access by the website. const ports = await navigator.serial.getPorts();要打开串口,需要调用`port.open()`并指定波特率。
await port.open({ baudRate: 9600 });要读取和写入数据,可以使用`port.readable`和`port.writable`属性获取可读和可写的流。然后可以使用`TextDecoderStream`和`TextEncoderStream`将数据转换为文本。const textDecoder = new TextDecoderStream();
const readableStreamClosed = port.readable.pipeTo(textDecoder.writable);
const reader = textDecoder.readable.getReader();
// Read data from the serial device.
while (true) {
const { value, done } = await reader.read();
if (done) {
reader.releaseLock();
break;
}
console.log(value);
}
const textEncoder = new TextEncoderStream();
const writableStreamClosed = textEncoder.readable.pipeTo(port.writable);
const writer = textEncoder.writable.getWriter();
// Write data to the serial device.
await writer.write("hello");
writer.releaseLock();最后,要关闭串口,可以调用`port.close()`。 网友回复


