-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlambda_function.py
290 lines (228 loc) · 8.88 KB
/
lambda_function.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
from datetime import datetime
import uuid
import heatpump
from config import user_devices
def log(title, msg):
print(f"[{title}]: {msg}")
def get_utc_timestamp(dt):
return dt.strftime("%Y-%m-%dT%H:%M:%S.00Z")
def get_uuid():
return str(uuid.uuid4())
def generate_response(name, context, appliance_id, correlation_token):
return {
"context": context,
"event": {
"header": {
"namespace": "Alexa",
"name": name,
"payloadVersion": "3",
"messageId": get_uuid(),
"correlationToken": correlation_token
},
"endpoint": {
"endpointId": appliance_id
},
"payload": {}
}
}
def is_valid_token(access_token):
return True
def get_devices():
return user_devices
def is_device_online(applianceId, access_token):
log("DEBUG", f"is_device_online(applianceId: ${applianceId})")
return True
def handle_discovery(event, session):
print("DEBUG", f"Discovery Request: {event}")
access_token = event["directive"]["payload"]["scope"]["token"]
if access_token == "" or (not is_valid_token(access_token)):
message_id = event["directive"]["header"]["messageId"]
error_message = f"Discovery Request [{message_id}] failed. Invalid access token: {access_token}"
print("ERROR", error_message)
return error_message
return {
"event": {
"header": {
"namespace": 'Alexa.Discovery',
"name": 'Discover.Response',
"payloadVersion": 3,
"messageId": get_uuid()
},
"payload": {
"endpoints": get_devices()
}
}
}
def turn_on(appliance_id, access_token, correlation_token):
log("DEBUG", f"turn_on(applianceId: {appliance_id}")
now = datetime.now()
if not heatpump.turn_on(appliance_id):
return None
context = {
"properties": [
{
"namespace": "Alexa.PowerController",
"name": "powerState",
"value": "ON",
"timeOfSample": get_utc_timestamp(now),
"uncertaintyInMilliseconds": 1000,
}
]
}
return generate_response("Response", context, appliance_id, correlation_token)
def turn_off(appliance_id, access_token, correlation_token):
log("DEBUG", f"turn_off(applianceId: {appliance_id}")
now = datetime.now()
if not heatpump.turn_off(appliance_id):
return None
context = {
"properties": [
{
"namespace": "Alexa.PowerController",
"name": "powerState",
"value": "OFF",
"timeOfSample": get_utc_timestamp(now),
"uncertaintyInMilliseconds": 1000,
}
]
}
return generate_response("Response", context, appliance_id, correlation_token)
def set_target_temperature(appliance_id, access_token, correlation_token):
log("DEBUG", f"set_target_temperature: {appliance_id}")
context = {}
return generate_response("Response", context, appliance_id, correlation_token)
def set_percentage(appliance_id, access_token, correlation_token, percentage):
log("DEBUG", f"set_percentage: {appliance_id}")
now = datetime.now()
if not heatpump.set_fan(appliance_id, percentage):
return None
context = {
"properties": [{
"namespace": "Alexa.PercentageController",
"name": "percentage",
"value": percentage,
"timeOfSample": get_utc_timestamp(now),
"uncertaintyInMilliseconds": 1000
}]
}
return generate_response("Response", context, appliance_id, correlation_token)
def set_power_level(appliance_id, access_token, correlation_token):
log("DEBUG", f"set_power_level: {appliance_id}")
context = {}
return generate_response("Response", context, appliance_id, correlation_token)
def report_state(appliance_id, access_token, correlation_token):
log("DEBUG", f"report_state(applianceId: {appliance_id}")
status = heatpump.get_status(appliance_id)
now = datetime.now()
mode = None
if status.setmode == 1:
mode = "HEAT"
elif status.setmode == 2:
mode = "DRY"
elif status.setmode == 3:
mode = "COOL"
elif status.setmode == 7:
mode = "FAN"
elif status.setmode == 8:
mode = "AUTO"
power_state = "ON" if status.power == 1 else "OFF"
context = {
"properties": [
{
"namespace": "Alexa.PowerController",
"name": "powerState",
"value": power_state,
"timeOfSample": get_utc_timestamp(now),
"uncertaintyInMilliseconds": 1000
},
{
"namespace": "Alexa.TemperatureSensor",
"name": "temperature",
"value": {
"value": status.roomtemp,
"scale": "CELSIUS"
},
"timeOfSample": get_utc_timestamp(now),
"uncertaintyInMilliseconds": 1000
},
{
"namespace": "Alexa.ThermostatController",
"name": "targetSetpoint",
"value": {
"value": status.settemp,
"scale": "CELSIUS"
},
"timeOfSample": get_utc_timestamp(now),
"uncertaintyInMilliseconds": 6000
},
{
"namespace": "Alexa.ThermostatController",
"name": "thermostatMode",
"value": mode,
"timeOfSample": get_utc_timestamp(now),
"uncertaintyInMilliseconds": 6000
},
{
"namespace": "Alexa.PercentageController",
"name": "percentage",
"value": 100,
"timeOfSample": get_utc_timestamp(now),
"uncertaintyInMilliseconds": 1000
}
]
}
return generate_response("StateReport", context, appliance_id, correlation_token)
def handle_control(event, session):
log("DEBUG", f"Control Request: {event}")
access_token = event["directive"]["endpoint"]["scope"]["token"]
if access_token == "" or (not is_valid_token(access_token)):
message_id = event["header"]["messageId"]
error_message = f"Discovery Request [{message_id}] failed. Invalid access token: {access_token}"
print("ERROR", error_message)
return error_message
appliance_id = event["directive"]["endpoint"]["endpointId"]
if appliance_id == "":
log("ERROR", "No applianceId provided in request")
payload = {"faultingParameter": f"applianceId: {applianceId}"}
return generate_response("UnexpectedInformationReceivedError", payload)
if not is_device_online(appliance_id, access_token):
log("ERROR", f"Device offline {access_token}")
return generate_response("TargetOfflineError", {})
response = None
name = event["directive"]["header"]["name"]
correlation_token = event["directive"]["header"]["correlationToken"]
if name == "TurnOn":
response = turn_on(appliance_id, access_token, correlation_token)
elif name == "TurnOff":
response = turn_off(appliance_id, access_token, correlation_token)
elif name == "ReportState":
response = report_state(appliance_id, access_token, correlation_token)
elif name == "SetTargetTemperature":
response = set_target_temperature(appliance_id, access_token, correlation_token)
elif name == "SetPercentage":
percentage = event["directive"]["payload"]["percentage"]
response = set_percentage(appliance_id, access_token, correlation_token, percentage)
elif name == "SetPowerLevel":
response = set_power_level(appliance_id, access_token, correlation_token)
else:
log("ERROR", f"No supported directive name: {name}")
return generate_response("UnsupportedOperationError", {}, appliance_id, correlation_token)
log(f"DEBUG", f"Control Confirmation: {response}")
return response
def lambda_handler(event, session):
namespace = event["directive"]["header"]["namespace"]
if namespace == "Alexa.Discovery":
return handle_discovery(event, session)
elif namespace == "Alexa":
return handle_control(event, session)
elif namespace == "Alexa.PowerController":
return handle_control(event, session)
elif namespace == "Alexa.ThermostatController":
return handle_control(event, session)
elif namespace == "Alexa.PercentageController":
return handle_control(event, session)
elif namespace == "Alexa.PowerLevelController":
return handle_control(event, session)
error_message = f"No supported namespace: {namespace}"
log("ERROR", error_message)
return error_message