/
event_ConnectionStatus.go
60 lines (52 loc) · 1.35 KB
/
event_ConnectionStatus.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
package bot
import (
ddp "github.com/gopackage/ddp"
"reflect"
)
type statusListener func(StatusType)
// OnStatus in order to receive status changes.
func (c *Client) OnStatus(listener statusListener) {
if c.events["OnStatus"] == nil {
c.ddpClient.AddStatusListener(c.ddpEventHandler)
}
c.events["OnStatus"] = append(c.events["OnStatus"], listener)
}
// Will be emited by ddpClient
func (e *ddpEventHandler) Status(status int) {
var st StatusType
switch status {
case ddp.DIALING:
st = CONNECTING
case ddp.CONNECTING:
st = CONNECTING
case ddp.CONNECTED:
st = CONNECTED
case ddp.DISCONNECTING:
st = DISCONNECTING
case ddp.DISCONNECTED:
st = DISCONNECTED
case ddp.RECONNECTING:
st = RECONNECTING
default:
st = DISCONNECTED
}
e.client.updateStatus(st)
}
// informs all status listeners with the new client status.
func (c *Client) updateStatus(status StatusType) {
if c.Status == status {
return
}
c.Status = status
for _, event := range c.events["OnStatus"] {
// call event(status)
f := reflect.TypeOf(event)
if f.Kind() == reflect.Func { //is function
if f.NumIn() == 1 && f.NumOut() == 0 { //inbound parameters == 1, outbound parameters == 0
if f.In(0).Kind() == reflect.String { //parameter 0 is of type string (StatusType)
go reflect.ValueOf(event).Call([]reflect.Value{reflect.ValueOf(status)})
}
}
}
}
}