This repository has been archived by the owner on Nov 25, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
myq.go
322 lines (261 loc) · 6.7 KB
/
myq.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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
package myq
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httputil"
"os"
)
const (
accountsEndpoint = "https://accounts.myq-cloud.com/api/v6.0/accounts"
// Parameter is account ID
devicesEndpointFmt = "https://devices.myq-cloud.com/api/v5.2/Accounts/%s/Devices"
// Parameters are account ID and device serial number
deviceEndpointFmt = "https://devices.myq-cloud.com/api/v5.2/Accounts/%s/Devices/%s"
// Parameters are account ID, device serial number, and action (open or close)
deviceActionsEndpointFmt = "https://account-devices-gdo.myq-cloud.com/api/v5.2/Accounts/%s/door_openers/%s/%s"
)
const (
ActionClose = "close"
ActionOpen = "open"
StateUnknown = "unknown"
StateOpen = "open"
StateClosed = "closed"
StateStopped = "stopped"
)
var (
// Debug indiciates whether to log HTTP responses to stderr
Debug = false
// ErrNotLoggedIn is returned whenever an operation is run the
// user has not logged in
ErrNotLoggedIn = errors.New("not logged in")
)
// Session represents an authenticated session to the MyQ service.
type Session struct {
Username string
Password string
token string
accounts []*Account
}
type Account struct {
ID string `json:"id"`
Name string `json:"name"`
}
// Device defines a MyQ device
type Device struct {
Account *Account
SerialNumber string
Type string
Name string
DoorState string
}
type errorResponse struct {
StatusCode int `json:"-"`
Message string
Description string
}
func (e *errorResponse) Error() string {
if e.Description != "" {
return e.Message + ": " + e.Description
}
return e.Message
}
func isStatus(err error, code int) bool {
e, ok := err.(*errorResponse)
return ok && e.StatusCode == code
}
func drain(rc io.ReadCloser) {
io.Copy(ioutil.Discard, rc)
rc.Close()
}
func doRequest(client *http.Client, req *http.Request) (*http.Response, error) {
if Debug {
d, _ := httputil.DumpRequestOut(req, true)
fmt.Fprintln(os.Stderr, string(d))
fmt.Fprintln(os.Stderr)
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
if Debug {
d, _ := httputil.DumpResponse(resp, true)
fmt.Fprintln(os.Stderr, string(d))
fmt.Fprintln(os.Stderr)
}
return resp, nil
}
func (s *Session) apiRequest(req *http.Request, target interface{}) error {
if req.Body != nil {
req.Header.Set("Content-Type", "application/json")
}
if s.token != "" {
req.Header.Set("Authorization", "Bearer "+s.token)
}
resp, err := doRequest(http.DefaultClient, req)
if err != nil {
return err
}
defer drain(resp.Body)
switch resp.StatusCode {
case http.StatusOK:
return json.NewDecoder(resp.Body).Decode(target)
case http.StatusNoContent, http.StatusAccepted:
return nil
case http.StatusUnauthorized:
return ErrNotLoggedIn
default:
var errResp errorResponse
if err := json.NewDecoder(resp.Body).Decode(&errResp); err != nil {
errResp.Message = fmt.Sprintf("received HTTP status code %d", resp.StatusCode)
}
errResp.StatusCode = resp.StatusCode
return &errResp
}
}
func (s *Session) apiRequestWithRetry(req *http.Request, target interface{}) error {
if err := s.apiRequest(req, target); err == ErrNotLoggedIn {
if err := s.Login(); err != nil {
return err
}
return s.apiRequest(req, target)
} else {
return err
}
}
// Login establishes an authenticated Session with the MyQ service
func (s *Session) Login() error {
o, err := newOAuth()
if err != nil {
return err
}
u, err := o.authorize()
if err != nil {
return err
}
u, err = o.login(u, s.Username, s.Password)
if err != nil {
return err
}
u, err = o.callback(u)
if err != nil {
return err
}
token, err := o.token(u)
if err != nil {
return err
}
s.token = token
return nil
}
func (s *Session) fillAccounts() error {
if len(s.accounts) > 0 {
return nil
}
req, err := http.NewRequest("GET", accountsEndpoint, nil)
if err != nil {
return err
}
var jsonResponse struct {
Accounts []*Account `json:"accounts"`
}
if err := s.apiRequestWithRetry(req, &jsonResponse); err != nil {
return err
}
s.accounts = jsonResponse.Accounts
return nil
}
// Devices returns the list of MyQ devices
func (s *Session) Devices() ([]Device, error) {
if err := s.fillAccounts(); err != nil {
return nil, err
}
var devices []Device
for _, acct := range s.accounts {
devicesEndpoint := fmt.Sprintf(devicesEndpointFmt, acct.ID)
req, err := http.NewRequest("GET", devicesEndpoint, nil)
if err != nil {
return nil, err
}
type item struct {
SerialNumber string `json:"serial_number"`
DeviceType string `json:"device_type"`
Name string `json:"name"`
State struct {
DoorState string `json:"door_state"`
} `json:"state"`
}
var body struct {
Items []item `json:"items"`
}
if err := s.apiRequestWithRetry(req, &body); err != nil {
return nil, err
}
for i := range body.Items {
devices = append(devices, Device{
Account: acct,
SerialNumber: body.Items[i].SerialNumber,
Type: body.Items[i].DeviceType,
Name: body.Items[i].Name,
DoorState: body.Items[i].State.DoorState,
})
}
}
return devices, nil
}
// DeviceState returns the device state (open, closed, etc.) for the
// provided device serial number
func (s *Session) DeviceState(serialNumber string) (string, error) {
if err := s.fillAccounts(); err != nil {
return "", err
}
for _, acct := range s.accounts {
deviceEndpoint := fmt.Sprintf(deviceEndpointFmt, acct.ID, serialNumber)
req, err := http.NewRequest("GET", deviceEndpoint, nil)
if err != nil {
return "", err
}
var body struct {
SerialNumber string `json:"serial_number"`
DeviceType string `json:"device_type"`
Name string `json:"name"`
State struct {
DoorState string `json:"door_state"`
} `json:"state"`
}
if err := s.apiRequestWithRetry(req, &body); err != nil {
if isStatus(err, http.StatusNotFound) {
continue
}
return "", err
}
return body.State.DoorState, nil
}
return "", fmt.Errorf("device %s not found", serialNumber)
}
// SetDoorState sets the target door state (open or closed) for the
// provided device serial number
func (s *Session) SetDoorState(serialNumber string, action string) error {
if err := s.fillAccounts(); err != nil {
return err
}
for _, acct := range s.accounts {
deviceActionsEndpoint := fmt.Sprintf(deviceActionsEndpointFmt, acct.ID, serialNumber, action)
req, err := http.NewRequest("PUT", deviceActionsEndpoint, nil)
if err != nil {
return err
}
var body struct{}
if err := s.apiRequestWithRetry(req, &body); err != nil {
if isStatus(err, http.StatusNotFound) {
continue
}
return err
}
return nil
}
return fmt.Errorf("device %s not found", serialNumber)
}