bugst / go-serial

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

Reading too few bytes #98

Closed syvanpera closed 2 years ago

syvanpera commented 3 years ago

I'm trying to read from a serial connection to a RS485 bus and the messages are 6 bytes in length. But for some reason I end up only getting 5 bytes out from the serial connection at a time. I tried using a Python library to quickly test the connection out and that seems to properly get me 6 bytes, but that also has a parameter for the Read function that can specify how many bytes should be read. Is this possible with this library? And how does it determine when it has read enough bytes from the serial connection and returns from Read?

syvanpera commented 3 years ago

Ah, actually it looks like I'm alternating between reading 5 bytes and 1 byte. So I suppose I just need to do it myself and read until the 6 bytes have been read and then use the read values. It would be nice to get a Read(n, buff) function though, where you could say that read n bytes

jlubawy commented 3 years ago

Maybe try using this? https://golang.org/pkg/io/#ReadAtLeast

syvanpera commented 3 years ago

Ah, nice! I really need to start reading the docs for all the standard libraries more. Seems to work! Thanks. I already did this to solve this issue earlier, but this is much cleaner

total := 0
for total < 6 {
      n, err := c.port.Read(buff[total:])
      if err != nil {
              log.Fatal().Err(err).Msg("Error while reading from serial connection")
      }
      total += n
}
cmaglie commented 2 years ago

Closing as not a bug.