-
Notifications
You must be signed in to change notification settings - Fork 4
/
websocket.go
170 lines (149 loc) · 4.2 KB
/
websocket.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
package server
import (
"net/http"
"strconv"
"strings"
"time"
"github.com/gobwas/ws"
"github.com/gobwas/ws/wsutil"
log "github.com/sirupsen/logrus"
)
func startWSServer(host string, port int, ctrl *ScannerCtrl) (*http.Server, error) {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
conn, _, _, err := ws.UpgradeHTTP(r, w)
if err != nil {
// handle error
log.Errorln("Error during WS upgrade", err)
}
ctrl.mode.WSClientConnected = true
defer func() {
conn.Close()
if ctrl.locker.name == r.RemoteAddr {
ctrl.locker.state = false
log.Infoln("Unlocking Scanner for new WS Client Connection")
}
}()
if ctrl.locker.state {
log.Infoln("Scanner is already is use by", ctrl.locker.name)
if writeErr := wsutil.WriteServerMessage(conn, ws.OpBinary, []byte("Locked by "+ctrl.locker.name)); writeErr != nil {
// handle error
log.Errorln("Failed to Write", writeErr)
return
}
return
} else {
log.Infof("Locking Scanner for new WS Client Connection: [%s]", r.RemoteAddr)
ctrl.locker.Lock()
ctrl.locker.state = true
ctrl.locker.name = r.RemoteAddr
ctrl.locker.pktSent = 0
ctrl.locker.pktRecv = 0
ctrl.locker.Unlock()
}
quitReader := make(chan bool, 1)
quitWriter := make(chan bool, 1)
done := make(chan bool, 1)
// WS Reader routine
go func() {
for {
select {
case <-quitWriter:
return
default:
time.Sleep(time.Millisecond * 50)
}
msgFromHost, _, readErr := wsutil.ReadClientData(conn)
if readErr != nil {
// handle error
log.Errorln("Failed to read from WS, Terminating Client Connection", readErr)
done <- true
quitReader <- true
return
}
if !validMsgFromWSClient(msgFromHost) {
log.Warnln("Message From WS Failed Validation", crlfStrip(msgFromHost, LF))
return
}
strMsg := string(crlfStrip(msgFromHost, LF))
if strMsg == TERMINATE {
log.Infoln("Received Client QUIT Command: Terminating Client Connection")
done <- true
quitReader <- true
return
}
if strMsg == "" || strMsg == "\n" {
continue
}
if strings.HasPrefix(strMsg, "HP,") {
log.Infof("HomePatrol message From Host: [%s]", crlfStrip(msgFromHost, LF))
hpCmd := homepatrolCommand(strings.Split(strMsg[3:], "|"))
log.Infof("Sending HomePatrol message %#q\n", hpCmd)
success := ctrl.SendToHostMsgChannel([]byte(hpCmd))
log.Infoln("Sent message?", success)
continue
}
// log.Infof("Message From Host: [%s]", crlfStrip(msgFromHost, LF))
ctrl.SendToHostMsgChannel(msgFromHost)
}
}()
// WS Writer routine
go func() {
for {
select {
case <-quitReader:
return
default:
time.Sleep(time.Millisecond * 50)
}
msgToHost, ok := ctrl.ReceiveFromRadioMsgChannel()
if ok {
elapsed := time.Since(msgToHost.ts)
log.Infof("Received[ql=%d] Message To Host at [%s] [%s]",
len(ctrl.radioMsg), elapsed, crlfStrip(msgToHost.msg, LF|NL))
if writeErr := wsutil.WriteServerMessage(conn, ws.OpBinary, msgToHost.msg); writeErr != nil {
// handle error
log.Errorln("Failed to Write", writeErr)
done <- true
quitWriter <- true
return
} else {
log.Infof("Message To Host: [%s]", string(msgToHost.msg))
}
}
}
}()
<-done
// TODO - need to reset radio into normal state: Turn off PSI
ctrl.SendToHostMsgChannel([]byte("PSI,0\r"))
// drain any UDP Traffic
ctrl.drain()
// Drain WS Messages so new connection won't receive old messages
for {
_, ok := ctrl.ReceiveFromRadioMsgChannel()
if !ok {
break
} else {
log.Infoln("RadioMsgChannel Draining...")
}
}
ctrl.mode.WSClientConnected = false
})
s := &http.Server{
Addr: host + ":" + strconv.Itoa(port),
Handler: handler,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
go func() {
if listenErr := s.ListenAndServe(); listenErr != nil {
log.Fatalln("Error when listening for WebSocket Server", listenErr)
}
}()
log.Infoln("Started WebSocket Server at", s.Addr)
return s, nil
}
// TODO -- add msg validation
func validMsgFromWSClient(msgFromHost []byte) bool {
return true
}