我正在尝试从硬件读取数据。
该程序应如下所示:
- 将书签发送到硬件
await writer.write(encoder.encode("X"));
- 设备得到书签,现在知道它必须发回数据。我让缓冲区溢出并等待 1 秒以等待所有数据到达。此外,数据通过AJAX发送到后台软件。
setTimeout(async function () {
...
}, 1000);
在下一步中,我想关闭 COM 端口,以便用户可以在必要时再次读取。最简单的方法是关闭端口并调用相同的方法。
但我不知道该怎么做。实际上,数据传输成功后,我的程序应该保存在
if (done){
}
环形。但这不会发生。至少 console.log 没有列出。
代码:
if ("serial" in navigator) {
hardwareData = '';
readData();
async function readData() {
console.log('read');
//Prompt the user to select any serial port.
const port = await navigator.serial.requestPort();
// Waits until the serial interface is open. + hardware Parameter.
await port.open({ baudRate: 115200, dataBits: 8, stopBits: 1, parity: "none" });
//Send "X" to hardware
const encoder = new TextEncoder();
const writer = port.writable.getWriter();
await writer.write(encoder.encode("X"));
writer.releaseLock();
//Wait 1 second and read Port
setTimeout(async function () {
// Port read
while (port.readable) {
const reader = port.readable.getReader();
try {
while (true) {
const { value, done } = await reader.read();
if (done) {
// Allow the serial interface to be closed.
reader.releaseLock();
console.log('test');
break;
}
if (value) {
//console.log(value);
hardwareData = hardwareData + new TextDecoder().decode(value);
hardwareData = hardwareData.replace(/\s/g, '');
var res = et2Daten.split(";");
var anzahl = res.length;
if (anzahl == 173 || anzahl == 169) {
console.log("Anzahl: " + anzahl);
//console.log(et2Daten);
$.ajax({
url: APPLICATION_PATH + 'Home/ReadDataFromET2',
type: 'POST',
dataType: 'json',
data: JSON.stringify({
'data': et2Daten,
}),
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
},
error: function (request) {
}
});
}
}
}
} catch (error) {
console.log("Error");
}
}
}, 1000);
}
}
有谁知道如何最有效地关闭我的端口?