You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
80 lines
2.3 KiB
JavaScript
80 lines
2.3 KiB
JavaScript
export const monitorSerialData = {
|
|
data() {
|
|
return {
|
|
serialPort: null,
|
|
reader: null,
|
|
decoder: new TextDecoder(),
|
|
barcode: '',//临时拼装数据使用
|
|
serialData: ''//获得的最终的条码数据
|
|
|
|
};
|
|
},
|
|
methods: {
|
|
checkSerialConnected() {
|
|
if (this.serialPort && this.serialPort.readable) {
|
|
console.log("串口当前已连接");
|
|
return true;
|
|
} else {
|
|
console.log("串口未连接或已断开");
|
|
return false;
|
|
}
|
|
},
|
|
|
|
|
|
async connectSerial(callback) {
|
|
if ('serial' in navigator) {
|
|
console.log("serial support")
|
|
try {
|
|
// 请求串口访问权限
|
|
this.serialPort = await navigator.serial.requestPort();
|
|
await this.serialPort.open({baudRate: 9600}); // 假设条码枪的波特率为9600
|
|
|
|
// 设置数据流解码
|
|
this.decoder = new TextDecoderStream();
|
|
const readableStreamClosed = this.serialPort.readable.pipeTo(this.decoder.writable);
|
|
this.reader = this.decoder.readable.getReader();
|
|
|
|
// 监听串口数据
|
|
while (true) {
|
|
const {value, done} = await this.reader.read();
|
|
if (done) {
|
|
this.reader.releaseLock();
|
|
break;
|
|
}
|
|
|
|
// console.log("---"+value);
|
|
// const data = this.decoder.decode(value);
|
|
this.processReceivedData(value, callback);
|
|
}
|
|
} catch (error) {
|
|
console.error('连接或读取串口时发生错误:', error);
|
|
} finally {
|
|
this.reader.releaseLock();
|
|
await this.serialPort.close();
|
|
}
|
|
}
|
|
},
|
|
|
|
processReceivedData(data, callback) {
|
|
// 假设条码数据以回车符或换行符结束
|
|
const barcodeEnd = /\r|\n/;
|
|
// console.log("---:" + data)
|
|
if (barcodeEnd.test(data)) {
|
|
const barcode = data.split(barcodeEnd)[0].trim(); // 获取并清理条码数据
|
|
console.log('扫描到的条码:', this.barcode + barcode);
|
|
this.serialData = this.barcode + barcode;
|
|
// 调用传入的函数
|
|
if (typeof callback === 'function') {
|
|
callback();
|
|
}
|
|
this.barcode = '';
|
|
} else {
|
|
this.barcode += data;
|
|
}
|
|
},
|
|
}
|
|
};
|
|
|
|
|
|
|