UNPKG

2.55 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6
7function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
8
9var COMPARISON_OPERATORS = {
10 'GREATER_THAN': '>',
11 'GREATER_THAN_OR_EQUAL_TO': '>=',
12 'LESS_THAN': '<',
13 'LESS_THAN_OR_EQUAL_TO': '<=',
14 'EQUAL_TO': '===',
15 'NOT_EQUAL': '!=='
16};
17
18var LOGICAL_OPERATORS = {
19 'AND': '&&',
20 'OR': '||'
21};
22
23function convertScenario(scenario) {
24 return new Promise(function (resolve, reject) {
25 if (!scenario) {
26 return reject('No scenario JSON received!');
27 }
28
29 if (!scenario.actions || !scenario.actions.length) {
30 return reject('Incorrect scenario JSON received!');
31 }
32
33 if (scenario.conditions && scenario.conditions.length >= 2 && !scenario.logicalOperator) {
34 return reject('Missing logical operator!');
35 }
36
37 return resolve('SMART_HOUSE\n .get_api(\'0.0.1\')\n .then(function(api){\n ' + getScriptBody(scenario) + '\n });');
38 });
39}
40
41function getScriptBody(scenario) {
42 if (scenario.conditions && scenario.conditions.length) {
43 return 'api.on(\'message\', [' + getDeviceList(scenario.conditions) + '], function () {\n if (' + getConditions(scenario.conditions, scenario.logicalOperator) + ') {\n ' + getActions(scenario.actions) + '\n }\n });';
44 } else {
45 return getActions(scenario.actions);
46 }
47}
48
49function getConditions(conditions, logicalOperator) {
50 return conditions.reduce(function (conditionsList, condition) {
51 return [].concat(_toConsumableArray(conditionsList), ['api.device.get(\'' + condition.device + '\').value ' + COMPARISON_OPERATORS[condition.condition] + ' ' + condition.value]);
52 }, []).join('\n' + LOGICAL_OPERATORS[logicalOperator] + ' ');
53}
54
55function getActions(actions) {
56 return actions.reduce(function (actionsString, action) {
57 return actionsString + ('api.device.get(\'' + action.device + '\').send(\'' + action.value + '\');\n');
58 }, '');
59}
60
61function getDeviceList(list) {
62 return list.map(function (listItem) {
63 return '\'' + listItem.device + '\'';
64 }).join(', ');
65}
66
67exports.default = { convertScenario: convertScenario };
68module.exports = exports['default'];
69//# sourceMappingURL=scenario.converter.js.map