WICG / serial

Serial ports API for the platform.
https://wicg.github.io/serial/
Other
255 stars 46 forks source link

No clear way to get a response from a write #162

Closed eleanormally closed 2 years ago

eleanormally commented 2 years ago

I'm currently trying to get a read response from a serial device, and as far as I can tell there is no clear way to do it. I have tried writing and then await a response, but it seems that the timing has to be perfect or the returned bytes will not appear in the read stream. Is there something I'm missing in how to consistently get a response from a write?

reillyeon commented 2 years ago

This kind of question is more appropriate for StackOverflow since it's about how to use the API. I will be closing this issue but will try to provide some helpful advice first.

A serial connection doesn't have a concept of a response. It provides a stream of data that gets sent to the device and a stream of data received from the device. It is up to the programmer to build concepts like requests and responses on top of that. In practice that means that while you can expect to have the response appear on the ReadableStream after writing a request to the WritableStream your code needs to handle the possibility that, for example, the response comes in small pieces rather than a single chunk. It might also be preceded by other data the device happened to be sending when the request was sent.

In this code lab, for example, we build a series of transformers which will first interpret the bytes from the device as ASCII text, then combine the chunks of data into full lines (separated by newlines), and then interpret those lines as JSON objects. Your approach will depend on the kind of data that your device sends.

I recommend starting with a loop which runs in the background and simply prints out any data received from the device as you send it requests so you can start to see how the device responds. Then you can start building code to interpret that data.