feat: add timeout parameter

master
Damanox 7 years ago
parent 2dd276b7b2
commit ac82c1fb52
  1. 18
      sl500.go
  2. 3
      sl500_test.go

@ -62,6 +62,7 @@ type Sl500 struct {
port *serial.Port port *serial.Port
logging bool logging bool
open bool open bool
timeout time.Duration
} }
type response struct { type response struct {
@ -69,8 +70,12 @@ type response struct {
err error err error
} }
func NewConnection(path string, baud baud, logging bool) (Sl500, error) { func NewConnection(path string, baud baud, logging bool, timeout time.Duration) (Sl500, error) {
c := &serial.Config{Name: path, Baud: baud.IntValue, ReadTimeout: 5 * time.Second} // TODO if timeout == 0 {
timeout = 3 * time.Second
}
c := &serial.Config{Name: path, Baud: baud.IntValue, ReadTimeout: timeout}
o, err := serial.OpenPort(c) o, err := serial.OpenPort(c)
res := Sl500{} res := Sl500{}
@ -83,6 +88,7 @@ func NewConnection(path string, baud baud, logging bool) (Sl500, error) {
res.port = o res.port = o
res.logging = logging res.logging = logging
res.open = true res.open = true
res.timeout = timeout
return res, nil return res, nil
} }
@ -325,8 +331,8 @@ func (s *Sl500) RfM1Transfer(blockNumber byte) ([]byte, error) {
return readResponseWithTimeout(s) return readResponseWithTimeout(s)
} }
func timeout(r chan response){ func timeout(timeout time.Duration, r chan response) {
time.Sleep(3 * time.Second) time.Sleep(timeout)
r <- response{err: errors.New("timeout")} r <- response{err: errors.New("timeout")}
} }
@ -338,7 +344,7 @@ func readResponseWithTimeout(s *Sl500) ([]byte, error) {
i, v := readResponse(s) i, v := readResponse(s)
inner <- response{data: i, err: v} inner <- response{data: i, err: v}
}() }()
go timeout(inner) go timeout(s.timeout, inner)
v := <-inner v := <-inner
@ -419,7 +425,7 @@ func filterBuf(buf []byte) []byte {
ind := 0 ind := 0
for i, b := range buf { for i, b := range buf {
if i > 0 && buf[i - 1] == 0xAA && b == 0x00 { if i > 0 && buf[i-1] == 0xAA && b == 0x00 {
continue continue
} }

@ -5,10 +5,11 @@ import (
"sl500-api" "sl500-api"
"fmt" "fmt"
"reflect" "reflect"
"time"
) )
func TestCanReadCard(t *testing.T) { 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) reader.RfAntennaSta(sl500_api.AntennaOn)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)

Loading…
Cancel
Save