-
Notifications
You must be signed in to change notification settings - Fork 0
/
myq.py
executable file
·568 lines (439 loc) · 16.9 KB
/
myq.py
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
#!/usr/bin/env python2.7
# Python to interface with MyQ garage doors.
"""
The MIT License (MIT)
Copyright (c) 2015
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import flask
import requests
from requests.auth import HTTPBasicAuth
# from requests.utils import quote
import sys
import time
import json
import logging
# Try to use the C implementation first, falling back to python.
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
from xml.etree import ElementTree
# compatibility with python 3
try:
from ConfigParser import RawConfigParser
except ImportError:
from configparser import RawConfigParser
requests.packages.urllib3.disable_warnings()
LOGGER = logging.getLogger(__name__)
class MyQ(object):
# Do not change this is the URL for the MyQ API
SERVICE = 'https://myqexternal.myqdevice.com'
# Do not change the APPID or CULTURE this is global for the MyQ API
APPID = \
'NWknvuBd7LoFHfXmKNMBcgajXtZEgKUh4V7WNzMidrpUUluDpVYVZx+xT4PCM5Kx'
CULTURE = 'en'
def __init__(self, username, password):
self.doors = {}
self.token = None
self.token_expiry = None
self.username = username
self.password = password
def get_door(self, name):
for id, door in self.get_doors().items():
if door.name == name or door.id == name:
return door
raise MyQException('Door {} not found'.format(name), 3)
def get_token(self):
if self.token_expiry > time.time():
return self.token
data = self.post(
'/api/v4/User/Validate',
{
'username': self.username,
'password': self.password,
},
token='null')
self.token = data['SecurityToken']
self.token_expiry = time.time() + 1800
return self.token
def get_doors(self, refresh=False):
if self.doors and not refresh:
return self.doors
doors = {}
data = self.get('/api/v4/UserDeviceDetails/Get', {'filterOn': 'true'})
for device in data['Devices']:
# Gateway == 1
# Garage Door Opener == 2
# VGDO == 7
# Structure == 10
# Thermostat == 11
if device['MyQDeviceTypeId'] in [2, 7]:
id = device['MyQDeviceId']
name = None
state = None
changed = None
for attr in device['Attributes']:
if attr['AttributeDisplayName'] == 'desc':
name = attr['Value']
elif attr['AttributeDisplayName'] == 'doorstate':
changed = time.localtime(
float(attr['UpdatedTime']) / 1000.0)
state = int(attr['Value'])
if id in self.doors:
doors[id] = self.doors[id]
doors[id].update_name(name)
doors[id].update_state(state, changed)
else:
doors[id] = Door(self, id, name, state, changed)
self.doors = doors
return self.doors
def put(self, url, payload):
put_url = self.SERVICE + url
headers = {
'Content-Type': 'application/json',
'User-Agent': 'Chamberlain/3.61.1 (iPhone; iOS 10.0.1; Scale/2.00)',
'ApiVersion': '4.1',
'BrandId': '2',
'Culture': self.CULTURE,
'MyQApplicationId': self.APPID,
'SecurityToken': self.get_token(),
}
if LOGGER.isEnabledFor(logging.DEBUG):
LOGGER.debug('PUT ' + url + ' Params: ' + self.logdata(payload) + ' Headers: ' + self.logdata(headers))
try:
r = requests.put(put_url, data=json.dumps(payload), headers=headers)
except requests.exceptions.RequestException as err:
raise MyQException('Caught Exception: ' + err, 2)
data = r.json()
LOGGER.debug('PUT ' + url + ' Response: ' + self.logdata(data))
if data['ReturnCode'] != '0':
raise MyQException(data['ErrorMessage'], 1)
return data
def get(self, url, params={}):
get_url = self.SERVICE + url
headers = {
'Content-Type': 'application/json',
'User-Agent': 'Chamberlain/3.61.1 (iPhone; iOS 10.0.1; Scale/2.00)',
'ApiVersion': '4.1',
'BrandId': '2',
'Culture': self.CULTURE,
'MyQApplicationId': self.APPID,
'SecurityToken': self.get_token(),
}
if LOGGER.isEnabledFor(logging.DEBUG):
LOGGER.debug('GET ' + url + ' Params: ' + self.logdata(params) + ' Headers: ' + self.logdata(headers))
try:
r = requests.get(get_url, params=params, headers=headers)
except requests.exceptions.RequestException as err:
raise MyQException('Caught Exception: ' + err, 2)
try:
data = r.json()
except Exception as err:
LOGGER.error('GET ' + url + ' Response: ' + r.text)
raise MyQException('Error parsing JSON', 2)
LOGGER.debug('GET ' + url + ' Response: ' + self.logdata(data))
if data['ReturnCode'] != '0':
raise MyQException(data['ErrorMessage'], 1)
return data
def post(self, url, params={}, token=None):
if token is None:
token = self.get_token()
post_url = self.SERVICE + url
headers = {
'Content-Type': 'application/json',
'User-Agent': 'Chamberlain/3.61.1 (iPhone; iOS 10.0.1; Scale/2.00)',
'ApiVersion': '4.1',
'BrandId': '2',
'Culture': self.CULTURE,
'MyQApplicationId': self.APPID,
}
if token != 'null':
headers['SecurityToken'] = token
if LOGGER.isEnabledFor(logging.DEBUG):
LOGGER.debug('POST ' + url + ' Params: ' + self.logdata(params) + ' Headers: ' + self.logdata(headers))
try:
r = requests.post(post_url, data=json.dumps(params), headers=headers)
except requests.exceptions.RequestException as err:
raise MyQException('Caught Exception: ' + err, 2)
try:
data = r.json()
except Exception as err:
LOGGER.error('POST ' + url + ' Response: ' + r.text)
raise MyQException('Error parsing JSON', 2)
LOGGER.debug('POST ' + url + ' Response: ' + self.logdata(data))
if data['ReturnCode'] != '0':
raise MyQException(data['ErrorMessage'], 1)
return data
def logdata(self, params):
protect = ['password', 'securityToken', 'SecurityToken']
return json.dumps({
x: (y if x not in protect else '***')
for x, y in params.items()
}, sort_keys=True, indent=2)
class Door(object):
# State value from API returns an integer, the index corresponds to the
# below list. Zero is not used.
STATES = [
'',
'Open',
'Closed',
'Stopped',
'Opening',
'Closing',
]
def __init__(self, myq, id, name=None, state=None, changed=None):
self.myq = myq
self.id = id
self.update_name(name)
self.update_state(state, changed)
def update_name(self, name=None):
if name is None:
data = self.myq.get(
'/api/v4/DeviceAttribute/GetDeviceAttribute',
{
'MyQDeviceId': self.id,
'AttributeName': 'desc',
})
name = data['AttributeValue']
self.name = name if name else self.id
def update_state(self, state=None, changed=None):
if state is None or changed is None:
data = self.myq.get(
'/api/v4/DeviceAttribute/GetDeviceAttribute',
{
'MyQDeviceId': self.id,
'AttributeName': 'doorstate',
})
state = int(data['AttributeValue'])
changed = time.localtime(float(data['UpdatedTime']) / 1000.0)
if type(state) == int:
try:
state = self.STATES[state]
except IndexError:
LOGGER.error('Invalid door state "{}" for door {}'.format(state, self.name))
state = 'Unknown'
self.state = state
self.changed = changed
self.updated = time.localtime()
@property
def format_changed(self):
return time.strftime(
"%a %d %b %Y %H:%M:%S", self.changed)
@property
def format_updated(self):
return time.strftime(
"%a %d %b %Y %H:%M:%S", self.updated)
def set_state(self, desired_state):
if desired_state.lower() == 'close':
if self.state in ['Closed', 'Closing']:
raise MyQException(
'{} already {}.'.format(self.name, self.state), 6)
desired_state = 0
elif desired_state.lower() == 'open':
if self.state in ['Open', 'Opening']:
raise MyQException(
'{} already {}.'.format(self.name, self.state), 6)
desired_state = 1
else:
raise MyQException('Invalid state specified', 7)
self.myq.put(
'/api/v4/DeviceAttribute/PutDeviceAttribute',
{
'AttributeName': 'desireddoorstate',
'MyQDeviceId': self.id,
'AttributeValue': desired_state,
})
self.update_state()
return True
class MyQException(Exception):
def __init__(self, msg, code=1):
LOGGER.error(msg)
self.code = code
super(MyQException, self).__init__(msg)
class ISY(object):
def __init__(self, host, port, username, password, var_prefix,
enabled=True):
self.host = host
self.port = port
self.username = username
self.password = password
self.var_prefix = var_prefix
self.enabled = enabled
self.var_ids = {}
def update_door(self, door):
if not self.enabled:
return
id, varname = self.get_var_id(door.name)
if door.state == "Open":
value = 1
else:
value = 0
self.set_var_state(id, varname, value)
def set_var_state(self, id, varname, value):
init, val = self.get_var_state(id)
if value == int(val):
LOGGER.debug('%s is already set to %s', varname, val)
return True
r = self.call('/rest/vars/set/2/' + id + '/' + str(value))
if int(r.status_code) == 404:
LOGGER.error('%s not found on ISY. Response was 404', id)
return False
if int(r.status_code) != 200:
LOGGER.error(
'Status change failed, response from ISY: %s - %s',
r.status_code, r.text)
return False
LOGGER.info('%s changed successfully to %s', varname, value)
return True
def get_var_state(self, id):
r = self.call('/rest/vars/get/2/' + id)
tree = ElementTree.fromstring(r.text)
init = tree.find('init').text
value = tree.find('val').text
LOGGER.info('Get_Var_State: init: %s - val: %s', init, value)
return init, value
def get_var_id(self, name):
varname = str(self.var_prefix + name.replace(" ", "_"))
if varname in self.var_ids:
return self.var_ids[varname], varname
LOGGER.info('Searching ISY Definitions for %s', varname)
r = self.call('/rest/vars/definitions/2')
tree = ElementTree.fromstring(r.text)
var_ids = {}
for e in tree.findall('e'):
var_ids[e.get('name')] = e.get('id')
self.var_ids = var_ids
if varname in self.var_ids:
LOGGER.info('State variable: %s found with ID: %s', varname, id)
return self.var_ids[varname], varname
raise Exception(
"State variable: {} not found in ISY variable list".format(
varname))
def call(self, url):
try:
r = requests.get(
'http://' + self.host + ':' + self.port + url,
auth=HTTPBasicAuth(self.username, self.password))
except requests.exceptions.RequestException as err:
raise Exception('Error calling ISY {}: {}'.format(url, err))
return r
def main():
LOGGER.setLevel(logging.INFO)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
LOGGER.addHandler(handler)
LOGGER.info('Starting')
try:
config = RawConfigParser()
config.read('myq.cfg')
if (config.has_option('MyQ', 'debug')
and config.getboolean('MyQ', 'debug')):
LOGGER.setLevel(logging.DEBUG)
myq = MyQ(
config.get('MyQ', 'username'),
config.get('MyQ', 'password'),
)
isy = ISY(
config.get('ISY', 'host'),
config.get('ISY', 'port'),
config.get('ISY', 'username'),
config.get('ISY', 'password'),
config.get('ISY', 'var_prefix'),
config.getboolean('ISY', 'enabled'),
)
except Exception as e:
LOGGER.error(e)
return 1
app = flask.Flask(__name__)
def make_response(ret, http_status=200):
response = flask.make_response(json.dumps(ret), http_status)
response.mimetype = 'application/json'
return response
def make_error(e):
return make_response(
{'error': str(e), 'code': getattr(e, 'code', None)}, 500)
@app.route('/doors/')
def doors_status():
try:
ret = []
for id, door in myq.get_doors(True).items():
LOGGER.info(
'%s is %s. Last changed at %s',
door.name, door.state, door.format_changed)
isy.update_door(door)
ret.append({
'id': door.id,
'name': door.name,
'state': door.state,
'changed': door.format_changed,
'updated': door.format_updated,
})
return make_response(ret)
except Exception as e:
return make_error(e)
@app.route('/doors/<doorname>')
def door_status(doorname):
try:
door = myq.get_door(doorname.replace('+', ' '))
door.update_state()
LOGGER.info(
'%s is %s. Last changed at %s',
door.name, door.state, door.format_changed)
isy.update_door(door)
ret = {
'id': door.id,
'name': door.name,
'state': door.state,
'changed': door.format_changed,
'updated': door.format_updated,
}
return make_response(ret)
except Exception as e:
return make_error(e)
@app.route('/doors/<doorname>/<state>')
def door_handler(doorname, state):
try:
door = myq.get_door(doorname.replace('+', ' '))
door.update_state()
isy.update_door(door)
LOGGER.info(
'%s is %s. Last changed at %s',
door.name, door.state, door.format_changed)
if state == 'status':
ret = door.state
else:
door.set_state(state)
ret = 'OK'
response = flask.make_response(ret)
response.mimetype = 'text/plain'
return response
except Exception as e:
return make_error(e)
LOGGER.info('Getting Doors')
try:
myq.get_doors()
except MyQException as e:
LOGGER.error(e)
return 1
app.run(
host=config.get('Flask', 'host'),
port=config.getint('Flask', 'port'),
debug=config.getboolean('Flask', 'debug'),
)
return 0
if __name__ == '__main__':
sys.exit(main())