/
nest_lib.py
463 lines (338 loc) · 13.2 KB
/
nest_lib.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
#! /usr/bin/python
#################################################
# NEST and Alexa Python API #
#################################################
# Zachary Priddy - 2015 #
# me@zpriddy.com #
# #
# Features: #
# - Read and Write capabilities with #
# Amazon Echo and Nest #
#################################################
#################################################
#################################################
# TO DO:
###############################################################################
# IMPORTS
###############################################################################
import json
import requests
from bson.binary import Binary
import pickle
import pymongo
from pymongo import MongoClient
import echopy_settings as settings
###############################################################################
# DB INIT
###############################################################################
def nestDBInit():
global mongoNEST
global mongoTHERMO
mongoClient = MongoClient()
mongoClient = MongoClient('localhost', 27017)
mongoDB = mongoClient['AlexaNestDB']
mongoNEST = mongoDB['NEST']
mongoTHERMO = mongoDB['THERMO']
###############################################################################
# NEST AUTH
###############################################################################
def nestAuth(alexaId, clientEmail):
global mongoNEST
clientInfo = mongoNEST.find_one({'alexaId':alexaId})
userId = clientInfo['nest_amazonEchoID']
clientInfo['nest_clientEmail'] = clientEmail
auth_uri = settings.nest_auth_uri_1.replace('STATE',alexaId)
mongoNEST.update({'nest_amazonEchoID':userId},clientInfo,True)
return auth_uri
def nestToken(alexaId,authCode):
global mongoNEST
clientInfo = mongoNEST.find_one({'alexaId':alexaId})
clientInfo['nest_authcode'] = authCode
userId = clientInfo['nest_amazonEchoID']
token_uri = settings.nest_auth_uri_2.replace('AUTHORIZATION_CODE',authCode)
usertoken = requests.post(token_uri).json()['access_token']
clientInfo['nest_usertoken'] = usertoken
mongoNEST.update({'nest_amazonEchoID':userId},clientInfo,True)
getStructures(userId)
getThermostats(userId)
clientInfo = mongoNEST.find_one({'alexaId':alexaId})
clientInfo['authenticated'] = True
mongoNEST.update({'nest_amazonEchoID':userId},clientInfo,True)
return True
###############################################################################
# READ DATA FROM NEST
###############################################################################
def getStructures(userId):
global mongoNEST
clientInfo = mongoNEST.find_one({'nest_amazonEchoID':userId})
access_token = clientInfo['nest_usertoken']
structures_uri = "https://developer-api.nest.com/structures?auth=" + access_token
structures_raw = requests.get(structures_uri).json()
clientInfo['structures'] = objectToData(NestStructure(structures_raw))
print dataToObject(clientInfo['structures'])._structures
mongoNEST.update({'nest_amazonEchoID':userId},clientInfo,True)
def getThermostats(userId):
global mongoNEST
global mongoTHERMO
clientInfo = mongoNEST.find_one({'nest_amazonEchoID':userId})
access_token = clientInfo['nest_usertoken']
thermostats_uri = "https://developer-api.nest.com/devices/thermostats?auth=" + access_token
thermostats_raw = requests.get(thermostats_uri).json()
clientInfo['thermostats'] = objectToData(NestThermostats(thermostats_raw))
clientInfo['thermostatIds'] = [a for a in thermostats_raw]
for thermostat in clientInfo['thermostatIds']:
thermoInfo = mongoTHERMO.find_one({'thermoID':thermostat})
thermoInfo = {}
thermoInfo['thermoID'] = thermostat
thermoInfo['nest_amazonEchoID'] = userId
#thermoInfo['nest_name'] = thermostats_raw[thermostat]['name']
#thermoInfo['ambient_temperature_f'] = thermostats_raw[thermostat]['ambient_temperature_f']
#thermoInfo['status'] = thermostats_raw[thermostat]['status']
#thermoInfo['humidity'] = thermostats_raw[thermostat]['humidity']
#thermoInfo['target_temperature_f'] = thermostats_raw[thermostat]['target_temperature_f']
for item in thermostats_raw[thermostat]:
thermoInfo[item] = thermostats_raw[thermostat][item]
print thermoInfo
mongoTHERMO.update({'thermoID':thermostat},thermoInfo,True)
print dataToObject(clientInfo['thermostats'])._thermostats
mongoNEST.update({'nest_amazonEchoID':userId},clientInfo,True)
###############################################################################
# SET ALL THERMOSTATS
###############################################################################
def setTemperatureTargetAll(userId,temp):
global mongoNEST
getThermostats(userId)
clientInfo = mongoNEST.find_one({'nest_amazonEchoID':userId})
if(int(temp) > 100):
return False
access_token = clientInfo['nest_usertoken']
thermostats = dataToObject(clientInfo['thermostats']).getThermostatIds()
thermos_test = dataToObject(clientInfo['thermostats'])
for device in thermos_test._thermostats:
print device
for item in thermos_test._thermostats[device]:
print item
if item != 'id':
for a in thermos_test._thermostats[device][item]:
print a
command = {"target_temperature_f":int(temp)}
commandSucessfull = True
for device in thermostats:
print "Device:" + device
command_uri = 'https://developer-api.nest.com/devices/thermostats/' + device + "?auth=" + access_token
print command_uri
response = requests.put(url=command_uri, data=command, json=command)
print response
print response.text
if response.status_code != 200:
commandSucessfull = False
return commandSucessfull
def setTemperatureTargetOne(userId,temp,thermostatName):
global mongoNEST
getThermostats(userId)
clientInfo = mongoNEST.find_one({'nest_amazonEchoID':userId})
clientThermo = mongoTHERMO.find({'nest_amazonEchoID':userId})
for thermo in clientThermo:
print thermo
print thermo['name']
if thermo['name'].lower() == thermostatName.lower():
print 'Found Thermostat'
print thermo['name']
print thermo['thermoID']
'''
if(int(temp) > 100):
return False
access_token = clientInfo['nest_usertoken']
thermostats = dataToObject(clientInfo['thermostats']).getThermostatIds()
thermos_test = dataToObject(clientInfo['thermostats'])
for device in thermos_test._thermostats:
print device
for item in thermos_test._thermostats[device]:
print item
if item != 'id':
for a in thermos_test._thermostats[device][item]:
print a
command = {"target_temperature_f":int(temp)}
commandSucessfull = True
for device in thermostats:
print "Device:" + device
command_uri = 'https://developer-api.nest.com/devices/thermostats/' + device + "?auth=" + access_token
print command_uri
response = requests.put(url=command_uri, data=command, json=command)
print response
print response.text
if response.status_code != 200:
commandSucessfull = False
'''
commandSucessfull = True
return commandSucessfull
###############################################################################
# Turn down temp by 2 degress
###############################################################################
def setTurnDownTemperatureAll(userId):
print "Turn Down Temp"
global mongoNEST
clientInfo = mongoNEST.find_one({'nest_amazonEchoID':userId})
access_token = clientInfo['nest_usertoken']
commandSucessfull = True
getThermostats(userId)
thermostats = dataToObject(clientInfo['thermostats']).getThermostats()
temps = []
for device in thermostats:
print "Setting Temp for: " + device
currentTemp = thermostats[device]['status']['target_temperature_f']
deviceId = thermostats[device]['id']
temps.append(int(currentTemp)-2)
command = {"target_temperature_f":int(currentTemp)-2}
command_uri = 'https://developer-api.nest.com/devices/thermostats/' + deviceId + "?auth=" + access_token
response = requests.put(url=command_uri, data=command, json=command)
if response.status_code != 200:
commandSucessfull = False
return False
return sum(temps)/len(temps)
###############################################################################
# NEST TEMP UP
###############################################################################
def setTurnUpTemperatureAll(userId):
global mongoNEST
clientInfo = mongoNEST.find_one({'nest_amazonEchoID':userId})
access_token = clientInfo['nest_usertoken']
commandSucessfull = True
getThermostats(userId)
thermostats = dataToObject(clientInfo['thermostats']).getThermostats()
temps = []
for device in thermostats:
print "Setting Temp for: " + device
currentTemp = thermostats[device]['status']['target_temperature_f']
deviceId = thermostats[device]['id']
temps.append(int(currentTemp)+2)
command = {"target_temperature_f":int(currentTemp)+2}
command_uri = 'https://developer-api.nest.com/devices/thermostats/' + deviceId + "?auth=" + access_token
response = requests.put(url=command_uri, data=command, json=command)
if response.status_code != 200:
commandSucessfull = False
return False
return sum(temps)/len(temps)
###############################################################################
# THIS IS WHERE I LEFT OFF
###############################################################################
def setModeAll(userId,mode):
global mongoNEST
clientInfo = mongoNEST.find_one({'nest_amazonEchoID':userId})
access_token = clientInfo['nest_usertoken']
structures = dataToObject(clientInfo['structures']).getStructureIds()
command = {"away":mode}
commandSucessfull = True
for structure in structures:
command_uri = 'https://developer-api.nest.com/structures/' + structure + "?auth=" + access_token
print command_uri
response = requests.put(url=command_uri, data=command, json=command)
print response
if response.status_code != 200:
commandSucessfull = False
return commandSucessfull
'''
def getAvgTemp(userId):
global nestData
currentUser = nestData.getUser(userId)
getThermostats(userId)
thermostats = currentUser.getThermostats()
temps = [a['status']['ambient_temperature_f'] for a in thermostats.values()]
avgTemp = sum(temps)/len(temps)
return avgTemp
def getAvgTargetTemp(userId):
global nestData
currentUser = nestData.getUser(userId)
getThermostats(userId)
thermostats = currentUser.getThermostats()
temps = [a['status']['target_temperature_f'] for a in thermostats.values()]
avgTemp = sum(temps)/len(temps)
return avgTemp
'''
###############################################################################
# CHECK IF USER IS VALID USER
###############################################################################
def isValidNestUser(userId):
global mongoNEST
if(mongoNEST.find_one({'nest_amazonEchoID':userId})):
if(mongoNEST.find_one({'nest_amazonEchoID':userId})['authenticated']):
return True
else:
return False
else:
return False
###############################################################################
# CLASS STRUCTURES FOR DATA STORAGE
###############################################################################
def objectToData(pObject):
return Binary(pickle.dumps(pObject))
def dataToObject(pData):
return pickle.loads(pData)
class NestStructure:
def __init__(self,rawData):
self._structures = {}
for key in rawData.keys():
self._structures[rawData[key]['name']] = {"id":key,"thermostats":rawData[key]['thermostats']}
def getStructureIds(self):
ids = [a['id'] for a in self._structures.values()]
return ids
def getStructures(self):
return self._structures
class NestThermostats:
def __init__(self,rawData):
self._thermostats = {}
for key in rawData.keys():
self._thermostats[rawData[key]['name']] = {"id":key,"status":rawData[key]}
def getThermostatIds(self):
ids = [a['id'] for a in self._thermostats.values()]
return ids
def getThermostats(self):
return self._thermostats
def generateError(errorMessage, functionName):
output_speech = "Nest encountered and error. " + errorMessage + ". Please try again"
output_type = "PlainText"
card_type = "Simple"
card_title = "Nest Error - " + functionName
card_content = "Smart Things encountered and error. " + errorMessage
response = {"outputSpeech": {"type":output_type,"text":output_speech},"card":{"type":card_type,"title":card_title,"content":card_content},'shouldEndSession':False}
print response
return response
###############################################################################
# TO BE DELETED
###############################################################################
class NestUser:
def __init__(self,userId):
self.userId = userId
self.token = None
self.devices = {}
self.structures = {}
self.thermostats = {}
self.authed = False
def setToken(self,token):
self.token = token
self.authed = True
def getToken(self):
return self.token
def getThermostats(self):
return self.thermostats
def getThermostatIds(self):
ids = [a['id'] for a in self.thermostats.values()]
return ids
def getStructureIds(self):
ids = [a['id'] for a in self.structures.values()]
return ids
class NestDataStore:
def __init__(self):
self.nestUsers = {}
def addUser(self, userId, nestUser):
if userId not in self.nestUsers:
self.nestUsers[userId] = nestUser
def getUser(self, userId):
if userId not in self.nestUsers:
self.addUser(userId,NestUser(userId))
return self.nestUsers[userId]
def isValidUser(self,userId):
if userId in self.nestUsers:
return True
else:
return False