-
Notifications
You must be signed in to change notification settings - Fork 6
/
echo.go
82 lines (70 loc) · 1.37 KB
/
echo.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
package lifxlan
import (
"bytes"
"context"
"encoding/binary"
"errors"
"math/rand"
"net"
)
const (
EchoPayloadLength = 64
)
// RawEchoResponsePayload defines echo response payload according to:
//
// https://lan.developer.lifx.com/docs/information-messages#echoresponse---packet-59
type RawEchoResponsePayload struct {
Echoing [EchoPayloadLength]byte
}
func (d *device) Echo(ctx context.Context, conn net.Conn, payload []byte) 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()
}
}
body := make([]byte, EchoPayloadLength)
copy(body, payload)
if len(payload) < EchoPayloadLength {
rand.Read(body[len(payload):])
}
seq, err := d.Send(
ctx,
conn,
0, // flags
EchoRequest,
body,
)
if err != nil {
return err
}
for {
resp, err := ReadNextResponse(ctx, conn)
if err != nil {
return err
}
if resp.Sequence != seq || resp.Source != d.Source() {
continue
}
if resp.Message != EchoResponse {
continue
}
var raw RawEchoResponsePayload
r := bytes.NewReader(resp.Payload)
if err := binary.Read(r, binary.LittleEndian, &raw); err != nil {
return err
}
if !bytes.Equal(raw.Echoing[:], body) {
return errors.New("unexpected echo response value")
}
return nil
}
}