32 lines
697 B
Go
32 lines
697 B
Go
|
package shared
|
||
|
|
||
|
import (
|
||
|
"errors"
|
||
|
"github.com/goburrow/serial"
|
||
|
"io"
|
||
|
"time"
|
||
|
)
|
||
|
|
||
|
// receive the requested number of bytes from serial port and stop after the given timeout in seconds
|
||
|
func ReceiveBytes(port *serial.Port, count int, timeout time.Duration) ([]byte, error) {
|
||
|
timeoutCh := time.After(timeout * time.Second)
|
||
|
readCh := make(chan []byte, 1)
|
||
|
errCh := make(chan error, 1)
|
||
|
go func() {
|
||
|
data := make([]byte, count)
|
||
|
if _, err := io.ReadAtLeast(*port, data, count); err != nil {
|
||
|
errCh <- err
|
||
|
} else {
|
||
|
readCh <- data
|
||
|
}
|
||
|
}()
|
||
|
select {
|
||
|
case <-timeoutCh:
|
||
|
return nil, errors.New("timeout")
|
||
|
case err := <-errCh:
|
||
|
return nil, err
|
||
|
case data := <-readCh:
|
||
|
return data, nil
|
||
|
}
|
||
|
}
|