I want to close the serial port after a condition is met.
if (result !== null && i == 1) {
Swal.fire("error!", "", "error");
port. close();
break;
}
if (result2 !== null && i == 1) {
Swal.fire("success!", "", "success");
port. close();
break;
}
use port.close(); But the problem encountered is that the serial port cannot be close. and a warning message saying "Uncaught (in promise) TypeError: Failed to execute 'close' on 'SerialPort': Cannot cancel a locked stream at connectSerial" How should I fix it? Thanks.
async function connectSerial() {
const log = document.getElementById("target");
try {
const ports = await navigator.serial.getPorts();
const port = ports[0];
const bufferSize = 1024;
await port.open({ baudRate: 115200, bufferSize });
const decoder = new TextDecoderStream();
const inputStream = decoder.readable;
const reader = inputStream.getReader();
port.readable.pipeTo(decoder.writable);
let Number = $("#Number").val();
$.ajax({
url: "example.php",
method: "POST",
data: {
Number: Number,
},
dataType: "json",
})
.done(async function (data) {
let asciiVal = data.hex;
const encoder = new TextEncoder();
const writer = port.writable.getWriter();
await writer.write(encoder.encode(asciiVal));
})
.fail(function (jqXHR, textStatus, errorThrown) {
console.log("Ajax request failed: " + textStatus);
});
let i = 0;
while (true) {
const { value, done } = await reader.read();
if (value) {
log.textContent += value + "\n";
let text = value;
let result = text.match("CN");
let result2 = text.match("APPROVAL");
if (result !== null && i == 1) {
Swal.fire("error!", "", "error");
port.close();
break;
}
if (result2 !== null && i == 1) {
Swal.fire("success!", "", "success");
port.close();
break;
}
}
if (done) {
console.log("[readLoop] DONE", done);
reader.releaseLock();
break;
}
i++;
}
} catch (error) {
log.innerHTML = error;
}
}