cacert-gosigner/shared/io.go

44 lines
1 KiB
Go
Raw Normal View History

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