-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathweatherflow.go
281 lines (233 loc) · 6.26 KB
/
weatherflow.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
// Package weatherflow provides a client for accessing WeatherFlow's Smart
// Weather API over a WebSocket connection.
package weatherflow
import (
"context"
"errors"
"fmt"
"math"
"strconv"
"sync"
"time"
"nhooyr.io/websocket"
"nhooyr.io/websocket/wsjson"
)
const (
wfURL = "wss://ws.weatherflow.com/swd/data?token=%s"
initialBackoff = 2 // seconds (don't set below 2)
maxBackoff = 32
)
var (
defaultTimeout = 12 * time.Hour
)
// Client represents a client for the WeatherFlow Smart Weather API.
type Client struct {
deviceIDs map[int]struct{}
url string
timeout time.Duration
logf Logf
conn *websocket.Conn
errors int
ready bool
ctx context.Context
cancel context.CancelFunc
mu sync.RWMutex
}
// NewClient creates a new Client with the given API token, optional connection
// timeout, and an optional log function (if nil, logs will be discarded).
func NewClient(token string, timeout *time.Duration, logf Logf) *Client {
if logf == nil {
logf = func(format string, args ...interface{}) {} // discard
}
if timeout == nil {
timeout = &defaultTimeout
}
ctx, cancel := context.WithCancel(context.Background())
c := &Client{
deviceIDs: make(map[int]struct{}),
url: fmt.Sprintf(wfURL, token),
timeout: *timeout,
logf: logf,
ctx: ctx,
cancel: cancel,
}
return c
}
// SetURL overrides the server URL (for testing).
func (c *Client) SetURL(url string) {
c.url = url
}
// AddDevice subscribes to wind events for a device ID.
func (c *Client) AddDevice(id int) {
c.mu.Lock()
defer c.mu.Unlock()
c.deviceIDs[id] = struct{}{}
if c.conn != nil && c.ready {
c.sendListenStart(id)
}
}
// RemoveDevice unsubscribes from wind events for a device ID.
func (c *Client) RemoveDevice(id int) {
c.mu.Lock()
defer c.mu.Unlock()
delete(c.deviceIDs, id)
if c.conn != nil && c.ready {
c.sendListenStop(id)
}
}
// DeviceCount returns a count of monitored devices.
func (c *Client) DeviceCount() int {
c.mu.RLock()
defer c.mu.RUnlock()
return len(c.deviceIDs)
}
// Start initiates a WebSocket connection to the WeatherFlow server and processes
// incoming messages.
func (c *Client) Start(onMessage func(Message)) {
go func() {
defer c.cancel()
for {
select {
case <-c.ctx.Done():
// Close the WebSocket connection and return
// Probably redundant?
if c.conn != nil {
c.logf("Disconnecting from WeatherFlow")
_ = c.conn.Close(websocket.StatusNormalClosure, "Closing connection")
}
c.ready = false
return
default:
c.handleBackoff()
c.logf("Connecting to WeatherFlow")
conn, _, err := websocket.Dial(c.ctx, c.url, nil)
if err != nil {
c.logf("Error connecting to WeatherFlow: %v", err)
c.errors++
continue
}
// Start a ticker for the connection timeout
ticker := time.NewTicker(c.timeout)
defer ticker.Stop()
defer conn.Close(websocket.StatusInternalError, "closing connection")
c.conn = conn
// Read messages from the WebSocket connection
readLoop:
for {
select {
case <-ticker.C:
c.logf("Connection timeout")
break readLoop
default:
msgType, msg, err := conn.Read(c.ctx)
if err != nil {
if !errors.Is(err, context.Canceled) {
c.logf("Error reading message: %v", err)
c.errors++
}
break readLoop
}
if msgType != websocket.MessageText {
c.logf("Error resolving unexpected message type: %v", msgType)
c.errors++
continue
}
// Parse the message
m, err := UnmarshalMessage(msg)
if err != nil {
c.logf("Error unmarshalling message: %v", err)
c.errors++
continue
}
// Handle the message
switch t := m.(type) {
case *MessageRapidWind:
onMessage(m)
case *MessageObsSt:
onMessage(m)
case *MessageAck:
c.logf("Received ack: %s", t.ID)
case *MessageConnectionOpened:
// Subscribe to wind events
c.mu.Lock()
c.ready = true
for id, _ := range c.deviceIDs {
c.sendListenStart(id)
}
c.mu.Unlock()
default:
c.logf("Received unknown message: %v", t)
}
// One good message resets the error counter.
// Set to 1 to enforce minimum backoff between reconnects.
c.errors = 1
}
}
}
}
}()
}
// handleBackoff sleeps for up to maxBackoff seconds to avoid overwhelming
// the API when it's having issues.
func (c *Client) handleBackoff() {
// No backoff if we haven't gotten any errors yet.
if c.errors == 0 {
return
}
backoff := math.Min(math.Pow(initialBackoff, float64(c.errors)), maxBackoff)
c.logf("sleeping for %.0f sec after %d error(s)", backoff, c.errors)
time.Sleep(time.Duration(backoff) * time.Second)
}
// sendListenStart subscribes to wind observation events.
func (c *Client) sendListenStart(id int) {
c.logf("Listening to wind events from device %d", id)
idStr := strconv.Itoa(id)
startMessage := map[string]interface{}{
"type": "listen_start",
"device_id": id,
"id": "listen_start_" + idStr,
}
rapidStartMessage := map[string]interface{}{
"type": "listen_rapid_start",
"device_id": id,
"id": "listen_rapid_start_" + idStr,
}
err := wsjson.Write(c.ctx, c.conn, startMessage)
if err != nil {
c.logf("Error sending start message: %v", err)
c.errors++
}
err = wsjson.Write(c.ctx, c.conn, rapidStartMessage)
if err != nil {
c.logf("Error sending rapid start message: %v", err)
c.errors++
}
}
// sendListenStop unsubscribes from wind observation events.
func (c *Client) sendListenStop(id int) {
c.logf("Stopping wind events from device %d", id)
idStr := strconv.Itoa(id)
stopMessage := map[string]interface{}{
"type": "listen_stop",
"device_id": id,
"id": "listen_stop_" + idStr,
}
rapidStopMessage := map[string]interface{}{
"type": "listen_rapid_stop",
"device_id": id,
"id": "listen_rapid_stop_" + idStr,
}
err := wsjson.Write(c.ctx, c.conn, stopMessage)
if err != nil {
c.logf("Error sending stop message: %v", err)
c.errors++
}
err = wsjson.Write(c.ctx, c.conn, rapidStopMessage)
if err != nil {
c.logf("Error sending rapid stop message: %v", err)
c.errors++
}
}
func (c *Client) Stop() {
c.cancel()
}