async serial() {
// 浏览器支持serial
if ('serial' in navigator) {
// 获取用户之前授予该网站访问权限的所有串口
const ports = await navigator.serial.getPorts()
if (this.port === null) {
if (ports.length > 0) {
// 已经连接过
this.port = ports[0]
this.open()
return
}
// 提示用户选择一个串口
this.port = await navigator.serial.requestPort()
this.open()
}
} else {
alert('你的浏览器不支持串口连接')
}
},
async open() { // 打开串口
// 等待串口打开
await this.port.open({
baudRate: 9600, // 波特率
dataBits: 8, // 每帧的数据位数(7或8)
stopBits: 1, // 停止位数(1或2)
parity: 'none', // 校验模式,可以是none,偶数,奇数
flowControl: 'none' // 流控模式(none或hardware)。
})
console.log('串口打开成功', this.port)
if (this.port) {
await this.getWeight()
}
},
// 获取重量
async getWeight() {
const _this = this
this.keepReading = true
if (this.port) {
this.reader = this.port.readable.getReader()
this.writer = this.port.writable.getWriter()
this.writeInt = setInterval(async() => {
const data = new Uint8Array([2, 111, 111, 111, 111, 111, 13])
await this.writer.write(data)
}, 200)
while (_this.port.readable && this.keepReading) {
try {
while (true) {
const { value, done } = await this.reader.read()
if (done) {
this.reader.releaseLock()
break
}
console.log(weight)
var weight = _this.Uint8ArrayToString(value.reverse())
console.log(weight)
}
} catch (error) {
console.error(error)
} finally {
// 允许稍后关闭串口。
this.reader.releaseLock()
this.writer.releaseLock()
console.log('允许稍后关闭串口。')
}
}
clearInterval(this.writeInt)
await this.port.close()
}
},
// 去皮 写入串口
async peel() {
if (this.port) {
const data = new Uint8Array([2, 11, 11, 11, 136, 111, 13])
await this.writer.write(data)
console.log('去皮操作')
} else {
this.serial()
}
},
```
电子秤分两种获取,一种是连续返回,不需要发送指令获取。第二种是指令获取,发送一次指令返回一次数据。
上面是第二种电子秤的写法,如果是第一种,可以去掉发送指令的代码,直接用方法持续获取。
web 串口通讯navigator.serial
于 2021-11-22 11:46:05 首次发布