Refactor signer code into command and package

This commit is contained in:
Jan Dittberner 2021-01-04 14:15:12 +01:00
parent 3a2578ae55
commit 38566f35ef
13 changed files with 476 additions and 276 deletions

View file

@ -2,30 +2,37 @@ package shared
import (
"fmt"
log "github.com/sirupsen/logrus"
"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.ReadWriteCloser, count int, timeout time.Duration) ([]byte, error) {
func ReceiveBytes(port io.Reader, 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)
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
}
}
return
}()
select {
case <-time.After(timeout):
return nil, fmt.Errorf("timeout passed %v: %v", timeout)
return nil, fmt.Errorf("timeout passed %v", timeout)
case err := <-errCh:
return nil, err
case data := <-readCh:
@ -33,11 +40,11 @@ func ReceiveBytes(port *io.ReadWriteCloser, count int, timeout time.Duration) ([
}
}
func SendByte(port *io.ReadWriteCloser, data byte) error {
if bytesWritten, err := (*port).Write([]byte{data}); err != 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 of handshake info", bytesWritten)
log.Tracef("wrote %d bytes", bytesWritten)
}
return nil
}

View file

@ -1,7 +1,36 @@
package shared
const MagicTrailer = "rie4Ech7"
const (
ProtocolVersion = 1
const HandshakeByte = 0x02
const AckByte = 0x10
const ResendByte = 0x11
HandshakeByte = 0x02
AckByte = 0x10
ResendByte = 0x11
MagicTrailer = "rie4Ech7"
LengthFieldSize = 3
CheckSumFieldSize = 1
TrailerFieldSize = len(MagicTrailer)
)
type Action uint8
const (
ActionNul = Action(0)
ActionSign = Action(1)
ActionRevoke = Action(2)
)
func (a Action) String() string {
switch a {
case ActionNul:
return "NUL"
case ActionSign:
return "SIGN"
case ActionRevoke:
return "REVOKE"
default:
return "unknown"
}
}