/
client.go
366 lines (301 loc) · 8.59 KB
/
client.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
359
360
361
362
363
364
365
366
package ig
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"path/filepath"
"strings"
"sync"
"time"
)
const (
igBaseURL = "https://api.autogrow.com/v1"
igTokenURI = igBaseURL + "/auth/token"
igRefreshURI = igBaseURL + "/auth/token/refresh"
igDeviceURI = "/intelligrow/devices?username="
igDevicesURI = igBaseURL + "/intelligrow/devices"
igDeviceStateURI = igBaseURL + "/intelligrow/devices/state?device="
igMetricsURI = igBaseURL + "/intelligrow/devices/metrics?device="
igConfigURI = igBaseURL + "/intelligrow/devices/config?device="
igHistoryURI = igBaseURL + "/intelligrow/devices/history?device="
)
// Client - object that can be used to communicate directly with intelligrow
type Client struct {
*http.Client
lock *sync.RWMutex
username string
password string
auth authResponse
CheckedDevices float64
growrooms map[string]*Growroom
devices *Devices
tokenRefresherQuit chan bool
url url.URL
}
// NewClient creates a new client with the given username and password. It will
// return an error if the authentication fails
func NewClient(user, pass string) (*Client, error) {
c := &Client{
Client: &http.Client{Timeout: time.Second * 30},
lock: new(sync.RWMutex),
username: user,
password: pass,
growrooms: make(map[string]*Growroom),
}
c.url.Scheme = "https"
c.url.Host = "api.autogrow.com"
// Initialize the devices object in the structure, this is blank object
c.devices = NewDevices()
err := c.authenticate()
if err != nil {
return c, err
}
go c.autoAuthExtender()
return c, nil
}
// Close the client (read: stop trying to refresh the auth token every hour)
func (c *Client) Close() error {
if c.tokenRefresherQuit != nil {
close(c.tokenRefresherQuit)
}
return nil
}
// AutoUpdater - automatically updates the device connected to the client
func (c *Client) AutoUpdater(pollInterval int, quit chan bool, updateInterval chan int) {
ticker := time.NewTicker(time.Duration(pollInterval) * time.Second)
for {
select {
case <-ticker.C:
c.UpdateAllGrowrooms()
case stop, ok := <-quit:
if !ok || stop {
return
}
case newInt, ok := <-updateInterval:
if !ok {
return
}
ticker.Stop()
ticker = time.NewTicker(time.Duration(newInt) * time.Second)
}
}
}
func (c *Client) buildURL(path string, queries ...string) string {
u := c.url
u.Path = filepath.Join("v1", path)
u.RawQuery = strings.Join(queries, "&")
return u.String()
}
func (c *Client) doRequest(method, url string, body io.Reader) (*http.Response, error) {
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", c.getToken())
return c.Do(req)
}
// SaveDevice will save the config and state of the given device
func (c *Client) SaveDevice(i Intelli) error {
payload, err := i.StatePayload()
if err != nil {
return err
}
data, err := json.Marshal(payload)
if err != nil {
return err
}
res, err := c.doRequest("PUT", c.buildURL("/intelligrow/devices"), bytes.NewBuffer(data))
if err != nil {
return fmt.Errorf("failed to save state/config: %s", err)
}
if res.StatusCode != 200 {
return fmt.Errorf("unexpected http status: %d", res.StatusCode)
}
return nil
}
// GetDevices is deprecated in favour of RefreshDevices
func (c *Client) GetDevices() error {
return c.RefreshDevices()
}
// RefreshDevices will get the latest data from the API and update all known structs
func (c *Client) RefreshDevices() error {
res, err := c.doRequest("GET", c.buildURL("/intelligrow/devices", "username="+c.username), nil)
if err != nil {
return fmt.Errorf("failed to refresh devices; %s", err)
}
msi := make(map[string]interface{})
data, err := ioutil.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("couldn't read response body: %s", err)
}
if err := json.Unmarshal(data, &msi); err != nil {
return fmt.Errorf("couldn't unmarshal response body: %s", err)
}
checkedDevices, exists := msi["checked_devices"]
if !exists {
return fmt.Errorf("no checked devices in response")
}
c.CheckedDevices = checkedDevices.(float64)
devices, exists := msi["devices"]
if !exists {
return fmt.Errorf("no devices in response")
}
data, err = json.Marshal(devices)
if err != nil {
return fmt.Errorf("Error marshalling devices interface: %s", err)
}
var igDevices []*Device
if err := json.Unmarshal(data, &igDevices); err != nil {
return fmt.Errorf("Error unmarshalling devices: %s", err)
}
c.lock.Lock()
for _, d := range igDevices {
d.AttachClient(c)
c.devices.Add(d)
c.addDeviceToGrowroom(d)
}
c.lock.Unlock()
return err
}
func (c *Client) addDeviceToGrowroom(dev *Device) {
grName := dev.GetGrowroom()
gr, exists := c.growrooms[grName]
if !exists {
gr = NewGrowroom(grName)
c.growrooms[grName] = gr
}
gr.AddDevice(dev)
}
// IntelliClimate will return the IntelliClimate with the given name or serial
func (c *Client) IntelliClimate(nameOrID string) (*IntelliClimate, error) {
if c.devices.IsEmpty() {
c.RefreshDevices()
}
ic, err := c.devices.GetClimateByID(nameOrID)
if err != nil {
ic, err = c.devices.GetClimateByName(nameOrID)
if err != nil {
return nil, fmt.Errorf("no IntelliClimate found with name or serial of %s", nameOrID)
}
}
return ic, nil
}
// IntelliDose will return the IntelliDose with the given name or serial
func (c *Client) IntelliDose(nameOrID string) (*IntelliDose, error) {
if c.devices.IsEmpty() {
c.RefreshDevices()
}
id, err := c.devices.GetDoserByID(nameOrID)
if err != nil {
id, err = c.devices.GetDoserByName(nameOrID)
if err != nil {
return nil, fmt.Errorf("no IntelliDose found with name or serial of %s", nameOrID)
}
}
return id, nil
}
// IntelliDoses will return all known IntelliDoses
func (c *Client) IntelliDoses() ([]*IntelliDose, error) {
if c.devices.IsEmpty() {
c.RefreshDevices()
}
return c.devices.Dosers(), nil
}
// IntelliClimates will return all known IntelliClimates
func (c *Client) IntelliClimates() ([]*IntelliClimate, error) {
if c.devices.IsEmpty() {
c.RefreshDevices()
}
return c.devices.Climates(), nil
}
// Devices returns the devices found in IntelliGrow for the user
func (c *Client) Devices() []*Device {
if c.devices.IsEmpty() {
c.RefreshDevices()
}
devs := []*Device{}
for _, ic := range c.devices.IntelliClimates {
devs = append(devs, ic.Device)
}
for _, id := range c.devices.IntelliDoses {
devs = append(devs, id.Device)
}
return devs
}
// ListDevicesBySerial will return the serial numbers of all known devices
func (c *Client) ListDevicesBySerial() []string {
if len(c.growrooms) == 0 {
c.RefreshDevices()
}
serials := []string{}
for _, ic := range c.devices.IntelliClimates {
serials = append(serials, ic.ID)
}
for _, id := range c.devices.IntelliDoses {
serials = append(serials, id.ID)
}
return serials
}
// ListGrowrooms returns a list of the names known growrooms
func (c *Client) ListGrowrooms() []string {
if len(c.growrooms) == 0 {
c.RefreshDevices()
}
grs := []string{}
for n := range c.growrooms {
grs = append(grs, n)
}
return grs
}
// Growroom returns the growroom with the given name, and a false if it
// wasn't found
func (c *Client) Growroom(name string) (*Growroom, bool) {
if len(c.growrooms) == 0 {
c.RefreshDevices()
}
growroom, exists := c.growrooms[name]
return growroom, exists
}
// GetGrowroom is deprecated in favour of Growroom
func (c *Client) GetGrowroom(name string) (*Growroom, bool) {
return c.Growroom(name)
}
// UpdateAllGrowrooms - Updated all growrooms
func (c *Client) UpdateAllGrowrooms() {
for _, gr := range c.growrooms {
gr.Update()
}
}
// UpdateGrowroom - returns the growroom specified and an error
func (c *Client) UpdateGrowroom(gr string) error {
growroom, exists := c.growrooms[gr]
if !exists {
return fmt.Errorf("No growroom called %s found", gr)
}
return growroom.Update()
}
// GetGrowroomReading - returns the reading for the growroom specified as a string, also return an error
func (c *Client) GetGrowroomReading(gr, reading string) (string, error) {
growroom, exists := c.growrooms[gr]
if !exists {
return "no growroom found", fmt.Errorf("No growroom called %s found", gr)
}
avaliable, r := growroom.GetReading(reading)
if !avaliable {
return "no reading found", fmt.Errorf("No reading called %s found in growroom %s", r, gr)
}
return r, nil
}
// Growrooms returns a slice of all the known growrooms
func (c *Client) Growrooms() []*Growroom {
grs := []*Growroom{}
for _, gr := range grs {
grs = append(grs, gr)
}
return grs
}