-
Notifications
You must be signed in to change notification settings - Fork 36
/
huego.go
288 lines (223 loc) · 6.66 KB
/
huego.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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
// Package huego provides an extensive, easy to use interface to the Philips Hue bridge.
package huego
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
)
const (
applicationJSON = "application/json"
contentType = "Content-Type"
)
// APIResponse holds the response data returned form the bridge after a request has been made.
type APIResponse struct {
Success map[string]interface{} `json:"success,omitempty"`
Error *APIError `json:"error,omitempty"`
}
// APIError defines the error response object returned from the bridge after an invalid API request.
type APIError struct {
Type int
Address string
Description string
}
// Response is a wrapper struct of the success response returned from the bridge after a successful API call.
type Response struct {
Success map[string]interface{}
}
// UnmarshalJSON makes sure that types are correct when unmarshalling. Implements package encoding/json
func (a *APIError) UnmarshalJSON(data []byte) error {
var aux map[string]interface{}
err := json.Unmarshal(data, &aux)
if err != nil {
return err
}
a.Type = int(aux["type"].(float64))
a.Address = aux["address"].(string)
a.Description = aux["description"].(string)
return nil
}
// Error returns an error string
func (a *APIError) Error() string {
return fmt.Sprintf("ERROR %d [%s]: \"%s\"", a.Type, a.Address, a.Description)
}
func handleResponse(a []*APIResponse) (*Response, error) {
success := map[string]interface{}{}
for _, r := range a {
if r.Success != nil {
for k, v := range r.Success {
success[k] = v
}
}
if r.Error != nil {
return nil, r.Error
}
}
resp := &Response{Success: success}
return resp, nil
}
// unmarshal will try to unmarshal data into APIResponse so that we can
// return the actual error returned by the bridge http API as an error struct.
func unmarshal(data []byte, v interface{}) error {
err := json.Unmarshal(data, &v)
if err != nil {
var a []*APIResponse
err = json.Unmarshal(data, &a)
if err != nil {
return err
}
_, err = handleResponse(a)
if err != nil {
return err
}
}
return nil
}
func get(ctx context.Context, url string, client *http.Client) ([]byte, error) {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
res, err := client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
return body, nil
}
func put(ctx context.Context, url string, data []byte, client *http.Client) ([]byte, error) {
body := strings.NewReader(string(data))
req, err := http.NewRequest(http.MethodPut, url, body)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
req.Header.Set(contentType, applicationJSON)
res, err := client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
result, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
return result, nil
}
func post(ctx context.Context, url string, data []byte, client *http.Client) ([]byte, error) {
body := strings.NewReader(string(data))
req, err := http.NewRequest(http.MethodPost, url, body)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
req.Header.Set(contentType, applicationJSON)
res, err := client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
result, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
return result, nil
}
func del(ctx context.Context, url string, client *http.Client) ([]byte, error) {
req, err := http.NewRequest(http.MethodDelete, url, nil)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
req.Header.Set(contentType, applicationJSON)
res, err := client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
result, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
return result, nil
}
// DiscoverAll performs a discovery on the network looking for bridges using https://www.meethue.com/api/nupnp service.
// DiscoverAll returns a list of Bridge objects.
func DiscoverAll() ([]Bridge, error) {
return DiscoverAllContext(context.Background())
}
// DiscoverAllContext performs a discovery on the network looking for bridges using https://www.meethue.com/api/nupnp service.
// DiscoverAllContext returns a list of Bridge objects.
func DiscoverAllContext(ctx context.Context) ([]Bridge, error) {
req, err := http.NewRequest(http.MethodGet, "https://discovery.meethue.com", nil)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
client := http.DefaultClient
res, err := client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
d, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
var bridges []Bridge
err = json.Unmarshal(d, &bridges)
if err != nil {
return nil, err
}
return bridges, nil
}
// Discover performs a discovery on the network looking for bridges using https://www.meethue.com/api/nupnp service.
// Discover uses DiscoverAll() but only returns the first instance in the array of bridges if any.
func Discover() (*Bridge, error) {
return DiscoverContext(context.Background())
}
// DiscoverContext performs a discovery on the network looking for bridges using https://www.meethue.com/api/nupnp service.
// DiscoverContext uses DiscoverAllContext() but only returns the first instance in the array of bridges if any.
func DiscoverContext(ctx context.Context) (*Bridge, error) {
b := &Bridge{}
bridges, err := DiscoverAllContext(ctx)
if err != nil {
return nil, err
}
if len(bridges) > 0 {
b = &bridges[0]
}
return b, nil
}
// New instantiates and returns a new Bridge. New accepts hostname/ip address to the bridge (h) as well as an username (u).
// h may or may not be prefixed with http(s)://. For example http://192.168.1.20/ or 192.168.1.20.
// u is a username known to the bridge. Use Discover() and CreateUser() to create a user.
func New(h, u string) *Bridge {
return &Bridge{
Host: h,
User: u,
ID: "",
client: http.DefaultClient,
}
}
// NewWithClient instantiates and returns a new Bridge with a custom HTTP client.
// NewWithClient accepts the same parameters as New, but with an additional acceptance of an http.Client.
//
// h may or may not be prefixed with http(s)://. For example http://192.168.1.20/ or 192.168.1.20.
// u is a username known to the bridge. Use Discover() and CreateUser() to create a user.
// Difference between New and NewWithClient being the ability to implement your own http.RoundTripper for proxying.
func NewWithClient(h, u string, client *http.Client) *Bridge {
return &Bridge{
Host: h,
User: u,
ID: "",
client: client,
}
}