-
Notifications
You must be signed in to change notification settings - Fork 0
/
lamp.go
77 lines (57 loc) · 1.38 KB
/
lamp.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
package api
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
// LampState represents the State of a Hue Lamp from the API
type LampState struct {
On bool `json:"on"`
Brightness int `json:"bri"`
Reachable bool `json:"reachable"`
}
// Lamp hold informations of a Hue Lamp from the API
type Lamp struct {
State LampState `json:"state"`
}
// GetLamp request to the API for informations about a Hue Lamp
// It returns a Lamp with the current State
func GetLamp(config Config) (lamp *Lamp, err error) {
id := config.Id
address := config.Address
username := config.Username
url := fmt.Sprintf("http://%s/api/%s/lights/%d", address, username, id)
response, err := http.Get(url)
if err != nil {
return
}
defer response.Body.Close()
lamp = new(Lamp)
err = json.NewDecoder(response.Body).Decode(lamp)
if err != nil {
return
}
return
}
// PutLamp update the State of a Hue Lamp using the API
func PutLamp(config Config, lamp *Lamp) (err error) {
marshal, err := json.Marshal(lamp.State)
if err != nil {
return
}
id := config.Id
address := config.Address
username := config.Username
url := fmt.Sprintf("http://%s/api/%s/lights/%d/state", address, username, id)
request, err := http.NewRequest(http.MethodPut, url, bytes.NewBuffer(marshal))
if err != nil {
return
}
client := &http.Client{}
_, err = client.Do(request)
if err != nil {
return
}
return
}