bugst / go-serial

A cross-platform serial library for go-lang.
BSD 3-Clause "New" or "Revised" License
617 stars 188 forks source link

Why read timeout return a nil error? #148

Open lu-xiaoliang opened 1 year ago

lu-xiaoliang commented 1 year ago

when i write a command, then i use io.ReadFull to read an response. But if the device do not response, it will STW. whether to return a read timeout error?

cmaglie commented 1 year ago

Unfortunately, this is a breaking change. I'm collecting all the breaking changes to be implemented in a future 2.0 release, BTW it's a low priority, for now, no estimates for when it will be done.

bmuessig commented 1 month ago

This is a simple workaround:

var errTimeout = errors.New("timeout")

type timeoutReader struct {
    r io.Reader
}

func NewTimeoutReader(r io.Reader) timeoutReader {
    return timeoutReader{r}
}

func (t timeoutReader) Read(p []byte) (n int, err error) {
    n, err = t.r.Read(p)
    if n == 0 {
        err = errTimeout
    }
    return
}

You only have to wrap your port in a NewTimeoutReader(port) and io.ReadFull and Scanner work as expected.