Skip to content

Ability to check whether data is available or a read timeout #122

@marciot

Description

@marciot

Right now, when you call await serial.readable.getReader().read(), it will block indefinitely if no data is available. This works alright when you know you are expecting data, but it won't work very well if you do not know this for certain or when serial errors cause data to be dropped.

It is possible to implement a read timeout using setTimeout, but I found it is somewhat tricky to get right and I had to go through several iterations to figure out how to make it work:

async read(timeout) {
    let timeoutId;
    let timeoutPromise = new Promise(
            (resolve, reject) =>
                this.timeoutId = setTimeout(
                    () => reject(new SerialTimeout("Timeout expired while waiting for data")),
                    timeout
                )
    );
    if(!this.readPromise) {
        this.readPromise = this.reader.read();
    }
    const result = await Promise.race([this.readPromise, timeoutPromise]);
    this.readPromise = null;
    clearTimeout(this.timeoutId);
    return result;
}

Having a timeout helps in some situations, but it really seems like a clumsy work around to not being able to check whether data is available before calling serial.readable.getReader().read()

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions