-
Notifications
You must be signed in to change notification settings - Fork 9
/
api.go
93 lines (78 loc) · 2.37 KB
/
api.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
// This file is part of gosmart, a set of libraries to communicate with
// the Samsumg SmartThings API using Go (golang).
//
// http://github.com/marcopaganini/gosmart
// (C) 2016 by Marco Paganini <[email protected]>
package gosmart
import (
"encoding/json"
"io/ioutil"
"net/http"
)
// DeviceList holds the list of devices returned by /devices
type DeviceList struct {
ID string `json:"id"`
Name string `json:"name"`
DisplayName string `json:"displayName"`
}
// DeviceInfo holds information about a specific device.
type DeviceInfo struct {
DeviceList
Attributes map[string]interface{} `json:"attributes"`
}
// DeviceCommand holds one command a device can accept.
type DeviceCommand struct {
Command string `json:"command"`
Params map[string]interface{} `json:"params"`
}
// GetDevices returns the list of devices from smartthings using
// the specified http.client and endpoint URI.
func GetDevices(client *http.Client, endpoint string) ([]DeviceList, error) {
ret := []DeviceList{}
contents, err := issueCommand(client, endpoint, "/devices")
if err != nil {
return nil, err
}
if err := json.Unmarshal(contents, &ret); err != nil {
return nil, err
}
return ret, nil
}
// GetDeviceInfo returns device specific information about a particular device.
func GetDeviceInfo(client *http.Client, endpoint string, id string) (*DeviceInfo, error) {
ret := &DeviceInfo{}
contents, err := issueCommand(client, endpoint, "/devices/"+id)
if err != nil {
return nil, err
}
if err := json.Unmarshal(contents, &ret); err != nil {
return nil, err
}
return ret, nil
}
// GetDeviceCommands returns a slice of commands a specific device accepts.
func GetDeviceCommands(client *http.Client, endpoint string, id string) ([]DeviceCommand, error) {
ret := []DeviceCommand{}
contents, err := issueCommand(client, endpoint, "/devices/"+id+"/commands")
if err != nil {
return nil, err
}
if err := json.Unmarshal(contents, &ret); err != nil {
return nil, err
}
return ret, nil
}
// issueCommand sends a given command to an URI and returns the contents
func issueCommand(client *http.Client, endpoint string, cmd string) ([]byte, error) {
uri := endpoint + cmd
resp, err := client.Get(uri)
if err != nil {
return nil, err
}
contents, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return nil, err
}
return contents, nil
}