/
wrap.go
89 lines (77 loc) · 1.67 KB
/
wrap.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
package light
import (
"bytes"
"context"
"encoding/binary"
"go.yhsif.com/lifxlan"
)
// Wrap tries to wrap a lifxlan.Device into a light device.
//
// When force is false and d is already a light device,
// d will be casted and returned directly.
// Otherwise, this function calls a light device API,
// and only returns a non-nil Device if it supports the API.
//
// If the device is not a light device,
// the function might block until ctx is cancelled.
//
// When returning a valid light device,
// the device's Label is guaranteed to be cached.
func Wrap(ctx context.Context, d lifxlan.Device, force bool) (Device, error) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
if !force {
if t, ok := d.(Device); ok {
return t, nil
}
}
conn, err := d.Dial()
if err != nil {
return nil, err
}
defer conn.Close()
if ctx.Err() != nil {
return nil, ctx.Err()
}
const msg = Get
seq, err := d.Send(
ctx,
conn,
0, // flags
msg,
nil, // payload
)
if err != nil {
return nil, err
}
for {
resp, err := lifxlan.ReadNextResponse(ctx, conn)
if err != nil {
return nil, err
}
if resp.Sequence != seq || resp.Source != d.Source() {
continue
}
switch resp.Message {
case State:
var raw RawStatePayload
r := bytes.NewReader(resp.Payload)
if err := binary.Read(r, binary.LittleEndian, &raw); err != nil {
return nil, err
}
ld := &device{
Device: d,
}
*ld.Label() = raw.Label
return ld, nil
case lifxlan.StateUnhandled:
var raw lifxlan.RawStateUnhandledPayload
r := bytes.NewReader(resp.Payload)
if err := binary.Read(r, binary.LittleEndian, &raw); err != nil {
return nil, err
}
return nil, raw
}
}
}