-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscenes.go
66 lines (52 loc) · 1.31 KB
/
scenes.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
package module
import (
"encoding/json"
"fmt"
)
type scene struct {
SceneId string `json:"sceneId"`
SceneName string `json:"sceneName"`
}
// Includes a list of all the scenes you have registered.
type Scenes struct {
SceneList []scene `json:"body"`
}
// Converts the API response body to a list of scenes.
func convertToScenes(data interface{}) (Scenes, error) {
dataSlice, ok := data.([]interface{})
if !ok {
return Scenes{}, fmt.Errorf("data is not a slice")
}
var scenes []scene
for _, s := range dataSlice {
jsonData, error := json.Marshal(s)
if error != nil {
return Scenes{}, error
}
var scene scene
error = json.Unmarshal(jsonData, &scene)
if error != nil {
return Scenes{}, error
}
scenes = append(scenes, scene)
}
return Scenes{SceneList: scenes}, nil
}
// Retrieve all scenes.
func (scenes Scenes) GetScenes() (Scenes, error) {
c := NewSwitchbotAPIClient()
resp, err := c.SendAPIRequest("https://api.switch-bot.com/v1.0/scenes", "GET", nil)
if err != nil {
return Scenes{}, err
}
var r apiResponse
json.Unmarshal(resp, &r)
if r.StatusCode == 190 {
return Scenes{}, fmt.Errorf("system error: Device internal error due to device states not synchronized with server")
}
scenes, error := convertToScenes(r.Body)
if error != nil {
panic(error)
}
return scenes, nil
}