2020-04-17 19:38:54 +02:00
|
|
|
package shared
|
|
|
|
|
|
|
|
import (
|
2021-01-05 19:59:43 +01:00
|
|
|
"bytes"
|
2020-04-19 22:29:58 +02:00
|
|
|
"fmt"
|
2020-04-17 19:38:54 +02:00
|
|
|
"io"
|
|
|
|
"time"
|
2021-01-04 14:15:12 +01:00
|
|
|
|
|
|
|
log "github.com/sirupsen/logrus"
|
2020-04-17 19:38:54 +02:00
|
|
|
)
|
|
|
|
|
2020-04-19 22:29:58 +02:00
|
|
|
// receive at maximum the requested number of bytes from serial port and stop after the given timeout
|
2021-01-04 14:15:12 +01:00
|
|
|
func ReceiveBytes(port io.Reader, count int, timeout time.Duration) ([]byte, error) {
|
2020-04-17 19:38:54 +02:00
|
|
|
readCh := make(chan []byte, 1)
|
|
|
|
errCh := make(chan error, 1)
|
|
|
|
go func() {
|
2021-01-05 19:59:43 +01:00
|
|
|
buffer := bytes.NewBuffer([]byte{})
|
|
|
|
for remainder := count; remainder > 0; {
|
|
|
|
data := make([]byte, remainder)
|
2021-01-04 14:15:12 +01:00
|
|
|
if readBytes, err := port.Read(data); err != nil {
|
|
|
|
errCh <- err
|
2021-01-05 19:59:43 +01:00
|
|
|
return
|
2021-01-04 14:15:12 +01:00
|
|
|
} else if readBytes > 0 {
|
2021-01-05 19:59:43 +01:00
|
|
|
buffer.Write(data[0:readBytes])
|
|
|
|
remainder -= readBytes
|
|
|
|
log.Tracef("%d bytes read, remaining %d", readBytes, remainder)
|
2021-01-04 14:15:12 +01:00
|
|
|
}
|
2020-04-17 19:38:54 +02:00
|
|
|
}
|
2021-01-05 19:59:43 +01:00
|
|
|
readCh <- buffer.Bytes()
|
|
|
|
close(readCh)
|
2020-04-17 19:38:54 +02:00
|
|
|
}()
|
2021-01-05 19:59:43 +01:00
|
|
|
|
|
|
|
buffer := bytes.NewBuffer([]byte{})
|
2020-04-17 19:38:54 +02:00
|
|
|
select {
|
2020-04-19 22:29:58 +02:00
|
|
|
case <-time.After(timeout):
|
2021-01-04 14:15:12 +01:00
|
|
|
return nil, fmt.Errorf("timeout passed %v", timeout)
|
2020-04-17 19:38:54 +02:00
|
|
|
case err := <-errCh:
|
|
|
|
return nil, err
|
|
|
|
case data := <-readCh:
|
2021-01-05 19:59:43 +01:00
|
|
|
log.Tracef("received %d bytes from channel", len(data))
|
|
|
|
if data == nil {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
buffer.Write(data)
|
2020-04-17 19:38:54 +02:00
|
|
|
}
|
2021-01-05 19:59:43 +01:00
|
|
|
return buffer.Bytes(), nil
|
2020-04-17 19:38:54 +02:00
|
|
|
}
|
2020-04-19 22:29:58 +02:00
|
|
|
|
2021-01-04 14:15:12 +01:00
|
|
|
func SendBytes(port io.Writer, data []byte) error {
|
|
|
|
if bytesWritten, err := port.Write(data); err != nil {
|
2020-04-19 22:29:58 +02:00
|
|
|
return err
|
|
|
|
} else {
|
2021-01-04 14:15:12 +01:00
|
|
|
log.Tracef("wrote %d bytes", bytesWritten)
|
2020-04-19 22:29:58 +02:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|