-
Notifications
You must be signed in to change notification settings - Fork 1
/
videoswitcher.go
108 lines (86 loc) · 2.09 KB
/
videoswitcher.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
package kramer
import (
"context"
"fmt"
"net"
"time"
"github.com/byuoitav/connpool"
)
type VideoSwitcher struct {
Address string
Log Logger
pool *connpool.Pool
}
var (
_defaultTTL = 30 * time.Second
_defaultDelay = 500 * time.Millisecond
)
type options struct {
ttl time.Duration
delay time.Duration
logger Logger
}
type Option interface {
apply(*options)
}
type optionFunc func(*options)
func NewVideoSwitcher(addr string, opts ...Option) *VideoSwitcher {
options := options{
ttl: _defaultTTL,
delay: _defaultDelay,
}
for _, o := range opts {
o.apply(&options)
}
vs := &VideoSwitcher{
Address: addr,
pool: &connpool.Pool{
TTL: options.ttl,
Delay: options.delay,
Logger: options.logger,
},
}
vs.pool.NewConnection = func(ctx context.Context) (net.Conn, error) {
d := net.Dialer{}
conn, err := d.DialContext(ctx, "tcp", vs.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 vs
}
// SendCommand sends the byte array to the desired address of projector
func (vs *VideoSwitcher) SendCommand(ctx context.Context, cmd []byte) ([]byte, error) {
var resp []byte
// command = strings.Replace(command, " ", string(SPACE), -1)
// color.Set(color.FgMagenta)
// log.L.Infof("Sending command %s", command)
// color.Unset()
// command += string(CARRIAGE_RETURN) + string(LINE_FEED)
// conn.Write([]byte(command))
err := vs.pool.Do(ctx, func(conn connpool.Conn) error {
_ = conn.SetWriteDeadline(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, 3*time.Second)
if err != nil {
return fmt.Errorf("unable to read response: %w", err)
}
return nil
})
if err != nil {
return nil, err
}
return resp, nil
}