-
Notifications
You must be signed in to change notification settings - Fork 6
/
stream.go
66 lines (60 loc) · 1.54 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
package nest
import (
"bufio"
"encoding/json"
"net/http"
"strings"
)
/*
DevicesStream emits events from the Nest devices REST streaming API
client.DevicesStream(func(event *Devices) {
fmt.Println(event)
})
*/
func (c *Client) DevicesStream(callback func(devices *Devices, err error)) {
c.setRedirectURL()
for {
c.streamDevices(callback)
}
}
// streamDevices connects to the stream, following the redirect and then watches the stream
func (c *Client) streamDevices(callback func(devices *Devices, err error)) {
resp, err := c.getDevices(Stream)
if err != nil {
callback(nil, err)
return
}
defer resp.Body.Close()
c.watchDevicesStream(resp, callback)
}
// watchDevicesStream grabs the data off the stream, parses them and invokes the callback
func (c *Client) watchDevicesStream(resp *http.Response, callback func(devices *Devices, err error)) {
reader := bufio.NewReader(resp.Body)
for {
line, err := reader.ReadString('\n')
if err != nil {
return
}
value := parseStreamData(line)
if value != "" {
devicesEvent := &DevicesEvent{}
json.Unmarshal([]byte(value), devicesEvent)
if devicesEvent.Data != nil {
c.associateClientToDevices(devicesEvent.Data)
callback(devicesEvent.Data, nil)
}
}
}
}
// parseStreamData takes a line of the stream and parses out the JSON data
func parseStreamData(line string) string {
sections := strings.SplitN(line, ":", 2)
field, value := sections[0], ""
if len(sections) == 2 {
value = strings.TrimPrefix(sections[1], " ")
}
if field == "data" {
return value
}
return ""
}