cacert-gosigner/shared/io.go

51 lines
1 KiB
Go

package shared
import (
"fmt"
"io"
"time"
log "github.com/sirupsen/logrus"
)
// receive at maximum the requested number of bytes from serial port and stop after the given timeout
func ReceiveBytes(port io.Reader, count int, timeout time.Duration) ([]byte, error) {
readCh := make(chan []byte, 1)
errCh := make(chan error, 1)
go func() {
sumRead := 0
for {
data := make([]byte, count)
if readBytes, err := port.Read(data); err != nil {
errCh <- err
} else if readBytes > 0 {
log.Tracef("%d bytes read", readBytes)
sumRead += readBytes
readCh <- data[0:readBytes]
} else {
readCh <- make([]byte, 0)
}
if sumRead >= count {
break
}
}
}()
select {
case <-time.After(timeout):
return nil, fmt.Errorf("timeout passed %v", timeout)
case err := <-errCh:
return nil, err
case data := <-readCh:
return data, nil
}
}
func SendBytes(port io.Writer, data []byte) error {
if bytesWritten, err := port.Write(data); err != nil {
return err
} else {
log.Tracef("wrote %d bytes", bytesWritten)
}
return nil
}