目前原生浏览器支持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()`。
网友回复
python如何实现torrent的服务端进行文件分发p2p下载?
如何在浏览器中录制摄像头和麦克风数据为mp4视频保存下载本地?
go如何编写一个类似docker的linux的虚拟容器?
python如何写一个bittorrent的种子下载客户端?
ai能通过看一个网页的交互过程视频自主模仿复制网页编写代码吗?
ai先写功能代码通过chrome mcp来进行测试功能最后ai美化页面这个流程能行吗?
vue在手机端上下拖拽元素的时候如何禁止父元素及body的滚动导致无法拖拽完成?
使用tailwindcss如何去掉响应式自适应?
有没有直接在浏览器中运行的离线linux系统?
nginx如何保留post或get数据进行url重定向?