forked from therivenman/pygop
-
Notifications
You must be signed in to change notification settings - Fork 1
/
pygop.py
417 lines (322 loc) · 14.1 KB
/
pygop.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
import re
import shelve
import socket
import sys
import ssl
import os
import uuid
import urllib, urllib2
import xml.etree.ElementTree as ET
# disable ssl cert validation for python versions >= 2.7.9
if hasattr(ssl, '_create_unverified_context'):
ssl._create_default_https_context = ssl._create_unverified_context
__version__ = "0.0.2"
cache_filename = "pygop.cache"
cache_location = os.path.join(os.path.dirname(os.path.realpath(__file__)), cache_filename)
GOPReturnCodes = { '200': 'Command Succesful',
'401': 'Invalid Token',
'404': 'Invalid Command',
'500': 'Incorrect Did/Rid'}
class pygop(object):
def __init__(self):
self.gatewayIP = self.__discoverGateway()
if not self.gatewayIP:
sys.exit("Couldn't detect gateway on the network.")
self.token = self.__login()
if not self.token:
sys.exit("Couldn't login to the gateway.\nHas the sync button on the gateway been activated?")
self.carousel = self.__scanRooms()
if not self.carousel:
sys.exit("Couldn't enumerate rooms or devices")
# API Functions
def printHouseInfo(self):
'Gets data for all rooms and prints it to the screen'
self.carousel = self.__scanRooms(invalidate=True)
if not self.carousel:
print "Couldn't enumerate rooms or devices"
return False
for room in self.carousel["rooms"]:
print 'Room: %s' % room["name"]
print ' Rid: %s' % room["rid"]
print ""
for device in room["devices"]:
if device["type"] == "LED":
print " Type: LED Bulb"
elif device["type"] == "CFL":
print " Type: CFL Bulb"
elif device["type"] == "Light Fixture":
print " Type: Light Fixture"
else:
print " Type: Unknown"
print " Name: %s" % device["name"]
print " Did: %s" % device["did"]
print " State: %s" % ("On" if device["state"] == "1" else "Off")
if (device["offline"]):
print " (Offline)"
if (device["level"]):
print " Level: %s" % device["level"]
print ""
# Set Level APIs
def setBulbLevelByDid(self, did, onoff, level=0):
'Sets the bulb on/off or dim level. [did, (1 - on, 0 off), dim level (1-100)]\n' \
'Note: To set the bulb on or off, the level parameter must be 0.'
command = 'DeviceSendCommand'
if (level == 0):
data = '<gip><version>1</version><token>%s</token><did>%d</did><value>%d</value></gip>' % (self.token, did, onoff)
else:
data = '<gip><version>1</version><token>%s</token><did>%d</did><type>level</type><value>%d</value></gip>' % (self.token, did, level)
result = self.__sendGopCommand(command, data)
if(result is False):
print 'Failed to setBulbLevelByDid'
return False
return True
def setBulbLevelByName(self, name, onoff, level=0):
'Sets the bulb on/off or dim level. [name, (1 - on, 0 off), dim level (1-100)]\n' \
'Note: To set the bulb on or off, the level parameter must be 0.'
# resolve name to did first
bulbDid = self.__nameToDid(name)
if (bulbDid is not None):
result = self.setBulbLevelByDid(bulbDid, onoff, level)
if(result is False):
print 'Failed to setBulbLevelByName'
return False
else:
print 'Device name does not exist'
return False
return True
def setRoomLevelByRid(self, rid, onoff, level=0):
'Sets the room on/off or dim level. [rid, (1 - on, 0 off), dim level (1-100)]\n' \
'Note: To set the room on or off, the level parameter must be 0.'
command = 'RoomSendCommand'
if (level == 0):
data = '<gip><version>1</version><token>%s</token><rid>%s</rid><value>%d</value></gip>' % (self.token, rid, onoff)
else:
data = '<gip><version>1</version><token>%s</token><rid>%s</rid><type>level</type><value>%d</value></gip>' % (self.token, rid, level)
result = self.__sendGopCommand(command, data)
if(result is False):
print 'Failed to setRoomLevelByRid'
return False
return True
def setRoomLevelByName(self, name, onoff, level=0):
'Sets the room on/off or dim level. [name, (1 - on, 0 off), dim level (1-100)]\n' \
'Note: To set the room on or off, the level parameter must be 0.'
# resolve name to did first
roomRid = self.__nameToRid(name)
if (roomRid is not None):
result = self.setRoomLevelByRid(roomRid, onoff, level)
if(result is False):
print 'Failed to setRoomLevelByName'
return False
else:
print 'Room name does not exist'
return False
return True
# Get Level APIs
def getBulbLevelByDid(self, did):
'Gets state and level of the bulb identified by did'
self.carousel = self.__scanRooms(invalidate=True)
if not self.carousel:
print "Couldn't enumerate rooms or devices"
return False
for room in self.carousel["rooms"]:
for device in room["devices"]:
if device["did"] == str(did):
return ((True if device["state"] == "1" else False),
device["level"])
def getBulbLevelByName(self, name, onoff, level=0):
'Gets state and level of the bulb identified by name'
self.carousel = self.__scanRooms(invalidate=True)
if not self.carousel:
print "Couldn't enumerate rooms or devices"
return False
for room in self.carousel["rooms"]:
for device in room["devices"]:
if device["name"] == name:
return ((True if device["state"] == "1" else False),
device["level"])
# Identify APIs
def identifyBulbByDid(self, did):
'Identifies a bulb by dimming it. [did]'
result = self.__identify(self.setBulbLevelByDid, did)
if(result is False):
print 'Failed to identifyBulbByDid'
return False
return True
def identifyBulbByName(self, name):
'Identifies a bulb by dimming it. [name]'
result = self.__identify(self.setBulbLevelByName, name)
if(result is False):
print 'Failed to identifyBulbByName'
return False
return True
def identifyRoomByRid(self, rid):
'Identifies a room by dimming the bulbs in it. [rid]'
result = self.__identify(self.setRoomLevelByRid, rid)
if(result is False):
print 'Failed to identifyRoomByRid'
return False
return True
def identifyRoomByName(self, name):
'Identifies a room by dimming the bulbs in it. [name]'
result = self.__identify(self.setRoomLevelByName, name)
if(result is False):
print 'Failed to identifyRoomByName'
return False
return True
# private helper functions
def __identify(self, action, identifier):
# turn the target on
result = action(identifier, 1)
if(result is False):
print 'Failed to identify %s' % identifier
return False
# dim between 50 and 70 percent a few times
for level in range(1,7):
result = action(identifier, 1, 50 + level%2 * 20)
if(result is False):
print 'Failed to identify %s' % identifier
return False
return True
def __sendGopCommand(self, command, data):
url = 'https://%s/gwr/gop.php' % self.gatewayIP
headers = { 'Host' : self.gatewayIP,
'Content-Type': 'application/x-www-form-urlencoded'}
values = {'cmd' : command,
'data' : data,
'fmt' : 'xml'}
data = urllib.urlencode(values)
req = urllib2.Request(url, data, headers)
# handle any connection errors
try:
response = urllib2.urlopen(req)
except urllib2.URLError as e:
if hasattr(e, 'reason'):
print 'Failed to reach the lighting server. Check to make ' \
'sure you\'re connected to the same network as the gateway ' \
'and it\'s online.'
print 'Reason: ', e.reason
elif hasattr(e, 'code'):
print 'The server couldn\'t fulfill the request.'
print 'Error code: ', e.code
return False
else:
result = response.read()
# Print GOP Error if there is one
rc = self.__getXMLTagValue(result, 'rc')
if (rc is not None):
if (rc != '200'):
print rc + ': ' + GOPReturnCodes[rc]
return False
return result
def __scanRooms(self, invalidate=False):
try:
carousel = self.__readCache("carousel", invalidate)
return carousel
except:
command = 'RoomGetCarousel'
data = '<gip><version>1</version><token>' + self.token + '</token><fields>name,power,product,class,image,imageurl,control</fields></gip>'
result = self.__sendGopCommand(command, data)
if result:
carousel = { "rooms" : [] }
tree = ET.fromstring(result)
for room in tree.findall('room'):
roomid = room.find('rid').text
roomname = room.find('name').text
current_room = { "name" : roomname, "rid" : roomid, "devices" : [] }
for device in room.findall('device'):
deviceid = device.find('did').text
devicename = device.find('name').text
devicetype = device.find('prodtype').text
devicestate = device.find('state').text
deviceoffline = True if device.find('offline') is not None else False
devicelevel = None if device.find('level') is None else device.find('level').text
current_room["devices"].append({ "name" : devicename,
"did" : deviceid ,
"type" : devicetype,
"state" : devicestate,
"offline" : deviceoffline,
"level" : devicelevel })
carousel["rooms"].append(current_room)
self.__writeCache("carousel", carousel)
return carousel
return None
def __nameToDid(self, name):
for room in self.carousel["rooms"]:
for device in room["devices"]:
if device["name"].lower() == name.lower():
return device["did"]
return None
def __nameToRid(self, name):
for room in self.carousel["rooms"]:
if room["name"].lower() == name.lower():
return room["rid"]
return None
def __getXMLTagValue(self, xml, tag):
tree = ET.fromstring(xml)
value = tree.find(tag)
if (value is not None):
return value.text
else:
return None
def __discoverGateway(self, invalidate=False):
try:
gatewayIP = self.__readCache("gatewayIP", invalidate)
return gatewayIP
except:
SSDP_ADDR = "239.255.255.250";
SSDP_PORT = 1900;
SSDP_MX = 1;
SSDP_ST = "urn:greenwavereality-com:service:gop:1";
ssdpRequest = "M-SEARCH * HTTP/1.1\r\n" + \
"HOST: %s:%d\r\n" % (SSDP_ADDR, SSDP_PORT) + \
"MAN: \"ssdp:discover\"\r\n" + \
"MX: %d\r\n" % (SSDP_MX, ) + \
"ST: %s\r\n" % (SSDP_ST, ) + "\r\n";
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.settimeout(2) # 2 second timeout
try:
sock.sendto(ssdpRequest, (SSDP_ADDR, SSDP_PORT))
result = sock.recv(1000)
sock.close()
location = re.findall(r"(LOCATION): https://(?P<host>.*?)\r\n", result)
if len(location) and len(location[0]):
gatewayIP = location[0][1]
self.__writeCache("gatewayIP", gatewayIP)
return gatewayIP
except:
return None
def __login(self):
try:
token = self.__readCache("token")
return token
except:
loginuuid = uuid.uuid4()
command = 'GWRLogin'
data = '<gip><version>1</version><email>%s</email><password>%s</password></gip>' % (loginuuid, loginuuid)
result = self.__sendGopCommand(command, data)
if result:
token = self.__getXMLTagValue(result, 'token')
self.__writeCache("token", token)
return token
return None
def __readCache(self, key, invalidate=False):
if invalidate:
# This is based on the assumption that we will
# write to the cache if it does not contain
# the key we were looking for. The exception
# will be handled in the calling function
# which will query the gateway for data
# and then write it to the cache afterwards
raise KeyError
try:
s = shelve.open(cache_location)
value = s[key]
finally:
s.close()
return value
def __writeCache(self, key, value):
try:
s = shelve.open(cache_location, writeback=True)
s[key] = value
finally:
s.close()