-
Notifications
You must be signed in to change notification settings - Fork 1
/
videoswitcherdsp.go
119 lines (96 loc) · 2.37 KB
/
videoswitcherdsp.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
114
115
116
117
118
119
package kramer
import (
"context"
"fmt"
"net"
"time"
"github.com/byuoitav/connpool"
)
type KramerVP558 struct {
Address string
Log Logger
pool *connpool.Pool
}
// var (
// _defaultTTL = 30 * time.Second
// _defaultDelay = 500 * time.Millisecond
// )
type KramerVP558options struct {
ttl time.Duration
delay time.Duration
logger Logger
}
type KramerVP558Option interface {
apply(*KramerVP558options)
}
type KramerVP558optionFunc func(*KramerVP558options)
func (f KramerVP558optionFunc) apply(o *KramerVP558options) {
f(o)
}
func WithLoggerVSDSP(l Logger) KramerVP558Option {
return KramerVP558optionFunc(func(o *KramerVP558options) {
o.logger = l
})
}
func NewVideoSwitcherDsp(addr string, opts ...KramerVP558Option) *KramerVP558 {
options := KramerVP558options{
ttl: _defaultTTL,
delay: _defaultDelay,
}
for _, o := range opts {
o.apply(&options)
}
vsdsp := &KramerVP558{
Address: addr,
pool: &connpool.Pool{
TTL: options.ttl,
Delay: options.delay,
Logger: options.logger,
},
Log: options.logger,
}
vsdsp.pool.NewConnection = func(ctx context.Context) (net.Conn, error) {
d := net.Dialer{}
conn, err := d.DialContext(ctx, "tcp", vsdsp.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 vsdsp
}
// SendCommand sends the byte array to the desired address of projector
func (vsdsp *KramerVP558) SendCommand(ctx context.Context, cmd []byte, readAgain bool) ([]byte, error) {
var resp []byte
err := vsdsp.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)
}
if readAgain {
_, 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
}