From ac82c1fb52ed866ce482d45a92517a47dc4c9207 Mon Sep 17 00:00:00 2001 From: Damanox Date: Fri, 21 Dec 2018 18:41:18 +0200 Subject: [PATCH] feat: add timeout parameter --- sl500.go | 18 ++++++++++++------ sl500_test.go | 3 ++- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/sl500.go b/sl500.go index 0b6d095..32b7fd9 100644 --- a/sl500.go +++ b/sl500.go @@ -62,6 +62,7 @@ type Sl500 struct { port *serial.Port logging bool open bool + timeout time.Duration } type response struct { @@ -69,8 +70,12 @@ type response struct { err error } -func NewConnection(path string, baud baud, logging bool) (Sl500, error) { - c := &serial.Config{Name: path, Baud: baud.IntValue, ReadTimeout: 5 * time.Second} // TODO +func NewConnection(path string, baud baud, logging bool, timeout time.Duration) (Sl500, error) { + if timeout == 0 { + timeout = 3 * time.Second + } + + c := &serial.Config{Name: path, Baud: baud.IntValue, ReadTimeout: timeout} o, err := serial.OpenPort(c) res := Sl500{} @@ -83,6 +88,7 @@ func NewConnection(path string, baud baud, logging bool) (Sl500, error) { res.port = o res.logging = logging res.open = true + res.timeout = timeout return res, nil } @@ -325,8 +331,8 @@ func (s *Sl500) RfM1Transfer(blockNumber byte) ([]byte, error) { return readResponseWithTimeout(s) } -func timeout(r chan response){ - time.Sleep(3 * time.Second) +func timeout(timeout time.Duration, r chan response) { + time.Sleep(timeout) r <- response{err: errors.New("timeout")} } @@ -338,7 +344,7 @@ func readResponseWithTimeout(s *Sl500) ([]byte, error) { i, v := readResponse(s) inner <- response{data: i, err: v} }() - go timeout(inner) + go timeout(s.timeout, inner) v := <-inner @@ -419,7 +425,7 @@ func filterBuf(buf []byte) []byte { ind := 0 for i, b := range buf { - if i > 0 && buf[i - 1] == 0xAA && b == 0x00 { + if i > 0 && buf[i-1] == 0xAA && b == 0x00 { continue } diff --git a/sl500_test.go b/sl500_test.go index a75bc23..5b4abc9 100644 --- a/sl500_test.go +++ b/sl500_test.go @@ -5,10 +5,11 @@ import ( "sl500-api" "fmt" "reflect" + "time" ) func TestCanReadCard(t *testing.T) { - reader, err := sl500_api.NewConnection("COM3", sl500_api.Baud.Baud19200, true) + reader, err := sl500_api.NewConnection("COM3", sl500_api.Baud.Baud19200, true, 3 * time.Second) reader.RfAntennaSta(sl500_api.AntennaOn) if err != nil { t.Fatal(err)