-
Notifications
You must be signed in to change notification settings - Fork 9
/
stream.go
358 lines (324 loc) · 9.25 KB
/
stream.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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
package tibber
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"time"
"github.com/gorilla/websocket"
log "github.com/sirupsen/logrus"
)
const subscriptionEndpoint = "v1-beta/gql/subscriptions"
const tibberHost = "api.tibber.com"
const (
StreamStateConnected = "CONNECTED"
StreamStateConnecting = "CONNECTING"
StreamStateDisconnected = "DISCONNECTED"
)
// MsgChan for reciving messages
type MsgChan chan *StreamMsg
// StreamMsg for streams
type StreamMsg struct {
HomeID string `json:"homeId"`
Type string `json:"type"`
ID int `json:"id"`
Payload Payload `json:"payload"`
}
type StreamState struct {
State string
Err error
}
// Payload in StreamMsg
type Payload struct {
Data Data `json:"data"`
}
// Data in Payload
type Data struct {
LiveMeasurement LiveMeasurement `json:"liveMeasurement"`
}
// LiveMeasurement in data payload
type LiveMeasurement struct {
Timestamp time.Time `json:"timestamp"`
Power float64 `json:"power"`
LastMeterConsumption float64 `json:"lastMeterConsumption"`
LastMeterProduction float64 `json:"lastMeterProduction"`
AccumulatedConsumption float64 `json:"accumulatedConsumption"`
AccumulatedCost float64 `json:"accumulatedCost"`
AccumulatedProduction float64 `json:"accumulatedProduction"`
AccumulatedReward float64 `json:"accumulatedReward"`
MinPower float64 `json:"minPower"`
AveragePower float64 `json:"averagePower"`
MaxPower float64 `json:"maxPower"`
PowerProduction float64 `json:"powerProduction"`
MinPowerProduction float64 `json:"minPowerProduction"`
MaxPowerProduction float64 `json:"maxPowerProduction"`
VoltagePhase1 float64 `json:"voltagePhase1"`
VoltagePhase2 float64 `json:"voltagePhase2"`
VoltagePhase3 float64 `json:"voltagePhase3"`
CurrentPhase1 float64 `json:"currentPhase1"`
CurrentPhase2 float64 `json:"currentPhase2"`
CurrentPhase3 float64 `json:"currentPhase3"`
}
// IsExtended returns whether the report is normal or extended.
// In an extended report we would have at least one phase information
func (m *LiveMeasurement) IsExtended() bool {
return m.CurrentPhase1 > 0 || m.CurrentPhase2 > 0 || m.CurrentPhase3 > 0
}
// HasPower returns true if the report contains power measurement
func (m *LiveMeasurement) HasPower() bool {
return m.Power > 0
}
// HasProductionOrConsumptionPower return true if measurement contains values
func (m *LiveMeasurement) HasProductionOrConsumptionPower() bool {
return m.Power > 0 || m.PowerProduction > 0
}
// AsFloatMap returns the LiveMeasurement struct as a float map
func (m *LiveMeasurement) AsFloatMap() map[string]float64 {
return map[string]float64{
"p_import": m.Power,
"e_import": m.LastMeterConsumption,
"e_export": m.LastMeterProduction,
"last_e_import": m.AccumulatedConsumption,
"last_e_export": m.AccumulatedProduction,
"p_import_min": m.MinPower,
"p_import_avg": m.AveragePower,
"p_import_max": m.MaxPower,
"p_export": m.PowerProduction,
"p_export_min": m.MinPowerProduction,
"p_export_max": m.MaxPowerProduction,
"u1": m.VoltagePhase1,
"u2": m.VoltagePhase2,
"u3": m.VoltagePhase3,
"i1": m.CurrentPhase1,
"i2": m.CurrentPhase2,
"i3": m.CurrentPhase3,
}
}
// Stream for subscribing to Tibber pulse
type Stream struct {
Token string
ID string
isRunning bool
initialized bool
client *websocket.Conn
stateReportChan chan StreamState
outputChan MsgChan
}
func (ts *Stream) StateReportChan() chan StreamState {
return ts.stateReportChan
}
// NewStream with id and token
func NewStream(id, token string) *Stream {
ts := Stream{
ID: id,
Token: token,
isRunning: true,
initialized: false,
stateReportChan: make(chan StreamState),
}
return &ts
}
// StartSubscription init connection and subscribes to home id
func (ts *Stream) StartSubscription(outputChan MsgChan) error {
// Connect
ts.outputChan = outputChan
for {
err := ts.connect()
if err != nil {
log.WithError(err).Error("<TibberStream> Could not connect to websocket")
time.Sleep(time.Second * 7) // trying to repair the connection
} else {
ts.initialized = false
log.Info("<TibberStream> Connected")
break // connection was made
}
}
ts.startMsgRouter()
return nil
}
func (ts *Stream) reportState(state string, err error) {
st := StreamState{
State: state,
Err: err,
}
select {
case ts.stateReportChan <- st:
default:
log.Debug("<TibberStream> No error liste")
}
}
func (ts *Stream) startMsgRouter() {
go func() {
for {
ts.msgLoop()
log.Error("<TibberStream> Restarting msg router")
}
}()
}
func (ts *Stream) msgLoop() {
defer func() {
if r := recover(); r != nil {
log.Error("<TibberStream> Process CRASHED with error: ", r)
time.Sleep(1 * time.Minute)
}
if ts.client != nil {
ts.client.Close()
}
}()
var unknownErrorCounter int
for {
if !ts.initialized {
ts.sendInitMsg()
}
tm := StreamMsg{}
err := ts.client.ReadJSON(&tm)
if err != nil {
if ts.isWsCloseError(err) {
log.WithError(err).Error("<TibberStream> CloseError, Reconnecting after 10 seconds")
ts.reportState(StreamStateDisconnected, err)
time.Sleep(time.Second * 10) // trying to repair the connection
ts.initialized = false
err = ts.connect()
if err != nil {
log.WithError(err).Error("<TibberStream> Could not connect to websocket")
time.Sleep(time.Second * 30)
}
continue
} else {
unknownErrorCounter++
log.WithError(err).Error("<TibberStream> Unknown error while reading data from WS")
ts.reportState(StreamStateDisconnected, err)
time.Sleep(time.Second * 20)
if unknownErrorCounter > 10 {
ts.client.Close()
err = ts.connect()
if err != nil {
log.WithError(err).Error("<TibberStream> Could not connect to websocket")
time.Sleep(time.Second * 60)
}
}
continue
}
} else {
unknownErrorCounter = 0
switch tm.Type {
case "init_success":
log.Info("<TibberStream> Init success")
ts.initialized = true
ts.sendSubMsg()
case "subscription_success":
log.Info("<TibberStream> Subscription success")
case "subscription_data":
tm.HomeID = ts.ID
ts.outputChan <- &tm
case "subscription_fail":
err := fmt.Errorf("subscription failed")
log.WithError(err).Error("<TibberStream>")
ts.reportState(StreamStateDisconnected, err)
default:
log.Info("<TibberStream> Unexpected message type :", tm.Type)
}
}
if !ts.isRunning {
log.Debug("<TibberStream> Stopping")
break
}
}
}
func (ts *Stream) isWsCloseError(err error) bool {
return websocket.IsCloseError(err,
websocket.CloseGoingAway,
websocket.CloseAbnormalClosure,
websocket.CloseNormalClosure,
websocket.CloseProtocolError,
websocket.CloseUnsupportedData,
websocket.CloseNoStatusReceived,
websocket.CloseInvalidFramePayloadData,
websocket.ClosePolicyViolation,
websocket.CloseMessageTooBig,
websocket.CloseMandatoryExtension,
websocket.CloseInternalServerErr,
websocket.CloseServiceRestart,
websocket.CloseTryAgainLater,
websocket.CloseTLSHandshake)
}
func (ts *Stream) connect() error {
defer func() {
if r := recover(); r != nil {
log.Error("<TibberStream> ID: ", ts.ID, " - Process CRASHED with error : ", r)
time.Sleep(time.Minute * 1)
}
}()
u := url.URL{Scheme: "wss", Host: tibberHost, Path: subscriptionEndpoint}
log.Infof("<TibberStream> Connecting to %s", u.String())
var err error
for {
reqHeader := make(http.Header)
reqHeader.Add("Sec-WebSocket-Protocol", "graphql-subscriptions")
ts.client, _, err = websocket.DefaultDialer.Dial(u.String(), reqHeader)
if err != nil {
log.Error("<TibberStream> Dial error", err)
time.Sleep(time.Second * 2)
} else {
log.Info("<TibberStream> WS Client is connected - ID: ", ts.ID, " error: ", err)
ts.isRunning = true
ts.reportState(StreamStateConnected, err)
return nil
}
}
}
// Stop stops stream
func (ts *Stream) Stop() {
log.Debug("<TibberWsClient> setting isRunning to false")
ts.isRunning = false
}
func (ts *Stream) sendInitMsg() {
init := `{"type":"init","payload":"token=` + ts.Token + `"}`
ts.client.WriteMessage(websocket.TextMessage, []byte(init))
}
func jsonEscape(i string) string {
b, err := json.Marshal(i)
if err != nil {
panic(err)
}
// Trim the beginning and trailing " character
return string(b[1 : len(b)-1])
}
func (ts *Stream) sendSubMsg() {
homeID := ts.ID
var subscriptionQuery = fmt.Sprintf(`
subscription {
liveMeasurement(homeId:"%s") {
timestamp
power
lastMeterConsumption
lastMeterProduction
accumulatedConsumption
accumulatedCost
accumulatedProduction
accumulatedReward
minPower
averagePower
maxPower
powerProduction
minPowerProduction
maxPowerProduction
voltagePhase1
voltagePhase2
voltagePhase3
currentPhase1
currentPhase2
currentPhase3
}
}`,
homeID)
sub := fmt.Sprintf(`
{
"query": "%s",
"variables":null,
"type":"subscription_start",
"id":0
}`, jsonEscape(subscriptionQuery))
log.Debug("Subscribe with query", sub)
ts.client.WriteMessage(websocket.TextMessage, []byte(sub))
}