文章目录

  • 前言
    • 1、打开串口 提示用户选择一个串口(因为浏览器安全策略原因,用户必须选择一次)
    • 2.读取数据
    • 3、解析函数
      • 值得注意的点:
    • 1、如果不想每次都让用户选择串口 可以使用公共变量将用户选择的串口 存储下来(cookie和localstorage不行。)。这样就可以在不同的页面 打开或者关闭同一个串口。重复使用
  • 总结

前言

一:Web Serial API 是什么
串口是一个双向通信接口,允许字节发送和接收数据。

Web Serial API为网站提供了一种使用JavaScript对串行设备进行读写的方法。串行设备可以通过用户系统上的串行端口连接,也可以通过模拟串行端口的可移动USB和蓝牙设备连接。

换句话说,Web Serial API通过允许网站与串行设备(如微控制器和3D打印机)通信来连接网络和物理世界。

该API是JS本身navigator对象上就独有的,所以与任何框架开发都没有太大的关系,不管你是用Vue还是React开发。
要使用该API需要服务器使用https协议,同时呢,本地开发建议使用http://localhost:端口号。


二、使用步骤
大致使用的步骤如下:
1、请求用户授权访问串行端口
2、设置串行端口的参数,例如波特率、数据位、停止位、奇偶校验等。
2、打开和关闭串行端口
3、读取和写入串行数据
4、监听来自串行设备的数据
三:具体代码

1、打开串口 提示用户选择一个串口(因为浏览器安全策略原因,用户必须选择一次)

 async test() { // 打开串口
      // 浏览器支持serial
      if ('serial' in navigator) {
        // 获取用户之前授予该网站访问权限的所有串口
        if (this.port==null) {
          console.log("有串口::::",this.globalVariable)
          if (this.globalVariable) {
           this.port= this.globalVariable
           console.log("00000000000::",this.globalVariable)
           this.open()
            return
          }
          // 提示用户选择一个串口
          this.port = await navigator.serial.requestPort()
           this.globalVariable = this.port
           console.log("11111111111::",this.globalVariable)
          this.open()
        } else {
          console.log("你的电脑没有串口")
        }
      } else {
        alert('你的浏览器不支持串口连接')
      }
    },

2.读取数据

代码如下:
注意点:串口数据是分几次读取到的。所以需要判断的。我这里额外加了一个keepReading 变量来控制读取的开关

async open() { // 打开串口
// 等待串口打开
console.log("进入open")
await  this.port.open({
baudRate: 115200, // 波特率
dataBits: 8, // 每帧的数据位数(7或8)
stopBits: 1, // 停止位数(1或2)
parity: 'none', // 校验模式,可以是none,偶数,奇数
flowControl: 'none' // 流控模式(none或hardware)。
})
console.log('串口打开成功', this.port)
if (this.port) {
//  let _this=this
this.reader = this.port.readable.getReader()
let mseeage=''
while (this.port.readable && this.keepReading) {
try {
while (true) {
let { value, done } = await this.reader.read()
console.log("value",value)
var weight = this.Uint8ArrayToString(value)
if(weight.length>0){
mseeage+=weight
}
if(mseeage.includes('
')){
mseeage=mseeage.split("
")[0]
if(mseeage.indexOf("up")>-1){
mseeage=mseeage.substring(mseeage.indexOf("up"),mseeage.length-1)
}
console.log("iiiiiiiiiiii"+this.keepReading)
console.log("接收到的数据:",mseeage)
if(this.keepReading){
this.ccsOrder=mseeage
this.serchOrder()
//  alert(mseeage.trim(0))
}
mseeage=''
}
this.resetCountdown()
//  if(!this.keepReading){
//    break
//  }
}
} catch (error) {
console.error(error)
} finally {
// 允许稍后关闭串口。
this.reader.releaseLock()
this.port.close()
console.log('允许稍后关闭串口。')
}
}
}
}

3、解析函数

Uint8ArrayToString(uint8Array) {
let string = '';
let i = 0;
while (i < uint8Array.length) {
let byte1 = uint8Array[i];
let charCode = 0;
if (byte1 < 0x80) {
charCode = byte1;
i += 1;
} else if (byte1 < 0xE0) {
let byte2 = uint8Array[i + 1];
charCode = ((byte1 & 0x1F) << 6) | (byte2 & 0x3F);
i += 2;
} else {
let byte2 = uint8Array[i + 1];
let byte3 = uint8Array[i + 2];
charCode =
((byte1 & 0x0F) << 12) |
((byte2 & 0x3F) << 6) |
(byte3 & 0x3F);
i += 3;
}
string += String.fromCharCode(charCode);
}
return string;
}

值得注意的点:

1、如果不想每次都让用户选择串口 可以使用公共变量将用户选择的串口 存储下来(cookie和localstorage不行。)。这样就可以在不同的页面 打开或者关闭同一个串口。重复使用

总结

是一个比较方便的,网页和串口通信的技术。缺点就是刷新页面就得去选择一次串口。所以适合页面不会频繁刷新的场景。

本站无任何商业行为
个人在线分享 » 网页与串口通信:Web Serial API 使用记录
E-->