如何从 Web 串行 api writer 读取字节响应
我正在尝试使用 Web Serial API。我想向设备写入字节并从中读取字节响应。
我可以将字节以及字符串写入设备 - 这里一切都按预期工作。 我可以从设备读取字节和字符串 - 这里我遇到问题。 示例表明您可以创建 while(true)
循环,并且流将返回 { value, done }
标志。但我没有找到 done
标志的实际含义。当我连接到设备并开始这个循环时,它永远不会结束。
while (this.port.readable) {
try {
while (true) {
const { value, done } = await this.reader.read();
if (value) {
getChunk(value);
}
if (done) {
break;
}
}
} catch (error) {
console.error("Serial port reading error: " + error);
} finally {
this.reader.releaseLock();
}
}
我确实找到了一些有关 pipeTo
函数的建议,但它仅在字符串响应的示例中运行,此外它在我的情况下不起作用:
const textEncoder = new TextEncoderStream();
const writableStreamClosed = textEncoder.readable.pipeTo(this.port.writable);
const writer = textEncoder.writable.getWriter();
await writer.write("help");
Uncaught (in promise) TypeError: Failed to execute 'pipeTo' on 'ReadableStream': Cannot pipe to a locked stream
所以总结一下。如何通过串行 API 将字节写入设备并接收其返回的响应。
提前致谢。
I'm trying to work with Web Serial API. I want to write bytes to device and read bytes response from it.
I can write bytes as well as string to device - here everything working as expected.
I can read bytes and string from device - here I have problems.
Examples are showing that you can create a while(true)
loop and the stream will return { value, done }
flags. But I didn't find what actually done
flag means. When I'm connecting to device and start this loop, it never ends.
while (this.port.readable) {
try {
while (true) {
const { value, done } = await this.reader.read();
if (value) {
getChunk(value);
}
if (done) {
break;
}
}
} catch (error) {
console.error("Serial port reading error: " + error);
} finally {
this.reader.releaseLock();
}
}
I did find some suggestions with pipeTo
function but it only operates in examples on string responses, in addition it don't work in my case:
const textEncoder = new TextEncoderStream();
const writableStreamClosed = textEncoder.readable.pipeTo(this.port.writable);
const writer = textEncoder.writable.getWriter();
await writer.write("help");
Uncaught (in promise) TypeError: Failed to execute 'pipeTo' on 'ReadableStream': Cannot pipe to a locked stream
So to sum up. How can I write bytes to device via serial API and receive back response from it.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好的,我确实编写了自己的函数来读取给定的字节数。也许这会对某人有所帮助。
Ok, I did write my own function that reads given number of bytes. Maybe this will help someone.