-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathresponse.go
94 lines (84 loc) · 1.86 KB
/
response.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
package lifxlan
import (
"bytes"
"context"
"encoding/binary"
"fmt"
"io/ioutil"
"net"
)
// Response is the parsed response from a lifxlan device.
type Response struct {
Message MessageType
Flags AckResFlag
Source uint32
Target Target
Sequence uint8
Payload []byte
}
// ParseResponse parses the response received from a lifxlan device.
func ParseResponse(msg []byte) (*Response, error) {
if len(msg) < int(HeaderLength) {
return nil, fmt.Errorf(
"lifxlan.ParseResponse: response size not enough: %d < %d",
len(msg),
HeaderLength,
)
}
var d RawHeader
r := bytes.NewReader(msg)
if err := binary.Read(r, binary.LittleEndian, &d); err != nil {
return nil, err
}
if len(msg) != int(d.Size) {
return nil, fmt.Errorf(
"lifxlan.ParseResponse: response size mismatch: %d != %d",
len(msg),
d.Size,
)
}
payload, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
resp := &Response{
Message: d.Type,
Flags: d.Flags,
Source: d.Source,
Target: d.Target,
Sequence: d.Sequence,
Payload: payload,
}
if resp.Message == StateUnhandled {
var raw RawStateUnhandledPayload
r := bytes.NewReader(resp.Payload)
if err := binary.Read(r, binary.LittleEndian, &raw); err != nil {
return nil, err
}
return nil, raw
}
return resp, nil
}
// ReadNextResponse returns the next received response.
//
// It handles read buffer, deadline, context cancellation check,
// and response parsing.
func ReadNextResponse(ctx context.Context, conn net.Conn) (*Response, error) {
buf := make([]byte, ResponseReadBufferSize)
for {
if ctx.Err() != nil {
return nil, ctx.Err()
}
if err := conn.SetReadDeadline(GetReadDeadline()); err != nil {
return nil, err
}
n, err := conn.Read(buf)
if err != nil {
if CheckTimeoutError(err) {
continue
}
return nil, err
}
return ParseResponse(buf[:n])
}
}