-
Notifications
You must be signed in to change notification settings - Fork 6
/
power.go
147 lines (126 loc) · 2.41 KB
/
power.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
package lifxlan
import (
"bytes"
"context"
"encoding/binary"
"net"
)
// Power is the raw power level value in messages.
//
// https://lan.developer.lifx.com/docs/changing-a-device#setpower---packet-21
// https://lan.developer.lifx.com/docs/information-messages#statepower---packet-22
type Power uint16
// Power values.
const (
PowerOn Power = 65535
PowerOff Power = 0
)
// On returns whether this power level value represents on state.
func (p Power) On() bool {
return p != PowerOff
}
func (p Power) String() string {
if p.On() {
return "on"
}
return "off"
}
// RawStatePowerPayload defines the struct to be used for encoding and decoding.
//
// https://lan.developer.lifx.com/docs/information-messages#statepower---packet-22
type RawStatePowerPayload struct {
Level Power
}
func (d *device) GetPower(ctx context.Context, conn net.Conn) (Power, error) {
if ctx.Err() != nil {
return 0, ctx.Err()
}
if conn == nil {
newConn, err := d.Dial()
if err != nil {
return 0, err
}
defer newConn.Close()
conn = newConn
if ctx.Err() != nil {
return 0, ctx.Err()
}
}
seq, err := d.Send(
ctx,
conn,
0, // flags
GetPower,
nil, // payload
)
if err != nil {
return 0, err
}
for {
resp, err := ReadNextResponse(ctx, conn)
if err != nil {
return 0, err
}
if resp.Sequence != seq || resp.Source != d.Source() {
continue
}
if resp.Message != StatePower {
continue
}
var raw RawStatePowerPayload
r := bytes.NewReader(resp.Payload)
if err := binary.Read(r, binary.LittleEndian, &raw); err != nil {
return 0, err
}
return raw.Level, nil
}
}
// RawSetPowerPayload defines the struct to be used for encoding and decoding.
//
// https://lan.developer.lifx.com/docs/changing-a-device#setpower---packet-21
type RawSetPowerPayload struct {
Level Power
}
func (d *device) SetPower(
ctx context.Context,
conn net.Conn,
power Power,
ack bool,
) error {
if ctx.Err() != nil {
return ctx.Err()
}
if conn == nil {
newConn, err := d.Dial()
if err != nil {
return err
}
defer newConn.Close()
conn = newConn
if ctx.Err() != nil {
return ctx.Err()
}
}
var flags AckResFlag
if ack {
flags |= FlagAckRequired
}
seq, err := d.Send(
ctx,
conn,
flags,
SetPower,
&RawSetPowerPayload{
Level: power,
},
)
if err != nil {
return err
}
if ack {
if err := WaitForAcks(ctx, conn, d.Source(), seq); err != nil {
return err
}
}
return nil
}