-
Notifications
You must be signed in to change notification settings - Fork 1
/
dsp.go
113 lines (91 loc) · 2.27 KB
/
dsp.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package kramer
import (
"context"
"fmt"
"net"
"time"
"github.com/byuoitav/connpool"
)
type KramerAFM20DSP struct {
Address string
Log Logger
pool *connpool.Pool
}
// var (
// _defaultTTL = 30 * time.Second
// _defaultDelay = 500 * time.Millisecond
// )
type KramerAFM20DSPoptions struct {
ttl time.Duration
delay time.Duration
logger Logger
}
// TODO add specific options for each model
type KramerAFM20DSPOption interface {
apply(*KramerAFM20DSPoptions)
}
type KramerAFM20DSPoptionFunc func(*KramerAFM20DSPoptions)
func (f KramerAFM20DSPoptionFunc) apply(o *KramerAFM20DSPoptions) {
f(o)
}
func WithLoggerDSP(l Logger) KramerAFM20DSPOption {
return KramerAFM20DSPoptionFunc(func(o *KramerAFM20DSPoptions) {
o.logger = l
})
}
func NewDsp(addr string, opts ...KramerAFM20DSPOption) *KramerAFM20DSP {
options := KramerAFM20DSPoptions{
ttl: _defaultTTL,
delay: _defaultDelay,
}
for _, o := range opts {
o.apply(&options)
}
dsp := &KramerAFM20DSP{
Address: addr,
pool: &connpool.Pool{
TTL: options.ttl,
Delay: options.delay,
Logger: options.logger,
},
Log: options.logger,
}
dsp.pool.NewConnection = func(ctx context.Context) (net.Conn, error) {
d := net.Dialer{}
conn, err := d.DialContext(ctx, "tcp", dsp.Address+":5000")
if err != nil {
return nil, fmt.Errorf("unable to open connection: %w", err)
}
select {
case <-ctx.Done():
return nil, fmt.Errorf("context done before welcome message is sent: %w", ctx.Err())
case <-time.After(500 * time.Millisecond):
}
return conn, nil
}
return dsp
}
// SendCommand sends the byte array to the desired address of projector
func (dsp *KramerAFM20DSP) SendCommand(ctx context.Context, cmd []byte) ([]byte, error) {
var resp []byte
err := dsp.pool.Do(ctx, func(conn connpool.Conn) error {
_ = conn.SetWriteDeadline(time.Now().Add(5 * time.Second))
readDur := time.Now().Add(3 * time.Second)
n, err := conn.Write(cmd)
switch {
case err != nil:
return err
case n != len(cmd):
return fmt.Errorf("wrote %v/%v bytes of command 0x%x", n, len(cmd), cmd)
}
resp, err = conn.ReadUntil(LINE_FEED, readDur)
if err != nil {
return fmt.Errorf("unable to read response: %w", err)
}
return nil
})
if err != nil {
return nil, err
}
return resp, nil
}