forked from openhab/openhab-alexa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
oh2.js
432 lines (376 loc) · 14.6 KB
/
oh2.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
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
/**
* Copyright (c) 2014-2016 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
/**
* An Amazon Echo Smart Home Skill API implementation for openHAB (v2.x)
*/
var utils = require('./utils.js');
var rest = require('./rest.js');
/**
* This method is invoked when we receive a "Discovery" message from Alexa Smart Home Skill.
* We are expected to respond back with a list of appliances that we have discovered for a given
* customer.
*/
exports.handleDiscovery = function (event, context) {
/**
* Crafting the response header
*/
var header = {
messageId: event.header.messageId,
name: event.header.name.replace("Request", "Response"),
namespace: event.header.namespace,
payloadVersion: event.header.payloadVersion
};
/**
* Craft the final response back to Alexa Smart Home Skill. This will include all the
* discoverd appliances.
*/
discoverDevices(event.payload.accessToken, function (devices) {
/**
* Response body will be an array of discovered devices.
*/
var payload = {
discoveredAppliances: devices
};
var result = {
header: header,
payload: payload
};
// DEBUG
utils.log('Discovery', JSON.stringify(result));
context.succeed(result);
},
function (error) {
context.done(null, utils.generateControlError(event.header.messageId, event.header.name, 'DependentServiceUnavailableError', error.message));
});
};
/**
* Control events are processed here.
* This is called when Alexa requests an action (IE turn off appliance).
*/
exports.handleControl = function (event, context) {
/**
* Make a remote call to execute the action based on accessToken and the applianceId and the switchControlAction
* Some other examples of checks:
* validate the appliance is actually reachable else return TARGET_OFFLINE error
* validate the authentication has not expired else return EXPIRED_ACCESS_TOKEN error
* Please see the technical documentation for detailed list of errors
*/
switch (event.header.name) {
case 'TurnOnRequest':
case 'TurnOffRequest':
turnOnOff(context, event);
break;
case 'SetTargetTemperatureRequest':
case 'IncrementTargetTemperatureRequest':
case 'DecrementTargetTemperatureRequest':
adjustTemperature(context, event);
break;
case 'SetPercentageRequest':
case 'IncrementPercentageRequest':
case 'DecrementPercentageRequest':
adjustPercentage(context, event);
break;
}
};
/**
* Turns a Switch Item on or off
*/
function turnOnOff(context, event) {
var success = function (response) {
var header = {
messageId: event.header.messageId,
name: event.header.name.replace("Request", "Confirmation"),
namespace: event.header.namespace,
payloadVersion: event.header.payloadVersion
};
var payload = {};
var result = {
header: header,
payload: payload
};
// DEBUG
//utils.log('Done with result', result);
context.succeed(result);
};
var failure = function (error) {
context.done(null, utils.generateControlError(event.header.messageId, event.header.name, 'DependentServiceUnavailableError', error.message));
};
var state = event.header.name === "TurnOnRequest" ? 'ON' : 'OFF';
postItemCommand(event.payload.accessToken,
event.payload.appliance.applianceId, state, success, failure);
}
/**
* Adjust a percentage value on a item
**/
function adjustPercentage(context, event) {
//is this a set command, or Inc/Dec command
var isSetCommand = event.header.name === 'SetPercentageRequest';
/**
* Success functon for sending a percentage change command to OH
*/
var itemPostSuccess = function (response) {
var header = {
messageId: event.header.messageId,
name: event.header.name.replace("Request", "Confirmation"),
namespace: event.header.namespace,
payloadVersion: event.header.payloadVersion
};
var payload = {};
var result = {
header: header,
payload: payload
};
// DEBUG
//utils.log('Done with result', result);
context.succeed(result);
};
/**
* Success Function for retrieveing an items state to use for INC/DEC logic
*/
var itemGetSuccess = function (item) {
// DEBUG
//utils.log("itemGetSuccess", "item state " + item.state + " delta " + event.payload.deltaPercentage.value);
//inc/dec command
//skip this if we don't have a number to start with
if (isNaN(item.state)) {
failure({
message: "Could not get numberic item state"
});
return;
}
var state = parseInt(item.state);
var value;
if (event.header.name === 'IncrementPercentageRequest') {
value = state + parseInt(event.payload.deltaPercentage.value);
if (value > 100) {
value = 100;
}
} else {
value = state - parseInt(event.payload.deltaPercentage.value);
if (value < 0) {
value = 0;
}
}
postItemCommand(event.payload.accessToken, event.payload.appliance.applianceId, value.toString(), itemPostSuccess, failure);
};
/**
* Failure Function used for both retieveing items and posting item commands.
*/
var failure = function (error) {
context.done(null, utils.generateControlError(event.header.messageId, event.header.name, 'DependentServiceUnavailableError', error.message));
};
if (isSetCommand) {
postItemCommand(event.payload.accessToken, event.payload.appliance.applianceId, event.payload.percentageState.value.toString(), itemPostSuccess, failure);
} else if (event.payload.percentageState) {
getItem(event.payload.accessToken, event.payload.appliance.applianceId, itemGetSuccess, failure);
} else {
context.done(null, utils.generateControlError(event.header.messageId, event.header.name, 'DependentServiceUnavailableError', 'Invalid target percentage.'));
}
}
/**
* Adjust a thermostat's temperature by first reading its current values
**/
function adjustTemperature(context, event) {
var success = function (response) {
var targetTemperature;
var currentTemperature;
var heatingCoolingMode;
for (var memberNum in response.members) {
var member = response.members[memberNum];
for (var tagNum in member.tags) {
if (member.tags[tagNum] === 'CurrentTemperature') {
currentTemperature = member;
}
if (member.tags[tagNum] === 'TargetTemperature') {
targetTemperature = member;
}
if (member.tags[tagNum] === 'homekit:heatingCoolingMode') {
heatingCoolingMode = member;
}
}
}
adjustTemperatureWithItems(context, event, currentTemperature, targetTemperature, heatingCoolingMode);
};
var failure = function (error) {
context.done(null, utils.generateControlError(event.header.messageId, event.header.name, 'DependentServiceUnavailableError', error.message));
};
getItem(event.payload.accessToken, event.payload.appliance.applianceId, success, failure);
}
/**
* Adjust a thermostat's temperature based on its current actual readings.
**/
function adjustTemperatureWithItems(context, event, currentTemperature, targetTemperature, heatingCoolingMode) {
if (!targetTemperature) {
context.done(null, utils.generateControlError(event.header.messageId, event.header.name, 'DependentServiceUnavailableError', 'Missing target temperature!'));
return;
}
var curValue = parseInt(targetTemperature.state);
/**
* Alexa needs everything in Celsius, we will need to respect what a user has set
*/
var isF = event.payload.appliance.additionalApplianceDetails.temperatureFormat && event.payload.appliance.additionalApplianceDetails.temperatureFormat === 'fahrenheit';
var setValue;
switch (event.header.name) {
case 'SetTargetTemperatureRequest':
setValue = isF ? utils.toF(event.payload.targetTemperature.value) : event.payload.targetTemperature.value;
break;
case 'IncrementTargetTemperatureRequest':
setValue = curValue + event.payload.deltaTemperature.value;
break;
case 'DecrementTargetTemperatureRequest':
setValue = curValue - event.payload.deltaTemperature.value;
break;
}
// DEBUG
//utils.log("adjustTemperatureWithItems", "setValue " + setValue);
var curMode = heatingCoolingMode ? heatingCoolingMode.state : "AUTO";
//if state returns as a decimal type, convert to string, this is a very common thermo pattern
switch (curMode) {
case '0': //off, not supported! Weird. But nothing else todo.
curMode = 'OFF';
break;
case '1': //auto
case 'heat-cool': //nest auto
curMode = 'AUTO';
break;
case '2': //heating
curMode = 'HEAT';
break;
case '3': //cooling
curMode = 'COOL';
break;
}
curMode = curMode.toUpperCase();
var success = function (response) {
var header = {
messageId: event.header.messageId,
name: event.header.name.replace("Request", "Confirmation"),
namespace: event.header.namespace,
payloadVersion: event.header.payloadVersion
};
var payload = {
targetTemperature: {
value: isF ? utils.toC(setValue) : setValue
},
temperatureMode: {
value: curMode
},
previousState: {
targetTemperature: {
value: isF ? utils.toC(curValue) : curValue
},
mode: {
value: curMode
}
}
};
var result = {
header: header,
payload: payload
};
// DEBUG
//utils.log('Done with result', JSON.stringify(result));
context.succeed(result);
};
var failure = function (error) {
context.done(null, utils.generateControlError(event.header.messageId, event.header.name, 'DependentServiceUnavailableError', 'Unable to connect to server'));
};
postItemCommand(event.payload.accessToken, targetTemperature.name, setValue.toString(), success, failure);
}
/**
* Add all devices that have been tagged
**/
function discoverDevices(token, success, failure) {
var getSuccess = function (items) {
//DEBUG
utils.log("discoverDevices", JSON.stringify(items));
var discoverdDevices = [];
for (var itemNum in items) {
var item = items[itemNum];
for (var tagNum in item.tags) {
var tag = item.tags[tagNum];
var actions = null;
var additionalApplianceDetails = {};
switch (tag) {
case "Lighting":
case "Switchable":
if (item.type === "Switch" ||
(item.type === "Group" && item.groupType && item.groupType === "Switch")) {
actions = [
"turnOn",
"turnOff"
];
} else if (item.type === "Dimmer" ||
(item.type === "Group" && item.groupType && item.groupType === "Dimmer")) {
actions = [
"incrementPercentage",
"decrementPercentage",
"setPercentage",
"turnOn",
"turnOff"
];
}
break;
case "CurrentTemperature":
case "homekit:heatingCoolingMode":
case "TargetTemperature":
break;
case "Thermostat":
//only group items are allowed to have a Temperature tag
if (item.type === 'Group') {
actions = [
"incrementTargetTemperature",
"decrementTargetTemperature",
"setTargetTemperature"
];
var formatIndex = item.tags.indexOf("Fahrenheit");
if (formatIndex > -1) {
additionalApplianceDetails.temperatureFormat = "fahrenheit";
} else {
additionalApplianceDetails.temperatureFormat = "celsius";
}
}
break;
default:
break;
}
if (actions !== null) {
// DEBUG
utils.log("adding " + item.name + " with tag: " + tag);
additionalApplianceDetails.itemType = item.type;
additionalApplianceDetails.itemTag = tag;
additionalApplianceDetails.openhabVersion = '2';
var discoverdDevice = {
actions: actions,
applianceId: item.name,
manufacturerName: 'openHAB',
modelName: tag,
version: '2',
friendlyName: item.label,
friendlyDescription: item.type + ' ' + item.name + ' ' + tag + ' via openHAB',
isReachable: true,
additionalApplianceDetails: additionalApplianceDetails
};
discoverdDevices.push(discoverdDevice);
}
}
}
success(discoverdDevices);
};
getItems(token, getSuccess, failure);
}
function getItem(token, itemName, success, failure) {
return rest.getItem(2, token, itemName, success, failure);
}
function getItems(token, success, failure) {
return rest.getItems(2, token, success, failure);
}
function postItemCommand(token, itemName, value, success, failure) {
return rest.postItemCommand(2, token, itemName, value, success, failure);
}