forked from ioBroker/ioBroker.text2command
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
313 lines (269 loc) · 11.3 KB
/
main.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
// structure of rule
// {
// template: 'templateName'
// words: 'key words option1/option2/option3 option* option_'
// args: []
// ack: true/false (If acknowledge must be written into .text back
// _break: true // if break processing rules if match
//
//
/* jshint -W097 */
/* jshint strict: false */
/* jslint node: true */
'use strict';
const utils = require('@iobroker/adapter-core'); // Get common adapter utils
const adapterName = require('./package.json').name.split('.').pop();
//noinspection JSUnresolvedFunction
const model = require('./admin/langModel');
const devicesControl = require('./lib/devicesControl');
const simpleControl = require('./lib/simpleControl');
const simpleAnswers = require('./lib/simpleAnswers');
let rules;
let commandsCallbacks;
let systemConfig = {};
let enums = {};
let processTimeout = null;
let processQueue = [];
let adapter;
function startAdapter(options) {
options = options || {};
Object.assign(options, {
name: adapterName
});
adapter = new utils.Adapter(options);
adapter.on('stateChange', (id, state) => {
//noinspection JSUnresolvedVariable
if (state && !state.ack && state.val) {
if (id === adapter.namespace + '.text') {
//noinspection JSUnresolvedVariable
processText(state.val.toString(), sayIt);
}
} else
//noinspection JSUnresolvedVariable
if (state && id === adapter.config.processorId && state.ack) {
// answer received
if (processTimeout) {
clearTimeout(processTimeout);
processTimeout = null;
let task = processQueue.shift();
//noinspection JSUnresolvedVariable
if (state.val) {
if (task.callback) {
//noinspection JSUnresolvedVariable
task.callback((task.withLanguage ? task.language + ';' : '') + state.val);
}
} else {
//noinspection JSUnresolvedVariable
processText((task.withLanguage ? task.language + ';' : '') + task.command, task.callback, null, null, true);
}
setTimeout(useExternalProcessor, 0);
}
}
});
adapter.on('objectChange', (id/*, obj*/) => {
if (id.substring(0, 5) === 'enum.') {
// read all enums
//noinspection JSUnresolvedFunction
adapter.getEnums('', (err, list) => {
enums = list;
devicesControl.init(enums);
});
}
});
adapter.on('ready', () => {
main();
//noinspection JSUnresolvedFunction
adapter.subscribeStates(adapter.namespace + '.text');
});
// New message arrived. obj is array with current messages
adapter.on('message', obj => {
if (obj) {
//noinspection JSUnresolvedVariable
switch (obj.command) {
case 'send':
if (obj.message) {
//noinspection JSUnresolvedVariable
processText(typeof obj.message === 'object' ? obj.message.text : obj.message, res => {
let responseObj = JSON.parse(JSON.stringify(obj.message));
if (typeof responseObj !== 'object') {
responseObj = {text: responseObj};
}
responseObj.response = res;
if (obj.callback) {
//noinspection JSUnresolvedFunction, JSUnresolvedVariable
adapter.sendTo(obj.from, obj.command, responseObj, obj.callback);
}
}, typeof obj.message === 'object' ? JSON.parse(JSON.stringify(obj.message)) : null, obj.from);
}
break;
default:
//noinspection JSUnresolvedVariable
adapter.log.warn('Unknown command: ' + obj.command);
break;
}
}
return true;
});
return adapter;
}
function sayIt(text) {
//noinspection JSUnresolvedFunction
adapter.setState('response', text || '', true, err => err && adapter.log.error(err));
//noinspection JSUnresolvedVariable
if (!text || !adapter.config.sayitInstance) return;
//noinspection JSUnresolvedVariable,JSUnresolvedFunction
adapter.setForeignState(adapter.config.sayitInstance, text, err => err && adapter.log.error(err));
}
function useExternalProcessor() {
if (!processTimeout && processQueue.length) {
let task = processQueue[0];
// send task to external processor
//noinspection JSUnresolvedVariable,JSUnresolvedFunction
adapter.setForeignState(adapter.config.processorId, JSON.stringify(task));
// wait x seconds for answer
//noinspection JSUnresolvedVariable
processTimeout = setTimeout(() => {
processTimeout = null;
// no answer in given period
let _task = processQueue.shift();
// process with rules
//noinspection JSUnresolvedVariable
processText((_task.withLanguage ? _task.language + ';' : '') + _task.command, _task.callback, null, null, true);
// process next
useExternalProcessor();
}, adapter.config.processorTimeout || 1000);
}
}
function processText(cmd, cb, messageObj, from, afterProcessor) {
adapter.log.info('processText: "' + cmd + '"');
let lang = adapter.config.language || systemConfig.language || 'en';
if (cmd === null || cmd === undefined) {
adapter.log.error('processText: invalid command!');
adapter.setState('error', 'invalid command', true);
//noinspection JSUnresolvedFunction
simpleAnswers.sayError(lang, 'processText: invalid command!', null, null, result =>
cb(result ? ((withLang ? lang + ';' : '') + result) : ''));
return;
}
cmd = cmd.toString();
let originalCmd = cmd;
let withLang = false;
let ix = cmd.indexOf(';');
cmd = cmd.toLowerCase();
// extract language
if (ix !== -1) {
withLang = true;
lang = cmd.substring(0, ix) || lang;
cmd = cmd.substring(ix + 1);
originalCmd = originalCmd.substring(ix + 1);
}
// if desired processing by javascript
//noinspection JSUnresolvedVariable
if (!afterProcessor && adapter.config.processorId) {
let task = messageObj || {};
task.language = lang;
task.command = originalCmd;
task.withLanguage = withLang;
task.from = from;
task.callback = cb;
if (processQueue.length < 100) {
processQueue.push(task);
useExternalProcessor();
return;
} else {
adapter.log.error('External process queue is full. Try to use rules.');
}
} else if (afterProcessor) {
//noinspection JSUnresolvedVariable
adapter.log.warn('Timeout for external processor: ' + adapter.config.processorId);
}
//noinspection JSUnresolvedFunction
let matchedRules = model.findMatched(cmd, rules);
let result = '';
let count = matchedRules.length;
for (let m = 0; m < matchedRules.length; m++) {
//noinspection JSUnresolvedVariable
if (model.commands[rules[matchedRules[m]].template] && model.commands[rules[matchedRules[m]].template].extractText) {
//noinspection JSUnresolvedFunction,JSUnresolvedVariable
cmd = simpleControl.extractText(cmd, originalCmd, rules[matchedRules[m]].words);
}
//noinspection JSUnresolvedVariable
if (commandsCallbacks[rules[matchedRules[m]].template]) {
//noinspection JSUnresolvedVariable
commandsCallbacks[rules[matchedRules[m]].template](lang, cmd, rules[matchedRules[m]].args, rules[matchedRules[m]].ack, response => {
adapter.log.info('Response: ' + response);
// somehow combine answers
if (response) {
//noinspection JSReferencingMutableVariableFromClosure
result += (result ? ', ' : '') + response;
}
adapter.config.writeEveryAnswer && adapter.setState('response', response, true);
if (!--count) {
//noinspection JSReferencingMutableVariableFromClosure
cb && cb(result ? ((withLang ? lang + ';' : '') + result) : '');
cb = null;
}
});
} else {
count--;
if (rules[matchedRules[m]].ack) {
//noinspection JSUnresolvedFunction
result += (result ? ', ' : '') + simpleAnswers.getRandomPhrase(rules[matchedRules[m]].ack);
}
}
}
if (!matchedRules.length) {
//noinspection JSUnresolvedFunction
simpleAnswers.sayIDontUnderstand(lang, cmd, null, null, result => {
cb && cb(result ? ((withLang ? lang + ';' : '') + result) : '');
cb = null;
});
} else if (!count) {
cb && cb(result ? ((withLang ? lang + ';' : '') + result) : '');
cb = null;
}
}
function main() {
rules = adapter.config.rules || {};
//noinspection JSUnresolvedVariable
commandsCallbacks = {
whatTimeIsIt: simpleControl.sayTime,
whatIsYourName: simpleControl.sayName,
outsideTemperature: simpleControl.sayTemperature,
insideTemperature: simpleControl.sayTemperature,
functionOnOff: devicesControl.controlByFunction,
blindsUpDown: devicesControl.controlBlinds,
userDeviceControl: simpleControl.userDeviceControl,
sendText: simpleControl.sendText,
/* openLock: openLock,*/
userQuery: simpleControl.userQuery,
buildAnswer: simpleControl.buildAnswer
};
//noinspection JSUnresolvedFunction
adapter.subscribeForeignObjects('enum.*');
//noinspection JSUnresolvedVariable
if (adapter.config.processorId) {
//noinspection JSUnresolvedFunction,JSUnresolvedVariable
adapter.subscribeForeignStates(adapter.config.processorId);
}
// read system configuration
//noinspection JSUnresolvedFunction
adapter.getForeignObject('system.config', (err, obj) => {
//noinspection JSUnresolvedVariable
systemConfig = (obj ? obj.common : {}) || {};
simpleControl.init(systemConfig, adapter);
});
// read all enums
//noinspection JSUnresolvedFunction
adapter.getEnums('', (err, list) => {
enums = list;
devicesControl.init(enums, adapter);
});
}
// If started as allInOne mode => return function to create instance
if (module.parent) {
module.exports = startAdapter;
} else {
// or start the instance directly
startAdapter();
}