-
Notifications
You must be signed in to change notification settings - Fork 6
/
version.go
125 lines (109 loc) · 2.51 KB
/
version.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
package lifxlan
import (
"bytes"
"context"
"encoding/binary"
"fmt"
"net"
"strings"
)
// EmptyHardwareVersion is the constant to be compared against
// Device.HardwareVersion().String().
const EmptyHardwareVersion = "(0, 0, 0)"
// RawStateVersionPayload defines the struct to be used for encoding and
// decoding.
//
// https://lan.developer.lifx.com/docs/information-messages#stateversion---packet-33
type RawStateVersionPayload struct {
Version HardwareVersion
}
// ProductMapKey generates key for ProductMap based on vendor and product ids.
func ProductMapKey(vendor, product uint32) uint64 {
return uint64(vendor)<<32 + uint64(product)
}
// HardwareVersion defines raw version info in message payloads according to:
//
// https://lan.developer.lifx.com/docs/information-messages#stateversion---packet-33
type HardwareVersion struct {
VendorID uint32
ProductID uint32
HardwareVersion uint32
}
// ProductMapKey generates key for ProductMap.
func (raw HardwareVersion) ProductMapKey() uint64 {
return ProductMapKey(raw.VendorID, raw.ProductID)
}
// Parse parses the raw hardware version info by looking up ProductMap.
//
// If this hardware version info is not in ProductMap, nil will be returned.
func (raw HardwareVersion) Parse() *Product {
parsed, ok := ProductMap[raw.ProductMapKey()]
if !ok {
return nil
}
return &parsed
}
func (raw HardwareVersion) String() string {
var sb strings.Builder
parsed := raw.Parse()
if parsed != nil {
sb.WriteString(parsed.ProductName)
}
sb.WriteString(
fmt.Sprintf(
"(%v, %v, %v)",
raw.VendorID,
raw.ProductID,
raw.HardwareVersion,
),
)
return sb.String()
}
func (d *device) HardwareVersion() *HardwareVersion {
return &d.version
}
func (d *device) GetHardwareVersion(ctx context.Context, conn net.Conn) 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()
}
}
seq, err := d.Send(
ctx,
conn,
0, // flags
GetVersion,
nil, // payload
)
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 != StateVersion {
continue
}
var raw RawStateVersionPayload
r := bytes.NewReader(resp.Payload)
if err := binary.Read(r, binary.LittleEndian, &raw); err != nil {
return err
}
d.version = raw.Version
return nil
}
}