目前原生浏览器支持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()`。
网友回复
js如何流式输出ai的回答并折叠代码块,点击代码块右侧可预览代码?
ai大模型如何将文章转换成可视化一目了然的图片流程图图表?
大模型生成html版本的ui原型图和ppt演示文档的系统提示词怎么写?
rtsp视频直播流如何转换成websocket流在h5页面上观看?
为啥coze会开源工作流agent coze studio?
如何检测网页是通过收藏夹打开的?
python如何实现类似php的http动态脚本请求处理响应代码?
js如何实现类似php的http动态脚本请求处理响应代码?
trae与solo有啥区别不同?
vue如何让ai动态生成问卷调查多步骤表单式收集基础信息自动规划执行任务?