-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathhandler.py
95 lines (86 loc) · 3.02 KB
/
handler.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
import logging
import boto3
import json
logger = logging.getLogger()
logger.setLevel(logging.INFO)
client = boto3.client('iot-data')
def lambda_handler(event, context):
logger.info('got event{}'.format(event))
access_token = event['payload']['accessToken']
if (event['header']['namespace'] == 'Alexa.ConnectedHome.Discovery' and
event['header']['name'] == 'DiscoverAppliancesRequest'):
return handleDiscovery(context, event)
elif event['header']['namespace'] == 'Alexa.ConnectedHome.Control':
return handleControl(context, event)
def handleDiscovery(context, event):
return {
'header': {
'messageId': event['header']['messageId'],
'name': 'DiscoverAppliancesResponse',
'namespace': 'Alexa.ConnectedHome.Discovery',
'payloadVersion': '2'
},
'payload': {
'discoveredAppliances': [
{
'applianceId': 'table-lamp',
'friendlyName': 'Table Lamp',
'friendlyDescription': 'The table lamp controlled by Raspberry Pi and RF switch 1',
'actions': [
'turnOn',
'turnOff'
],
'additionalApplianceDetails': {},
'isReachable': True,
'manufacturerName': 'AWShome',
'modelName': '1',
'version': '1'
},
{
'applianceId': 'floor-lamp',
'friendlyName': 'Floor Lamp',
'friendlyDescription': 'The floor lamp controlled by Raspberry Pi and RF switch 2',
'actions': [
'turnOn',
'turnOff'
],
'additionalApplianceDetails': {},
'isReachable': True,
'manufacturerName': 'AWShome',
'modelName': '1',
'version': '1'
}
]
}
}
def handleControl(context, event):
device_id = event['payload']['appliance']['applianceId']
requestType = event['header']['name']
if requestType == 'TurnOnRequest':
name = 'TurnOnConfirmation'
light = True
elif requestType == 'TurnOffRequest':
name = 'TurnOffConfirmation'
light = False
# we don't support other requestTypes yet
logger.info('turning %s %s' % ('on' if light else 'off', device_id))
response = client.update_thing_shadow(
thingName=device_id,
payload=json.dumps({
'state': {
'desired': {
'light': light
}
}
})
)
logger.info('received {}'.format(response))
return {
'header': {
"messageId": event['header']['messageId'],
"name": name,
"namespace":"Alexa.ConnectedHome.Control",
"payloadVersion":"2"
},
'payload': {}
}