-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsfconnection.go
285 lines (238 loc) · 5.84 KB
/
sfconnection.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
// Author Raido Pahtma
// License MIT
// SerialForwarder connection library.
package sfconnection
import "net"
import "fmt"
import "strconv"
import "bufio"
import "io"
import "time"
import "errors"
import "sync"
import "sync/atomic"
import "github.com/proactivity-lab/go-loggers"
type Packet interface {
Dispatch() byte
Serialize() ([]byte, error)
Deserialize([]byte) error
SetPayload([]byte) error
GetPayload() []byte
}
type PacketFactory interface {
Dispatch() byte
NewPacket() Packet
}
type Dispatcher interface {
Dispatch() byte
Receive([]byte) error
NewPacket() Packet
}
type SfConnection struct {
loggers.DIWEloggers
Host string
Port uint16
connectlock sync.Mutex
shouldconnect bool
autoconnect bool
period time.Duration
connected atomic.Value
outgoing chan []byte
incoming chan []byte
dispatchers map[byte]Dispatcher
conn net.Conn
connbuf *bufio.Reader
watchdog chan bool
closed chan bool
}
func (self *SfConnection) runErrorHandler(err error) error {
if err != io.EOF && err != io.ErrUnexpectedEOF {
self.Debug.Printf("%s\n", err)
}
return err
}
func (self *SfConnection) connectErrorHandler(conn net.Conn, err error) error {
if conn != nil {
conn.Close()
}
if self.autoconnect {
go self.connect(self.period)
}
return self.runErrorHandler(err)
}
func (self *SfConnection) Connected() bool {
return self.connected.Load().(bool)
}
func (self *SfConnection) Disconnect() {
self.notifyWatchdog(false)
self.connectlock.Lock()
defer self.connectlock.Unlock()
self.shouldconnect = false
self.autoconnect = false
if self.connected.Load().(bool) {
self.conn.Close()
}
}
func (self *SfConnection) Connect(host string, port uint16) error {
self.connectlock.Lock()
self.Host = host
self.Port = port
self.shouldconnect = true
self.autoconnect = false
self.connectlock.Unlock()
return self.connect(0)
}
func (self *SfConnection) Autoconnect(host string, port uint16, period time.Duration) {
self.connectlock.Lock()
defer self.connectlock.Unlock()
self.Host = host
self.Port = port
self.shouldconnect = true
self.autoconnect = true
self.period = period
go self.connect(0)
}
func (self *SfConnection) notifyWatchdog(outcome bool) {
select {
case self.watchdog <- outcome:
case <-time.After(time.Second):
self.Debug.Printf("No watchdog?\n")
}
}
func (self *SfConnection) connectWatchdog(timeout time.Duration, conn net.Conn) {
select {
case v := <-self.watchdog:
if v {
self.Debug.Printf("Watchdog stop.\n")
return
} else {
self.Debug.Printf("Watchdog interrupt.\n")
conn.Close()
}
case <-time.After(timeout):
self.Debug.Printf("Timeout.\n")
conn.Close()
}
}
func (self *SfConnection) connect(delay time.Duration) error {
time.Sleep(delay)
self.connectlock.Lock()
defer self.connectlock.Unlock()
if self.connected.Load().(bool) {
return errors.New("Already connected.")
}
if self.shouldconnect == false {
return errors.New("Connect interrupted.")
}
constring := self.Host + ":" + strconv.Itoa(int(self.Port))
self.Info.Printf("Connecting to %s\n", constring)
conn, err := net.Dial("tcp", constring)
if err != nil {
return self.connectErrorHandler(conn, err)
}
go self.connectWatchdog(30*time.Second, conn)
_, err = conn.Write([]byte("U "))
if err != nil {
return self.connectErrorHandler(conn, err)
}
connbuf := bufio.NewReader(conn)
protocol := make([]byte, 2)
_, err = io.ReadFull(connbuf, protocol)
if err == nil {
if string(protocol) == "U " {
self.notifyWatchdog(true)
self.connected.Store(true)
self.conn = conn
self.connbuf = connbuf
self.Info.Printf("Connection established.\n")
go self.read()
go self.run()
return nil
} else {
return self.connectErrorHandler(conn, errors.New(fmt.Sprintf("Unsupported protocol %s!", string(protocol))))
}
} else {
return self.connectErrorHandler(conn, err)
}
}
func (self *SfConnection) read() {
for {
len, err := self.connbuf.ReadByte()
if err == nil {
msg := make([]byte, len)
_, err := io.ReadFull(self.connbuf, msg)
if err == nil {
self.incoming <- msg
} else {
self.runErrorHandler(err)
self.closed <- true
break
}
} else {
self.runErrorHandler(err)
self.closed <- true
break
}
}
}
func (self *SfConnection) run() {
for {
select {
case msg := <-self.incoming:
self.Debug.Printf("RCV(%d): %X\n", len(msg), msg)
if len(msg) > 0 {
if dispatcher, ok := self.dispatchers[msg[0]]; ok {
err := dispatcher.Receive(msg)
if err != nil {
self.Debug.Printf("Dispatcher error: %s", err)
}
} else {
self.Debug.Printf("No dispatcher for %02X!\n", msg[0])
}
}
case msg := <-self.outgoing:
length := make([]byte, 1)
length[0] = byte(len(msg))
self.Debug.Printf("SND(%d): %X\n", length[0], msg)
self.conn.Write(length)
self.conn.Write(msg)
case <-self.closed:
self.Debug.Printf("Connection closed.\n")
self.connectlock.Lock()
defer self.connectlock.Unlock()
self.connected.Store(false)
self.conn.Close()
if self.autoconnect {
go self.connect(self.period)
}
return
}
}
}
func (self *SfConnection) Send(msg Packet) error {
serialized, err := msg.Serialize()
if err != nil {
return err
}
select {
case self.outgoing <- serialized:
return nil
case <-time.After(50 * time.Millisecond): // Because the run goroutine might be doing something other than reading self.outgoing at this very moment
return errors.New("Not connected!")
}
}
func (self *SfConnection) AddDispatcher(dispatcher Dispatcher) error {
self.dispatchers[dispatcher.Dispatch()] = dispatcher
return nil
}
func NewSfConnection() *SfConnection {
sfc := new(SfConnection)
sfc.InitLoggers()
sfc.dispatchers = make(map[byte]Dispatcher)
sfc.outgoing = make(chan []byte)
sfc.incoming = make(chan []byte)
sfc.watchdog = make(chan bool)
sfc.closed = make(chan bool)
sfc.connected.Store(false)
return sfc
}