cacert-gosigner/shared/io.go
Jan Dittberner 80b3309c7c Use better maintained go.bug.st/serial
This commit switches to serial port library to the better maintained
go.bug.st/serial library.
2020-04-17 19:39:06 +02:00

32 lines
687 B
Go

package shared
import (
"errors"
"go.bug.st/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
}
}