forked from savaki/go.wemo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
device.go
206 lines (176 loc) · 5.28 KB
/
device.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
// Copyright 2014 Matt Ho
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package wemo
import (
"encoding/xml"
"errors"
"fmt"
"github.com/savaki/httpctx"
"golang.org/x/net/context"
"io/ioutil"
"log"
"net/http"
"regexp"
"strconv"
"strings"
)
type Device struct {
Host string
Logger func(string, ...interface{}) (int, error)
}
type DeviceInfo struct {
Device *Device `json:"-"`
DeviceType string `xml:"deviceType" json:"device-type"`
FriendlyName string `xml:"friendlyName" json:"friendly-name"`
MacAddress string `xml:"macAddress" json:"mac-address"`
FirmwareVersion string `xml:"firmwareVersion" json:"firmware-version"`
SerialNumber string `xml:"serialNumber" json:"serial-number"`
}
type DeviceInfos []*DeviceInfo
func (d DeviceInfos) Len() int { return len(d) }
func (d DeviceInfos) Swap(i, j int) { d[i], d[j] = d[j], d[i] }
func (d DeviceInfos) Less(i, j int) bool { return d[i].FriendlyName < d[j].FriendlyName }
func (d *Device) printf(format string, args ...interface{}) {
if d.Logger != nil {
d.Logger(format, args...)
}
}
func unmarshalDeviceInfo(data []byte) (*DeviceInfo, error) {
resp := struct {
DeviceInfo DeviceInfo `xml:"device"`
}{}
err := xml.Unmarshal(data, &resp)
if err != nil {
return nil, err
}
return &resp.DeviceInfo, nil
}
func (d *Device) FetchDeviceInfo(ctx context.Context) (*DeviceInfo, error) {
var data []byte
uri := fmt.Sprintf("http://%s/setup.xml", d.Host)
err := httpctx.NewClient().Get(ctx, uri, nil, &data)
if err != nil {
return nil, err
}
deviceInfo, err := unmarshalDeviceInfo(data)
if err != nil {
return nil, err
}
deviceInfo.Device = d
return deviceInfo, nil
}
func (d *Device) GetBinaryState() int {
message := newGetBinaryStateMessage()
response, err := post(d.Host, "basicevent", "GetBinaryState", message)
if err != nil {
d.printf("unable to fetch BinaryState => %s\n", err)
return -1
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
d.printf("GetBinaryState returned status code => %d\n", response.StatusCode)
return -1
}
data, err := ioutil.ReadAll(response.Body)
if err != nil {
d.printf("unable to read data => %s\n", err)
return -1
}
re := regexp.MustCompile(`.*<BinaryState>(\d+)</BinaryState>.*`)
matches := re.FindStringSubmatch(string(data))
if len(matches) != 2 {
d.printf("unable to find BinaryState response in message => %s\n", string(data))
return -1
}
result, _ := strconv.Atoi(matches[1])
return result
}
func (d *Device) Off() {
d.changeState(false)
}
func (d *Device) On() {
d.changeState(true)
}
func (d *Device) Toggle() {
if binaryState := d.GetBinaryState(); binaryState == 0 {
d.On()
} else {
d.Off()
}
}
func (d *Device) changeState(newState bool) error {
fmt.Printf("changeState(%v)\n", newState)
message := newSetBinaryStateMessage(newState)
response, err := post(d.Host, "basicevent", "SetBinaryState", message)
if err != nil {
log.Println("unable to SetBinaryState")
return err
}
defer response.Body.Close()
if response.StatusCode != 200 {
data, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Println("couldn't read body from message => " + err.Error())
return err
}
content := string(data)
gripe := fmt.Sprintf("changeState(%v) => %s", newState, content)
log.Println(gripe)
return errors.New(gripe)
}
return nil
}
type InsightParams struct {
Power int // mW
}
func (d *Device) GetInsightParams() *InsightParams {
message := newGetInsightParamsMessage()
response, err := post(d.Host, "insight", "GetInsightParams", message)
if err != nil {
d.printf("unable to fetch Power => %s\n", err)
return nil
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
d.printf("GetInsightParams returned status code => %d\n", response.StatusCode)
return nil
}
data, err := ioutil.ReadAll(response.Body)
if err != nil {
d.printf("unable to read data => %s\n", err)
return nil
}
// <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body>
// <u:GetInsightParamsResponse xmlns:u="urn:Belkin:service:metainfo:1">
// <InsightParams>8|1471416661|8|3244|3182|15377|19|7300|1011115|1011115.000000|8000</InsightParams>
// </u:GetInsightParamsResponse>
re := regexp.MustCompile(`.*<InsightParams>(.+)</InsightParams>.*`)
matches := re.FindStringSubmatch(string(data))
if len(matches) != 2 {
d.printf("unable to find GetInsightParams response in message => %s\n", string(data))
return nil
}
split := strings.Split(matches[1], "|")
if len(split) < 7 {
d.printf("unable to parse InsightParams response => %s\n", string(data))
return nil
}
power, err := strconv.Atoi(split[7])
if err != nil {
d.printf("failed to parse power: %v", err)
}
return &InsightParams{
Power: power,
}
}