Refactor client I/O into protocol package

This commit is contained in:
Jan Dittberner 2020-04-19 22:29:58 +02:00
parent 337e974a26
commit 9924771531
7 changed files with 339 additions and 200 deletions

View file

@ -1,31 +1,43 @@
package shared
import (
"errors"
"go.bug.st/serial"
"fmt"
log "github.com/sirupsen/logrus"
"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)
// 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 _, err := io.ReadAtLeast(*port, data, count); err != nil {
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 <- data
readCh <- make([]byte, 0)
}
return
}()
select {
case <-timeoutCh:
return nil, errors.New("timeout")
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
}

View file

@ -4,4 +4,4 @@ const MagicTrailer = "rie4Ech7"
const HandshakeByte = 0x02
const AckByte = 0x10
const NackByte = 0x11
const ResendByte = 0x11