forked from zpriddy/ZP_EchoSmartThingsPy
/
echopy_smartthings.py
279 lines (195 loc) · 9.26 KB
/
echopy_smartthings.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
import os
import echopy_app
import echopy_doc
import smartthings_doc as st_doc
import smartthings_lib as st
import smartthings_settings as settings
import alexa_utils as utils
import random
import logger
import string
from flask import Flask, render_template, Response, send_from_directory, request, current_app, redirect, jsonify, json
import pymongo
from pymongo import MongoClient
appVersion = 1.0
debug = settings.debug
def get_st_user_count():
global mongoST
return mongoST.find({}).count()
def STAlexaAuth(alexaId, clientId, clientSecret,clientEmail):
global mongoST
clientInfo = mongoST.find_one({'alexaId':alexaId.upper()})
userId = clientInfo['st_amazonEchoID']
auth_uri = st.smartThingsAuth(alexaId, userId, clientId, clientSecret, clientEmail)
return auth_uri
def data_init():
global mongoST
mongoClient = MongoClient()
mongoClient = MongoClient('localhost', 27017)
mongoDB = mongoClient['AlexaSmartThingsDB']
mongoST = mongoDB['ST']
#st.initAllSwitches()
def data_handler(rawdata):
global mongoST
logger.write_log(str(json.dumps(rawdata,sort_keys=True,indent=4)))
# Session will come later
# currentSession = MyDataStore.getSession(rawdata['session'])
# currentUser = MyDataStore.getUser(rawdata['session'])
sessionId = rawdata['session']['sessionId']
userId = rawdata['session']['user']['userId']
currentRequest = rawdata['request']
if len([a for a in mongoST.find({'st_amazonEchoID':userId})]) == 0:
print "Need to add user into database"
currentUser = {'_id':userId,'st_amazonEchoID':userId,'authenticated':False}
mongoST.update({'st_amazonEchoID':userId},currentUser,True)
timestamp = currentRequest['timestamp']
if utils.datecheck(timestamp,5):
response = request_handler(sessionId, userId, currentRequest)
else:
response = AlexaInvalidDate()
if response is None:
response = AlexaDidNotUnderstand()
if debug: print json.dumps({"version":appVersion,"response":response},sort_keys=True,indent=4)
logger.write_log(str(json.dumps({"version":appVersion,"response":response},sort_keys=True,indent=4)))
return json.dumps({"version":appVersion,"response":response},indent=2,sort_keys=True)
def request_handler(sessionId, userId, request):
global mongoST
requestType = request['type']
if requestType == "LaunchRequest":
return launch_request(sessionId, userId, request)
elif requestType == "IntentRequest":
return intent_request(sessionId, userId, request)
else:
return AlexaDidNotUnderstand()
def launch_request(sessionId, userId, request):
global mongoST
if not st.isValidStUser(userId):
genNewAlexaId(userId,10)
alexaId = getAlexaIdFormUserID(userId)
output_speech = "Current user is not a valid smart things user. Please look at the Echo app for help. New Alexa ID has been generated."
output_type = "PlainText"
card_type = "Simple"
card_title = "SmartThings Control"
card_content = "Current user is not a valid SmartThings user. Please authenticate user with Alexa ID: " + alexaId + " to SmartThings as instructed in the README"
response = {"outputSpeech": {"type":output_type,"text":output_speech},"card":{"type":card_type,"title":card_title,"content":card_content},'shouldEndSession':True}
return response
else:
output_speech = "Welcome to Smart Things Control App. Please say a command."
output_type = "PlainText"
card_type = "Simple"
card_title = "SmartThings Control - Welcome"
card_content = "Welcome to SmartThings Control App. Please say a command."
response = {"outputSpeech": {"type":output_type,"text":output_speech},"card":{"type":card_type,"title":card_title,"content":card_content},'shouldEndSession':False}
return response
def intent_request(sessionId, userId, request):
print "intent_request"
if debug: print json.dumps(request,sort_keys=True,indent=4)
logger.write_log(str(json.dumps(request,sort_keys=True,indent=4)))
if not st.isValidStUser(userId):
genNewAlexaId(userId,10)
alexaId = getAlexaIdFormUserID(userId)
output_speech = "This application has been updated and requires you to reconfigure your Smart Things tokens. Current user is not a valid smart things user. Please look at the Echo app for help. New Alexa ID has been generated."
output_type = "PlainText"
card_type = "Simple"
card_title = "SmartThings Control"
card_content = "Current user is not a valid SmartThings user. Please authenticate user with Alexa ID: " + alexaId + " to SmartThings as instructed in the README"
response = {"outputSpeech": {"type":output_type,"text":output_speech},"card":{"type":card_type,"title":card_title,"content":card_content},'shouldEndSession':True}
return response
else:
if request['intent']['name'] == "STSetMode":
mode = request['intent']['slots']['mode']['value']
output_speech = "Setting Smart Things to " + mode + " mode"
output_type = "PlainText"
card_type = "Simple"
card_title = "SmartThings Control - Setting Mode"
card_content = "Setting Smart Things to " + mode + " mode"
response = {"outputSpeech": {"type":output_type,"text":output_speech},"card":{"type":card_type,"title":card_title,"content":card_content},'shouldEndSession':True}
result = st.set_mode(userId, mode)
if mode == result:
return response
else:
return st_doc.generateError(result, "Setting Mode")
elif request['intent']['name'] == "STPhrase":
genNewAlexaId(userId,100)
phrase = request['intent']['slots']['phrase']['value']
output_speech = "Telling Smart Things to say " + phrase
output_type = "PlainText"
card_type = "Simple"
card_title = "SmartThings Control - HelloHome"
card_content = "Telling Smart Things to say " + phrase
response = {"outputSpeech": {"type":output_type,"text":output_speech},"card":{"type":card_type,"title":card_title,"content":card_content},'shouldEndSession':True}
result = st.set_phrase(userId, phrase)
if phrase == result:
return response
else:
return st_doc.generateError(result, "Setting Phrase")
elif request['intent']['name'] == "STSwitch":
genNewAlexaId(userId,100)
switchId = request['intent']['slots']['switch']['value']
switchState = request['intent']['slots']['state']['value']
result = st.st_switch(userId, switchId, switchState)
output_speech = "Telling " + switchId + " to turn " + result
output_type = "PlainText"
card_type = "Simple"
card_title = "SmartThings Control - Switch"
card_content = "Telling " + switchId + " to turn " + result
response = {"outputSpeech": {"type":output_type,"text":output_speech},"card":{"type":card_type,"title":card_title,"content":card_content},'shouldEndSession':True}
if switchState == 'toggle':
if result.lower() != 'on' and result.lower() != 'off':
return st_doc.generateError(result, "Switch")
else:
return response
elif switchState == result.lower():
return response
else:
return st_doc.generateError(result, "Switch")
elif request['intent']['name'] == "STSamples":
genNewAlexaId(userId,10)
alexaId = getAlexaIdFormUserID(userId)
output_speech = "Requesting new samples. New Alexa ID has been generated. Please see the Echo App."
output_type = "PlainText"
card_type = "Simple"
card_title = "SmartThings Control"
card_content = "New samples have been requested. Please authenticate user with Alexa ID: " + alexaId + " to https://alexa.zpriddy.com/alexa/samples"
response = {"outputSpeech": {"type":output_type,"text":output_speech},"card":{"type":card_type,"title":card_title,"content":card_content},'shouldEndSession':True}
return response
else:
return AlexaDidNotUnderstand()
def alexaIdGenerator(N):
return ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N))
def getUserIdFromAlexaId(alexaId):
global mongoST
currentUser = mongoST.find_one({'alexaId':alexaId})
return currentUser['st_amazonEchoID']
def getUserEmail(userId):
global mongoST
currentUser = mongoST.find_one({'_id':userId})
return currentUser['st_clientEmail']
def genNewAlexaId(userId,size):
global mongoST
currentUser = mongoST.find_one({'st_amazonEchoID':userId})
newAlexaId = alexaIdGenerator(size)
while len([a for a in mongoST.find({'alexaId':newAlexaId})]) > 0:
newAlexaId = alexaIdGenerator(size)
currentUser['alexaId'] = newAlexaId
mongoST.update({'st_amazonEchoID':userId},currentUser,True)
def getAlexaIdFormUserID(userId):
global mongoST
currentUser = mongoST.find_one({'st_amazonEchoID':userId})
return currentUser['alexaId']
def AlexaDidNotUnderstand():
output_speech = "Smart Things app did not understand your request. Please say it again."
output_type = "PlainText"
card_type = "Simple"
card_title = "SmartThings Control - Welcome"
card_content = "Welcome to SmartThings Control App. Please say a command."
response = {"outputSpeech": {"type":output_type,"text":output_speech},"card":{"type":card_type,"title":card_title,"content":card_content},'shouldEndSession':False}
return response
def AlexaInvalidDate():
output_speech = "The date and or time of the request does not match the durrent date."
output_type = "PlainText"
card_type = "Simple"
card_title = "SmartThings Control - Error"
card_content = "The date and or time of the request does not match the durrent date."
response = {"outputSpeech": {"type":output_type,"text":output_speech},"card":{"type":card_type,"title":card_title,"content":card_content},'shouldEndSession':True}
return response