-
Notifications
You must be signed in to change notification settings - Fork 12
/
client.go
516 lines (459 loc) · 12.6 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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
package golifx
import (
"sync"
"time"
"github.com/pdf/golifx/common"
)
// Client provides a simple interface for interacting with LIFX devices. Client
// can not be instantiated manually or it will not function - always use
// NewClient() to obtain a Client instance.
type Client struct {
discoveryInterval time.Duration
quitChan chan struct{}
protocol common.Protocol
timeout time.Duration
retryInterval time.Duration
internalRetryInterval time.Duration
common.SubscriptionProvider
sync.RWMutex
}
// GetLocations returns a slice of all locations known to the client, or
// common.ErrNotFound if no locations are currently known.
func (c *Client) GetLocations() (locations []common.Location, err error) {
return c.protocol.GetLocations()
}
// GetLocationByID looks up a location by its `id` and returns a common.Location.
// May return a common.ErrNotFound error if the lookup times out without finding
// the location.
func (c *Client) GetLocationByID(id string) (common.Location, error) {
location, err := c.protocol.GetLocation(id)
if err == nil {
return location, nil
}
var timeout <-chan time.Time
if c.timeout > 0 {
timeout = time.After(c.timeout)
} else {
timeout = make(<-chan time.Time)
}
sub := c.protocol.Subscribe()
defer func() {
if err = sub.Close(); err != nil {
common.Log.Warnf("Failed closing location subscription: %+v", err)
}
}()
events := sub.Events()
for {
select {
case event, ok := <-events:
if !ok {
return nil, common.ErrClosed
}
switch event := event.(type) {
case common.EventNewLocation:
if id == event.Location.ID() {
return event.Location, nil
}
}
case <-timeout:
return nil, common.ErrNotFound
}
}
}
// GetLocationByLabel looks up a location by its `label` and returns a
// common.Location. May return a common.ErrNotFound error if the lookup times
// out without finding the location.
func (c *Client) GetLocationByLabel(label string) (common.Location, error) {
locations, _ := c.GetLocations()
for _, location := range locations {
if label == location.GetLabel() {
return location, nil
}
}
var timeout <-chan time.Time
if c.timeout > 0 {
timeout = time.After(c.timeout)
} else {
timeout = make(<-chan time.Time)
}
sub := c.protocol.Subscribe()
defer func() {
if err := sub.Close(); err != nil {
common.Log.Warnf("Failed closing location subscription: %+v", err)
}
}()
events := sub.Events()
for {
select {
case event, ok := <-events:
if !ok {
return nil, common.ErrClosed
}
switch event := event.(type) {
case common.EventNewLocation:
if label == event.Location.GetLabel() {
return event.Location, nil
}
}
case <-timeout:
return nil, common.ErrNotFound
}
}
}
// GetGroups returns a slice of all groups known to the client, or
// common.ErrNotFound if no groups are currently known.
func (c *Client) GetGroups() (groups []common.Group, err error) {
return c.protocol.GetGroups()
}
// GetGroupByID looks up a group by its `id` and returns a common.Group.
// May return a common.ErrNotFound error if the lookup times out without finding
// the group.
func (c *Client) GetGroupByID(id string) (common.Group, error) {
group, err := c.protocol.GetGroup(id)
if err == nil {
return group, nil
}
var timeout <-chan time.Time
if c.timeout > 0 {
timeout = time.After(c.timeout)
} else {
timeout = make(<-chan time.Time)
}
sub := c.protocol.Subscribe()
defer func() {
if err = sub.Close(); err != nil {
common.Log.Warnf("Failed closing group subscription: %+v", err)
}
}()
events := sub.Events()
for {
select {
case event, ok := <-events:
if !ok {
return nil, common.ErrClosed
}
switch event := event.(type) {
case common.EventNewGroup:
if id == event.Group.ID() {
return event.Group, nil
}
}
case <-timeout:
return nil, common.ErrNotFound
}
}
}
// GetGroupByLabel looks up a group by its `label` and returns a common.Group.
// May return a common.ErrNotFound error if the lookup times out without finding
// the group.
func (c *Client) GetGroupByLabel(label string) (common.Group, error) {
groups, _ := c.GetGroups()
for _, dev := range groups {
if label == dev.GetLabel() {
return dev, nil
}
}
var timeout <-chan time.Time
if c.timeout > 0 {
timeout = time.After(c.timeout)
} else {
timeout = make(<-chan time.Time)
}
sub := c.protocol.Subscribe()
defer func() {
if err := sub.Close(); err != nil {
common.Log.Warnf("Failed closing group subscription: %+v", err)
}
}()
events := sub.Events()
for {
select {
case event, ok := <-events:
if !ok {
return nil, common.ErrClosed
}
switch event := event.(type) {
case common.EventNewGroup:
if label == event.Group.GetLabel() {
return event.Group, nil
}
}
case <-timeout:
return nil, common.ErrNotFound
}
}
}
// GetDevices returns a slice of all devices known to the client, or
// common.ErrNotFound if no devices are currently known.
func (c *Client) GetDevices() (devices []common.Device, err error) {
return c.protocol.GetDevices()
}
// GetDeviceByID looks up a device by its `id` and returns a common.Device.
// May return a common.ErrNotFound error if the lookup times out without finding
// the device.
func (c *Client) GetDeviceByID(id uint64) (common.Device, error) {
dev, err := c.protocol.GetDevice(id)
if err == nil {
return dev, nil
}
var timeout <-chan time.Time
if c.timeout > 0 {
timeout = time.After(c.timeout)
} else {
timeout = make(<-chan time.Time)
}
sub := c.protocol.Subscribe()
defer func() {
if err = sub.Close(); err != nil {
common.Log.Warnf("Failed closing device subscription: %+v", err)
}
}()
events := sub.Events()
for {
select {
case event, ok := <-events:
if !ok {
return nil, common.ErrClosed
}
switch event := event.(type) {
case common.EventNewDevice:
if id == event.Device.ID() {
return event.Device, nil
}
}
case <-timeout:
return nil, common.ErrNotFound
}
}
}
// GetDeviceByLabel looks up a device by its `label` and returns a common.Device.
// May return a common.ErrNotFound error if the lookup times out without finding
// the device.
func (c *Client) GetDeviceByLabel(label string) (common.Device, error) {
devices, _ := c.GetDevices()
for _, dev := range devices {
res, err := dev.GetLabel()
if err == nil && res == label {
return dev, nil
}
}
var timeout <-chan time.Time
if c.timeout > 0 {
timeout = time.After(c.timeout)
} else {
timeout = make(<-chan time.Time)
}
sub := c.protocol.Subscribe()
defer func() {
if err := sub.Close(); err != nil {
common.Log.Warnf("Failed closing device subscription: %+v", err)
}
}()
events := sub.Events()
for {
select {
case event, ok := <-events:
if !ok {
return nil, common.ErrClosed
}
switch event := event.(type) {
case common.EventNewDevice:
l, err := event.Device.GetLabel()
if err != nil {
return nil, err
}
if l == label {
return event.Device, nil
}
}
case <-timeout:
return nil, common.ErrNotFound
}
}
}
// GetLights returns a slice of all lights known to the client, or
// common.ErrNotFound if no lights are currently known.
func (c *Client) GetLights() (lights []common.Light, err error) {
devices, err := c.GetDevices()
if err != nil {
return lights, err
}
for _, dev := range devices {
if light, ok := dev.(common.Light); ok {
lights = append(lights, light)
}
}
if len(lights) == 0 {
return lights, common.ErrNotFound
}
return lights, nil
}
// GetLightByID looks up a light by its `id` and returns a common.Light.
// May return a common.ErrNotFound error if the lookup times out without finding
// the light, or common.ErrDeviceInvalidType if the device exists but is not a
// light.
func (c *Client) GetLightByID(id uint64) (light common.Light, err error) {
dev, err := c.GetDeviceByID(id)
if err != nil {
return nil, err
}
light, ok := dev.(common.Light)
if !ok {
return nil, common.ErrDeviceInvalidType
}
return light, nil
}
// GetLightByLabel looks up a light by its `label` and returns a common.Light.
// May return a common.ErrNotFound error if the lookup times out without finding
// the light, or common.ErrDeviceInvalidType if the device exists but is not a
// light.
func (c *Client) GetLightByLabel(label string) (common.Light, error) {
dev, err := c.GetDeviceByLabel(label)
if err != nil {
return nil, err
}
light, ok := dev.(common.Light)
if !ok {
return nil, common.ErrDeviceInvalidType
}
return light, nil
}
// SetPower broadcasts a request to change the power state of all devices on
// the network. A state of true requests power on, and a state of false
// requests power off.
func (c *Client) SetPower(state bool) error {
return c.protocol.SetPower(state)
}
// SetPowerDuration broadcasts a request to change the power state of all
// devices on the network, transitioning over the specified duration. A state
// of true requests power on, and a state of false requests power off. Not all
// device types support transitioning, so if you wish to change the state of all
// device types, you should use SetPower instead.
func (c *Client) SetPowerDuration(state bool, duration time.Duration) error {
return c.protocol.SetPowerDuration(state, duration)
}
// SetColor broadcasts a request to change the color of all devices on the
// network.
func (c *Client) SetColor(color common.Color, duration time.Duration) error {
return c.protocol.SetColor(color, duration)
}
// SetDiscoveryInterval causes the client to discover devices and state every
// interval. You should set this to a non-zero value for any long-running
// process, otherwise devices will only be discovered once.
func (c *Client) SetDiscoveryInterval(interval time.Duration) error {
c.Lock()
if c.discoveryInterval != 0 {
for i := 0; i < cap(c.quitChan); i++ {
c.quitChan <- struct{}{}
}
}
c.discoveryInterval = interval
c.Unlock()
common.Log.Infof("Starting discovery with interval %v", interval)
return c.discover()
}
// SetTimeout sets the time that client operations wait for results before
// returning an error. The special value of 0 may be set to disable timeouts,
// and all operations will wait indefinitely, but this is not recommended.
func (c *Client) SetTimeout(timeout time.Duration) {
c.timeout = timeout
}
// GetTimeout returns the currently configured timeout period for operations on
// this client
func (c *Client) GetTimeout() *time.Duration {
return &c.timeout
}
// SetRetryInterval sets the retry interval for operations on this client. If
// a timeout has been set, and the retry interval exceeds the timeout, the retry
// interval will be set to half the timeout
func (c *Client) SetRetryInterval(retryInterval time.Duration) {
if c.timeout > 0 && retryInterval >= c.timeout {
retryInterval = c.timeout / 2
}
c.Lock()
c.retryInterval = retryInterval
c.Unlock()
}
// GetRetryInterval returns the currently configured retry interval for
// operations on this client
func (c *Client) GetRetryInterval() *time.Duration {
c.RLock()
defer c.RUnlock()
return &c.retryInterval
}
// Close signals the termination of this client, and cleans up resources
func (c *Client) Close() error {
c.Lock()
defer c.Unlock()
select {
case <-c.quitChan:
common.Log.Warnf(`client already closed`)
return common.ErrClosed
default:
close(c.quitChan)
}
if err := c.SubscriptionProvider.Close(); err != nil {
common.Log.Warnf("closing subscriptions: %v", err)
}
return c.protocol.Close()
}
// subscribe to protocol events and proxy to client subscriptions
func (c *Client) subscribe() error {
sub := c.protocol.Subscribe()
events := sub.Events()
go func() {
for {
select {
case <-c.quitChan:
return
default:
}
select {
case <-c.quitChan:
return
case event := <-events:
switch event.(type) {
case common.EventNewDevice,
common.EventNewGroup,
common.EventNewLocation,
common.EventExpiredDevice,
common.EventExpiredGroup,
common.EventExpiredLocation:
c.Notify(event)
}
}
}
}()
return nil
}
func (c *Client) discover() error {
if c.discoveryInterval == 0 {
common.Log.Debugf("Discovery interval is zero, discovery will only be performed once")
return c.protocol.Discover()
}
go func() {
c.RLock()
tick := time.NewTicker(c.discoveryInterval)
c.RUnlock()
defer func() {
tick.Stop()
}()
for {
select {
case <-c.quitChan:
common.Log.Debugf("Quitting discovery loop")
return
default:
}
select {
case <-c.quitChan:
common.Log.Debugf("Quitting discovery loop")
return
case <-tick.C:
common.Log.Debugf("Performing discovery")
_ = c.protocol.Discover()
}
}
}()
return nil
}