-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapi.go
90 lines (80 loc) · 2.05 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
package kasa
import "fmt"
const (
cloudURL = "https://wap.tplinkcloud.com"
methodLogin = "login"
methodGetDevices = "getDeviceList"
methodPassthrough = "passthrough"
appType = "Kasa_Android"
)
// API Public interface to get information, devices and interact with them
type API interface {
GetDevicesInfo() ([]DeviceInfo, error)
GetHS100(alias string) (HS100, error)
GetHS105(alias string) (HS105, error)
GetHS110(alias string) (HS110, error)
}
type api struct {
Auth auth
DevicesInfo []listedDeviceInfo
}
// Connect Create an authenticated API
func Connect(username, password string) (API, error) {
a := api{
Auth: auth{
Username: username,
Password: password,
URL: cloudURL,
},
}
err := a.Auth.generateToken()
if err != nil {
return a, err
}
return a, nil
}
// GetHS100 to get HS100 device data
func (a api) GetHS100(alias string) (HS100, error) {
var hs100 HS100
devices, err := a.GetDevicesInfo()
if err != nil {
return hs100, err
}
for _, device := range devices {
if device.Alias == alias {
hs100 = smartPlug{Alias: alias, Auth: a.Auth, DeviceID: device.DeviceID}
return hs100, nil
}
}
return smartPlug{}, fmt.Errorf("there is no device with alias %s", alias)
}
// GetHS105 to get HS105 device data
func (a api) GetHS105(alias string) (HS105, error) {
return a.GetHS100(alias)
}
// GetHS110 to get HS110 device data
func (a api) GetHS110(alias string) (HS110, error) {
return a.GetHS100(alias)
}
func (a api) GetDevicesInfo() ([]DeviceInfo, error) {
res, err := a.getAuthRequest(requestBody{Method: methodGetDevices}).execute()
if err != nil {
return nil, err
}
deviceInfoList := make([]DeviceInfo, 0)
for _, device := range res.DeviceInfoList {
var deviceInfo DeviceInfo
deviceInfo.fromListedDeviceInfo(device)
deviceInfoList = append(deviceInfoList, deviceInfo)
}
return deviceInfoList, nil
}
func (a api) getAuthRequest(reqBody requestBody) authRequest {
return authRequest{
Auth: a.Auth,
Request: request{
URL: cloudURL,
RequestBody: reqBody,
},
}
}