/
controller-pair-list.go
115 lines (103 loc) · 2.04 KB
/
controller-pair-list.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
package hkontroller
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"net/http"
"github.com/hkontrol/hkontroller/tlv8"
)
type pairListReqPayload struct {
Method byte `tlv8:"0"`
State byte `tlv8:"6"`
}
type pairingPayload struct {
Identifier string `tlv8:"1"`
PublicKey []byte `tlv8:"3"`
Permission byte `tlv8:"11"`
}
// ListPairings should list all controllers of device.
func (d *Device) ListPairings() ([]Pairing, error) {
pl := pairListReqPayload{
State: M1,
Method: MethodListPairings,
}
b, err := tlv8.Marshal(pl)
if err != nil {
return nil, err
}
resp, err := d.doPost("/pairings", HTTPContentTypePairingTLV8, bytes.NewReader(b))
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("invalid status code %v", resp.StatusCode)
}
res := resp.Body
defer res.Close()
var tag byte
err = binary.Read(res, binary.BigEndian, &tag)
if err != nil {
return nil, err
}
var leng byte
err = binary.Read(res, binary.BigEndian, &leng)
if err != nil {
return nil, err
}
val := make([]byte, leng)
err = binary.Read(res, binary.BigEndian, &val)
if err != nil {
return nil, err
}
if tag != 6 && val[0] != M2 {
return nil, errors.New("wrong response")
}
var result []Pairing
var pp Pairing
for err == nil {
var tag byte
err = binary.Read(res, binary.BigEndian, &tag)
if err != nil {
if err == io.EOF {
break
}
return nil, err
}
var leng byte
err = binary.Read(res, binary.BigEndian, &leng)
if err != nil {
if err == io.EOF {
break
}
return nil, err
}
if tag == 0xff {
// separator
result = append(result, pp)
pp = Pairing{}
continue
}
val := make([]byte, leng)
err = binary.Read(res, binary.BigEndian, &val)
if err != nil {
if err == io.EOF {
break
}
return nil, err
}
if tag == 1 {
pp.Id = string(val)
} else if tag == 3 {
pp.PublicKey = val
} else if tag == 11 {
pp.Permission = val[0]
}
}
if err == io.EOF {
result = append(result, pp)
err = nil
}
return result, nil
}