-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtransport.go
320 lines (274 loc) · 6.1 KB
/
transport.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
package onkyoctl
import (
"bufio"
"errors"
"fmt"
"io"
"net"
"sync"
"time"
)
// ConnectionState is the type used to describe the connection status for the client.
type ConnectionState int
const (
Disconnected ConnectionState = iota
Connecting
Connected
Disconnecting
)
var (
ErrNotConnected = errors.New("not connected")
ErrTimeout = errors.New("timeout")
)
// MessageHandler is a callback function to handle incoming messages.
type MessageHandler func(ISCPCommand)
type sendTask struct {
Command ISCPCommand
Reply chan error
}
type client struct {
host string
port int
timeout time.Duration
state ConnectionState
conn net.Conn
connLock sync.Mutex
done chan bool
wantConnect chan bool
wantDisconnect chan bool
received chan ISCPCommand
send chan sendTask
handler MessageHandler
connectionCB func(ConnectionState)
log Logger
}
func newClient(host string, port int, log Logger) *client {
return &client{
host: host,
port: port,
timeout: 3 * time.Second,
state: Disconnected,
done: make(chan bool),
wantConnect: make(chan bool),
wantDisconnect: make(chan bool),
received: make(chan ISCPCommand, 32),
send: make(chan sendTask, 32),
log: log,
}
}
// public interface -----------------------------------------------------------
func (c *client) Start() {
// if started, ignore
go c.loop()
}
func (c *client) Stop() {
// if stopped, ignore
c.done <- true
}
func (c *client) Connect() {
c.wantConnect <- true
}
func (c *client) Disconnect() {
c.wantDisconnect <- true
}
func (c *client) WaitConnect(timeout time.Duration) bool {
if c.isState(Connected) {
return true
}
t := time.After(timeout)
ticker := time.NewTimer(50 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-t:
return c.isState(Connected)
case <-ticker.C:
if c.isState(Connected) {
return true
}
}
}
}
func (c *client) State() ConnectionState {
c.connLock.Lock()
defer c.connLock.Unlock()
return c.state
}
func (c *client) Send(cmd ISCPCommand, timeout time.Duration) error {
if c.isState(Disconnected, Disconnecting) {
return ErrNotConnected
}
reply := make(chan error, 1)
c.send <- sendTask{Command: cmd, Reply: reply}
if timeout <= 0 {
return nil
}
select {
case err := <-reply:
return err
case <-time.After(timeout):
return ErrTimeout
}
}
func (c *client) loop() {
for {
select {
case <-c.done:
c.doDone()
return
case <-c.wantDisconnect:
c.doDisconnect()
case <-c.wantConnect:
c.doConnect()
case cmd := <-c.received:
c.doReceive(cmd)
case task := <-c.send:
c.doSend(task)
}
}
}
func (c *client) doDone() {
c.log.Debug("Done")
c.doDisconnect()
}
// Connection handling --------------------------------------------------------
func (c *client) isState(states ...ConnectionState) bool {
c.connLock.Lock()
defer c.connLock.Unlock()
for _, s := range states {
if s == c.state {
return true
}
}
return false
}
func (c *client) changeState(s ConnectionState, conn net.Conn) {
c.connLock.Lock()
defer c.connLock.Unlock()
c.state = s
if conn != nil {
c.conn = conn
}
if c.connectionCB != nil {
go func() {
c.connectionCB(s)
}()
}
}
func (c *client) doConnect() {
if c.isState(Connected, Connecting) {
return
}
c.log.Debug("Connect")
c.changeState(Connecting, nil)
conn, err := c.createConn()
if err != nil {
c.changeState(Disconnected, nil)
return
}
c.changeState(Connected, conn)
go c.readLoop(c.conn) // TODO: not thread safe
}
func (c *client) createConn() (net.Conn, error) {
addr := fmt.Sprintf("%v:%v", c.host, c.port)
return net.DialTimeout(protocol, addr, c.timeout)
}
func (c *client) doDisconnect() {
if c.isState(Disconnected, Disconnecting) {
return
}
c.log.Debug("Disconnect")
c.changeState(Disconnecting, c.conn)
// wait for outgoing messages?
err := c.conn.Close() // TODO: not thread safe
if err != nil {
c.log.Warning("Error closing connection: %v", err)
}
c.changeState(Disconnected, nil)
}
func (c *client) readLoop(conn net.Conn) {
defer func() {
if c.isState(Connected) {
// unexpected close of connection, assume server side close
// and attempt reconnect
c.changeState(Disconnected, nil)
}
}()
r := bufio.NewReader(conn)
buf := make([]byte, headerSize) // reused
for {
// read header
_, err := r.Read(buf)
if err != nil {
if err == io.EOF {
// assume server side close
return
}
c.log.Warning("Read error: %v", err)
// return
continue
}
c.log.Debug("<- recv (H): %v", buf)
_, payloadSize, err := ParseHeader(buf)
if err != nil {
c.log.Warning("Discard bad message: %v", err)
continue
}
// read payload
payload := make([]byte, payloadSize)
_, err = r.Read(payload)
if err != nil {
if err == io.EOF {
// assume server side close
return
}
c.log.Warning("Read error: %v", err)
//return
continue
}
c.log.Debug("<- recv (P): %v", payload)
iscp, err := ParseISCP(payload)
if err != nil {
c.log.Warning("Discard invalid message: %v", err)
continue
}
c.received <- iscp.Command()
}
}
// send + receive -------------------------------------------------------------
func (c *client) doSend(t sendTask) {
if !c.isState(Connected) {
c.log.Warning("Discard message (not connected): %v", t.Command)
t.Reply <- ErrNotConnected
return
}
conn := c.conn // TODO: not thread safe
msg := NewEISCPMessage(t.Command)
c.log.Debug("-> send: %v", t.Command)
_, err := conn.Write(msg.Raw())
if err != nil {
c.log.Error("Error writing to connection: %v", err)
}
t.Reply <- err
}
func (c *client) doReceive(cmd ISCPCommand) {
c.log.Debug("<- handle: %v", cmd)
if c.handler != nil {
c.handler(cmd)
}
}
// pretty print for connection state
func (cs ConnectionState) String() string {
switch cs {
case Connected:
return "CONNECTED"
case Connecting:
return "CONNECTING"
case Disconnected:
return "DISCONNECTED"
case Disconnecting:
return "DISCONNECTING"
default:
return fmt.Sprintf("UNKNOWN (%v)", int(cs))
}
}