forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tibber-pulse.go
198 lines (161 loc) · 3.84 KB
/
tibber-pulse.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
package meter
import (
"context"
"encoding/json"
"errors"
"net/http"
"sync"
"time"
"github.com/connectorjs/evcm/api"
"github.com/connectorjs/evcm/meter/tibber"
"github.com/connectorjs/evcm/util"
"github.com/connectorjs/evcm/util/request"
"github.com/connectorjs/evcm/util/transport"
"github.com/hasura/go-graphql-client"
)
func init() {
registry.Add("tibber-pulse", NewTibberFromConfig)
}
type Tibber struct {
mu sync.Mutex
log *util.Logger
updated time.Time
live tibber.LiveMeasurement
url string
token, homeID string
client *graphql.SubscriptionClient
}
func NewTibberFromConfig(other map[string]interface{}) (api.Meter, error) {
var cc struct {
Token string
HomeID string
}
if err := util.DecodeOther(other, &cc); err != nil {
return nil, err
}
if cc.Token == "" {
return nil, errors.New("missing token")
}
log := util.NewLogger("pulse").Redact(cc.Token, cc.HomeID)
// query client
qclient := tibber.NewClient(log, cc.Token)
if cc.HomeID == "" {
home, err := qclient.DefaultHome("")
if err != nil {
return nil, err
}
cc.HomeID = home.ID
}
var res struct {
Viewer struct {
WebsocketSubscriptionUrl string
}
}
ctx, cancel := context.WithTimeout(context.Background(), request.Timeout)
defer cancel()
if err := qclient.Query(ctx, &res, nil); err != nil {
return nil, err
}
t := &Tibber{
log: log,
url: res.Viewer.WebsocketSubscriptionUrl,
token: cc.Token,
homeID: cc.HomeID,
}
// run the client
err := t.reconnect()
return t, err
}
// newSubscriptionClient creates graphql subscription client
func (t *Tibber) newSubscriptionClient() {
t.client = graphql.NewSubscriptionClient(t.url).
WithProtocol(graphql.GraphQLWS).
WithWebSocketOptions(graphql.WebsocketOptions{
HTTPClient: &http.Client{
Transport: &transport.Decorator{
Base: http.DefaultTransport,
Decorator: transport.DecorateHeaders(map[string]string{
"User-Agent": "go-graphql-client/0.9.0",
}),
},
},
}).
WithConnectionParams(map[string]any{
"token": t.token,
}).
WithRetryTimeout(0).
WithLog(t.log.TRACE.Println)
}
func (t *Tibber) subscribe(done chan error) {
var (
once sync.Once
query struct {
tibber.LiveMeasurement `graphql:"liveMeasurement(homeId: $homeId)"`
}
)
_, err := t.client.Subscribe(&query, map[string]any{
"homeId": graphql.ID(t.homeID),
}, func(data []byte, err error) error {
if err != nil {
once.Do(func() { done <- err })
}
var res struct {
LiveMeasurement tibber.LiveMeasurement
}
if err := json.Unmarshal(data, &res); err != nil {
once.Do(func() { done <- err })
t.log.ERROR.Println(err)
return nil
}
t.mu.Lock()
t.live = res.LiveMeasurement
t.updated = time.Now()
t.mu.Unlock()
once.Do(func() { close(done) })
return nil
})
if err != nil {
once.Do(func() { done <- err })
}
go func() {
if err := t.client.Run(); err != nil {
once.Do(func() { done <- err })
}
}()
}
func (t *Tibber) reconnect() error {
const timeout = time.Minute
t.mu.Lock()
if time.Since(t.updated) <= timeout {
t.mu.Unlock()
return nil
}
t.mu.Unlock()
if t.client != nil {
if err := t.client.Close(); err != nil {
t.log.DEBUG.Println("close:", err)
}
}
t.newSubscriptionClient()
done := make(chan error)
go t.subscribe(done)
return <-done
}
func (t *Tibber) CurrentPower() (float64, error) {
if err := t.reconnect(); err != nil {
return 0, err
}
t.mu.Lock()
defer t.mu.Unlock()
return t.live.Power - t.live.PowerProduction, nil
}
var _ api.PhaseCurrents = (*Tibber)(nil)
// Currents implements the api.PhaseCurrents interface
func (t *Tibber) Currents() (float64, float64, float64, error) {
if err := t.reconnect(); err != nil {
return 0, 0, 0, err
}
t.mu.Lock()
defer t.mu.Unlock()
return t.live.CurrentL1, t.live.CurrentL2, t.live.CurrentL3, nil
}