获取串口
var callbackList = []
var isInit = false
var resultKg = ""
var resultString = ""
let port = null
export function init_() {
}
export async function init() {
const ports = await navigator.serial.getPorts();
if (ports.length > 0) {
port = ports[0]
open()
return
}
port = await navigator.serial.requestPort()
console.log(port, '===========', ports);
open()
}
const open = async () => {
await port.open({ baudRate: 9600 });
let reader = port.readable.getReader();
console.log(reader, 'reader======>');
try {
while (true) {
const { value, done } = await reader.read()
if (done) {
reader.releaseLock()
break
}
var weight = Uint8ArrayToString(value)
resultString += weight
cutStr()
dispatchEvent()
}
} catch (err) {
console.error(err)
} finally {
reader.releaseLock()
console.log('允许稍后关闭串口。')
await port.close()
}
}
const Uint8ArrayToString = (fileData) => {
var dataString = "";
for (var i = 0; i < fileData.length; i++) {
dataString += String.fromCharCode(fileData[i]);
}
return dataString
}
function cutStr() {
var haveStar = resultString.match(/\d+(\.\d+)?/g)
if (haveStar && haveStar.length > 0) {
var str = haveStar[haveStar.length - 1]
if (resultKg !== parseFloat(str || 0)) {
resultKg = parseFloat(str || 0)
}
resultString = 0
}
}
function dispatchEvent() {
setInterval(() => {
}, interval);
for (var i = 0; i < callbackList.length; i++) {
resultKg = script.getWindowName()
callbackList[i](resultKg)
}
}
export function weightAddListenerWeight(callback) {
callbackList.push(callback)
console.log(callback, 'callback', callbackList);
if (isInit == false) {
isInit = true
init()
}
}
export function weightRemoveListener(callback) {
var i = callbackList.indexOf(callback)
if (i >= 0) {
callbackList.splice(i, 1)
}
}
引用到代码
weightAddListenerWeight((res) => {
console.log("重量", res);
return;
});