bugst / go-serial

A cross-platform serial library for go-lang.
BSD 3-Clause "New" or "Revised" License
681 stars 205 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 5 months 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 == nil {
        err = errTimeout
    }
    return
}

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

Updated with the suggestion from @ccollins476ad

ccollins476ad commented 4 months ago

This is a simple workaround: [...]

  if n == 0 {
      err = errTimeout
  }

Good suggestion. Just be sure not to lose the original error if there is one!

    if n == 0 && err == nil {
        err = errTimeout
    }
bmuessig commented 4 months ago

Good suggestion. Just be sure not to lose the original error if there is one!

Good catch, oops. Thanks!