...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package serial
18
19 import (
20 "errors"
21 "io"
22 )
23
24 import "testing"
25 import "time"
26
27 const (
28 DEVICE = "/dev/tty.usbserial-A8008HlV"
29 )
30
31
32
33
34
35
36
37 func readWithTimeout(r io.Reader, n int) ([]byte, error) {
38 buf := make([]byte, n)
39 done := make(chan error)
40 readAndCallBack := func() {
41 _, err := io.ReadAtLeast(r, buf, n)
42 done <- err
43 }
44
45 go readAndCallBack()
46
47 timeout := make(chan bool)
48 sleepAndCallBack := func() { time.Sleep(2e9); timeout <- true }
49 go sleepAndCallBack()
50
51 select {
52 case err := <-done:
53 return buf, err
54 case <-timeout:
55 return nil, errors.New("Timed out.")
56 }
57
58 return nil, errors.New("Can't get here.")
59 }
60
61
62
63
64
65
66
67 func TestIncrementAndEcho(t *testing.T) {
68
69 var options OpenOptions
70 options.PortName = DEVICE
71 options.BaudRate = 19200
72 options.DataBits = 8
73 options.StopBits = 1
74 options.MinimumReadSize = 4
75
76 circuit, err := Open(options)
77 if err != nil {
78 t.Fatal(err)
79 }
80
81 defer circuit.Close()
82
83
84 time.Sleep(3e9)
85
86
87 b := []byte{0x00, 0x17, 0xFE, 0xFF}
88
89 n, err := circuit.Write(b)
90 if err != nil {
91 t.Fatal(err)
92 }
93
94 if n != 4 {
95 t.Fatal("Expected 4 bytes written, got ", n)
96 }
97
98
99 b, err = readWithTimeout(circuit, 4)
100 if err != nil {
101 t.Fatal(err)
102 }
103
104 if b[0] != 0x01 {
105 t.Error("Expected 0x01, got ", b[0])
106 }
107 if b[1] != 0x18 {
108 t.Error("Expected 0x18, got ", b[1])
109 }
110 if b[2] != 0xFF {
111 t.Error("Expected 0xFF, got ", b[2])
112 }
113 if b[3] != 0x00 {
114 t.Error("Expected 0x00, got ", b[3])
115 }
116 }
117
View as plain text