-
Notifications
You must be signed in to change notification settings - Fork 0
/
thirdeye.js
267 lines (244 loc) · 8.15 KB
/
thirdeye.js
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
'use strict';
const baseUrl = process.env.ST_API_URL;
const request = require('request');
exports.handler = (event, context, callback) => {
console.log('Base URL from config file is: ', baseUrl);
console.log('Event payload: ' + JSON.stringify(event, null, 2));
console.log(event);
try {
let res;
switch(event.lifecycle) {
case 'PING': {
callback(null, {
statusCode: 200,
pingData: {
challenge: event.pingData.challenge
}
});
break;
}
case 'CONFIGURATION': {
res = handleConfig(event.configurationData);
callback(null, {
configurationData: res,
statusCode: 200
});
break;
}
case 'INSTALL': {
handleInstall(event.installData.installedApp, event.installData.authToken);
callback(null, {
installData: {},
statusCode: 200
});
break;
}
case 'UPDATE': {
handleUpdate(event.updateData.installedApp, event.authToken);
callback(null, {
updateData: {},
statusCode: 200
});
break;
}
case 'UNINSTALL': {
// Delete subscriptions
break;
}
case 'EVENT': {
handleEvents(event.eventData);
callback(null, {
eventData: {},
statusCode: 200
});
break;
}
default: {
callback('Error, execType is not supported: ${event.executionType}');
}
}
} catch (error) {
callback('Error occurred: ' + error);
}
};
function handleConfig(event) {
if (!event.config) {
throw new Error('No config section set in request.');
}
const configurationData = {};
const phase = event.phase;
const pageId = event.pageId;
const settings = event.config;
switch (phase) {
case 'INITIALIZE':
configurationData.initialize = createAppInfo();
break;
case 'PAGE':
configurationData.page = createConfigPage(pageId, settings);
break;
default:
throw new Error('Unsupported config phase: ${phase}');
break;
}
return configurationData;
}
function createAppInfo() {
return {
name: 'Third Eye',
description: 'Smartapp for monitoring intruders.',
id: 'thirdeye',
permissions: ['r:devices:*', 'x:devices:*', 'w:devices:*', 'w:installedapps'],
firstPageId: '1'
}
}
function createConfigPage(pageId, currentConfig) {
if (pageId !== '1') {
throw new Error('Unsupported page name: ${pageId}');
}
return {
pageId: '1',
name: 'Third Eye',
nextPageId: null,
previousPageId: null,
complete: true,
sections: [
{
name: 'Turn on when there\'s movement...',
settings: [
{
id: 'motion1', // ID of this field
name: 'Select a motion sensor',
description: 'Tap to set',
type: 'DEVICE',
required: true,
multiple: false,
capabilities: ['motionSensor'],
permissions: ['r']
}
]
},
{
name: 'Turn on below light',
settings: [
{
id: 'switches', // ID of this field
name: 'Select a light',
description: 'Tap to set',
type: 'DEVICE',
required: true,
multiple: false,
capabilities: ['switch', 'actuator'],
permissions: ['r', 'x']
}
]
}
]
};
}
function handleInstall(installedApp, authCode) {
const path = '/installedapps/' + installedApp.installedAppId + '/subscriptions';
console.log('Config payload: ' + JSON.stringify(installedApp.config, null, 2));
console.log('Permissions payload: ' + installedApp.permissions);
let subRequest = {
sourceType: 'DEVICE',
device: {
componentId: installedApp.config.motion1[0].deviceConfig.componentId,
deviceId: installedApp.config.motion1[0].deviceConfig.deviceId,
capability: 'motionSensor',
attribute: 'motion',
stateChangeOnly: true,
value: '*'
}
};
console.log('subscribeToMotion:', [installedApp.installedAppId, installedApp.config, authCode, path]);
request.post({
url: baseUrl + path,
json: true,
body: subRequest,
headers: {
'Authorization': 'Bearer ' + authCode,
}
},function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log('Thirdeye subscriptions successful.')
} else {
console.log('Thirdeye subscriptions failed.');
console.log(error);
}
});
}
function handleUpdate(installedApp, authToken) {
const path = '/locations/${installedApp.locationId}/installedapps/${installedApp.installedAppId}/subscriptions';
request.delete({
url: baseUrl + path,
headers: {
'Authorization': 'Bearer ' + authToken
}
}, function () {
var switches = 'switches' in installedApp.config
var motion1 = 'motion1' in installedApp.config
console.log('Check for device deletion scenario. switches: ' + switches, 'motion1: ' + motion1);
if ((motion1 == false) || (switches == false)) {
console.log("Some device got deleted. Uninstall the app.");
unInstallApp(installedApp, authToken);
} else {
handleInstall(installedApp, authToken);
}
});
}
function unInstallApp(installedApp, authToken) {
// TODO
const path = '/v1/installedapps/${installedApp.installedAppId}';
request.delete({
url: baseUrl + path,
headers: {
'Authorization': 'Bearer ' + authToken
}
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log('uninstall app successful.')
} else {
console.log('uninstall app failed.');
console.log(error, response, body);
}
});
}
function handleEvents(eventData) {
const eventType = eventData.events[0].eventType;
if ('DEVICE_EVENT' === eventType) {
console.log(eventData.events[0].deviceEvent);
motionHandler(eventData.installedApp.installedAppId, eventData.events[0].deviceEvent, eventData.installedApp.config, eventData.authToken);
}
}
function motionHandler(installedAppId, deviceEvent, config, authToken) {
if (deviceEvent.deviceId === config.motion1[0].deviceConfig.deviceId) {
if (deviceEvent.value === 'active') {
console.log('turning on lights');
actuateLight(config.switches[0].deviceConfig.deviceId, 'on', authToken);
} else if (deviceEvent.value === 'inactive') {
actuateLight(config.switches[0].deviceConfig.deviceId, 'off', authToken);
}
}
}
function actuateLight(deviceId, status, authToken) {
const path = '/devices/' + deviceId + '/commands';
const deviceRequest = {
component: 'main',
capability: 'switch',
command: status,
arguments: []
};
console.log('Actuate Light:', [path, deviceRequest]);
request.post({
url: baseUrl + path,
json: true,
body: [deviceRequest],
headers: {
'Authorization': 'Bearer ' + authToken
}
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log('this worked')
}
});
}