forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
socket.go
205 lines (177 loc) Β· 4.23 KB
/
socket.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
package server
import (
"encoding/json"
"fmt"
"math"
"net/http"
"strings"
"sync"
"time"
"github.com/evcc-io/evcc/util"
"github.com/gorilla/websocket"
"github.com/kr/pretty"
)
const (
// Time allowed to write a message to the peer
socketWriteTimeout = 10 * time.Second
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { return true },
}
// SocketClient is a middleman between the websocket connection and the hub.
type SocketClient struct {
hub *SocketHub
// The websocket connection.
conn *websocket.Conn
// Buffered channel of outbound messages.
send chan []byte
}
// writePump pumps messages from the hub to the websocket connection.
func (c *SocketClient) writePump() {
defer func() {
c.conn.Close()
c.hub.unregister <- c
}()
for msg := range c.send {
if err := c.conn.SetWriteDeadline(time.Now().Add(socketWriteTimeout)); err != nil {
return
}
if err := c.conn.WriteMessage(websocket.TextMessage, msg); err != nil {
return
}
}
}
// ServeWebsocket handles websocket requests from the peer.
func ServeWebsocket(hub *SocketHub, w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.ERROR.Println(err)
return
}
client := &SocketClient{hub: hub, conn: conn, send: make(chan []byte, 256)}
client.hub.register <- client
// run writing to client in goroutine
go client.writePump()
}
// SocketHub maintains the set of active clients and broadcasts messages to the
// clients.
type SocketHub struct {
mu sync.RWMutex
// Registered clients.
clients map[*SocketClient]bool
// Register requests from the clients.
register chan *SocketClient
// Unregister requests from clients.
unregister chan *SocketClient
}
// NewSocketHub creates a web socket hub that distributes meter status and
// query results for the ui or other clients
func NewSocketHub() *SocketHub {
return &SocketHub{
register: make(chan *SocketClient),
unregister: make(chan *SocketClient),
clients: make(map[*SocketClient]bool),
}
}
func encode(v interface{}) (string, error) {
var s string
switch val := v.(type) {
case time.Time:
if val.IsZero() {
s = "null"
} else {
s = fmt.Sprintf(`"%s"`, val.Format(time.RFC3339))
}
case time.Duration:
// must be before stringer to convert to seconds instead of string
s = fmt.Sprintf("%d", int64(val.Seconds()))
case float64:
if math.IsNaN(val) {
s = "null"
} else {
s = fmt.Sprintf("%.5g", val)
}
default:
if b, err := json.Marshal(v); err == nil {
s = string(b)
} else {
return "", err
}
}
return s, nil
}
func kv(p util.Param) string {
val, err := encode(p.Val)
if err != nil {
panic(err)
}
if p.Key == "" && val == "" {
log.ERROR.Printf("invalid key/val for %+v %# v, please report to https://github.com/evcc-io/evcc/issues/6439", p, pretty.Formatter(p.Val))
return "\"foo\":\"bar\""
}
var msg strings.Builder
msg.WriteString("\"")
if p.Loadpoint != nil {
msg.WriteString(fmt.Sprintf("loadpoints.%d.", *p.Loadpoint))
}
msg.WriteString(p.Key)
msg.WriteString("\":")
msg.WriteString(val)
return msg.String()
}
func (h *SocketHub) welcome(client *SocketClient, params []util.Param) {
h.mu.Lock()
h.clients[client] = true
h.mu.Unlock()
var msg strings.Builder
msg.WriteString("{")
for _, p := range params {
if msg.Len() > 1 {
msg.WriteString(",")
}
msg.WriteString(kv(p))
}
msg.WriteString("}")
select {
case client.send <- []byte(msg.String()):
default:
close(client.send)
}
}
func (h *SocketHub) broadcast(p util.Param) {
h.mu.RLock()
defer h.mu.RUnlock()
if len(h.clients) > 0 {
msg := "{" + kv(p) + "}"
for client := range h.clients {
select {
case client.send <- []byte(msg):
default:
h.unregister <- client
}
}
}
}
// Run starts data and status distribution
func (h *SocketHub) Run(in <-chan util.Param, cache *util.Cache) {
for {
select {
case client := <-h.register:
h.welcome(client, cache.All())
case client := <-h.unregister:
h.mu.Lock()
if _, ok := h.clients[client]; ok {
close(client.send)
delete(h.clients, client)
}
h.mu.Unlock()
case msg, ok := <-in:
if !ok {
return // break if channel closed
}
h.broadcast(msg)
}
}
}