This repository has been archived by the owner on Dec 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
ws_helper.go
268 lines (227 loc) · 6.01 KB
/
ws_helper.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
package www
import (
"encoding/json"
"net/http"
"strconv"
"sync"
"time"
"github.com/go-home-iot/event-bus"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
"github.com/markdaws/gohome/pkg/attr"
"github.com/markdaws/gohome/pkg/gohome"
"github.com/markdaws/gohome/pkg/log"
)
// Need check origin to allow cross-domain calls
var upgrader = websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }}
type WSHelper struct {
monitor *gohome.Monitor
evtBus *evtbus.Bus
nextID int64
connections map[string]map[*connection]bool
conn *websocket.Conn
mutex sync.RWMutex
updates chan *gohome.ChangeBatch
}
type connection struct {
monitorID string
connectionID string
ws *websocket.Conn
writeChan chan bool
readChan chan bool
}
func NewWSHelper(monitor *gohome.Monitor, evtBus *evtbus.Bus) *WSHelper {
h := WSHelper{
monitor: monitor,
evtBus: evtBus,
nextID: time.Now().UnixNano(),
connections: make(map[string]map[*connection]bool),
updates: make(chan *gohome.ChangeBatch, 1000),
}
h.processUpdates()
return &h
}
func (h *WSHelper) register(c *connection) {
log.V("WSHelper - registering connection, monitorID: " + c.monitorID)
h.mutex.Lock()
conns, ok := h.connections[c.monitorID]
if !ok {
conns = make(map[*connection]bool)
h.connections[c.monitorID] = conns
}
conns[c] = true
h.mutex.Unlock()
}
func (h *WSHelper) unregister(c *connection) {
h.mutex.Lock()
var conns map[*connection]bool
conns, ok := h.connections[c.monitorID]
if !ok {
h.mutex.Unlock()
return
}
if _, ok := conns[c]; !ok {
h.mutex.Unlock()
return
}
delete(conns, c)
if len(conns) == 0 {
delete(h.connections, c.monitorID)
}
h.mutex.Unlock()
log.V("WSHelper - unregister connection, monitorID: " + c.monitorID)
c.ws.Close()
close(c.writeChan)
close(c.readChan)
h.evtBus.Enqueue(&gohome.ClientDisconnectedEvt{ConnectionID: c.connectionID})
}
func (h *WSHelper) HTTPHandler() func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Check the monitorID, use has to first subscribe and get an ID
// before trying to stream the values
monitorID := mux.Vars(r)["monitorID"]
if _, ok := h.monitor.Group(monitorID); !ok {
c.Close()
return
}
conn := &connection{
connectionID: strconv.FormatInt(h.nextID, 10),
monitorID: monitorID,
ws: c,
writeChan: make(chan bool),
readChan: make(chan bool),
}
h.nextID++
h.register(conn)
go conn.writeLoop(h)
origin := ""
if orig, ok := r.Header["Origin"]; ok && len(orig) == 1 {
origin = orig[0]
}
// Let the system know a new client has connected
h.evtBus.Enqueue(&gohome.ClientConnectedEvt{
MonitorID: monitorID,
Origin: origin,
ConnectionID: conn.connectionID,
})
// When a connection registers, we need to ask the monitor to refresh all
// values associated with it. Since we could have subscribed but not connected
// yet and missed previous updates
h.monitor.Refresh(monitorID, false)
conn.readLoop(h)
}
}
func (h *WSHelper) processUpdates() {
go func() {
for update := range h.updates {
h.mutex.RLock()
conns, ok := h.connections[update.MonitorID]
if !ok || len(conns) == 0 {
h.mutex.RUnlock()
continue
}
connList := make([]*connection, 0, len(conns))
for conn := range conns {
connList = append(connList, conn)
}
h.mutex.RUnlock()
evt := jsonMonitorGroupResponse{
Features: make(map[string]map[string]*attr.Attribute),
}
for featureID, attrs := range update.Features {
evt.Features[featureID] = attrs
}
bytes, err := json.Marshal(evt)
if err != nil {
log.E("failed to marshal change batch to JSON for update: %s", err)
continue
}
// Serial, if we ever get a lot of conncurrent users, would want to push
// these in parallel
for _, conn := range connList {
conn.ws.SetWriteDeadline(time.Now().Add(10 * time.Second))
err = conn.ws.WriteMessage(websocket.TextMessage, bytes)
if err != nil {
h.unregister(conn)
}
}
}
}()
}
// ========= gohome.MonitorDelegate interface ==============
// Update is the callback to the monitor service, it will get change notifications
// when zones and sensors update
func (h *WSHelper) Update(b *gohome.ChangeBatch) {
h.updates <- b
}
func (h *WSHelper) Expired(monitorID string) {
// The monitor ID has expired, close any connections associated
// with this monitorID
go func() {
log.V("WSHelper - expired connection, monitorID: " + monitorID)
h.mutex.RLock()
conns, ok := h.connections[monitorID]
if !ok || len(conns) == 0 {
h.mutex.RUnlock()
return
}
connList := make([]*connection, 0, len(conns))
for conn := range conns {
connList = append(connList, conn)
}
h.mutex.RUnlock()
for _, conn := range connList {
h.unregister(conn)
}
}()
}
// =========================================================
func (c *connection) writeLoop(l *WSHelper) {
ticker := time.NewTicker(50 * time.Second)
defer func() {
ticker.Stop()
}()
var exit = false
for {
select {
case _, ok := <-c.writeChan:
if !ok {
exit = true
}
case <-ticker.C:
// Making sure the client is still alive
c.ws.SetWriteDeadline(time.Now().Add(10 * time.Second))
if err := c.ws.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
l.unregister(c)
exit = true
}
}
if exit {
break
}
}
}
func (c *connection) readLoop(l *WSHelper) {
// have to have a read loop otherwise ping/pong don't work
defer func() {
l.unregister(c)
}()
c.ws.SetReadLimit(1024)
maxWait := 60 * time.Second
c.ws.SetReadDeadline(time.Now().Add(maxWait))
c.ws.SetPongHandler(func(string) error {
c.ws.SetReadDeadline(time.Now().Add(maxWait))
return nil
})
for {
// If the client closes we get a 1001 error here
if _, _, err := c.ws.ReadMessage(); err != nil {
break
}
}
}