forked from fewieden/MMM-voice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node_helper.js
367 lines (323 loc) · 11 KB
/
node_helper.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
/**
* @file node_helper.js
*
* @author fewieden
* @license MIT
*
* @see https://github.com/fewieden/MMM-voice
*/
/**
* @external pocketsphinx-continuous
* @see https://github.com/fewieden/pocketsphinx-continuous-node
*/
const Psc = require('pocketsphinx-continuous');
/**
* @external fs
* @see https://nodejs.org/api/fs.html
*/
const fs = require('fs');
/**
* @external child_process
* @see https://nodejs.org/api/child_process.html
*/
const exec = require('child_process').exec;
/**
* @external lmtool
* @see https://www.npmjs.com/package/lmtool
*/
const lmtool = require('lmtool');
/**
* @module Bytes
* @description Pure Magic
*/
const bytes = require('./Bytes.js');
/**
* @external node_helper
* @see https://github.com/MichMich/MagicMirror/blob/master/modules/node_modules/node_helper/index.js
*/
const NodeHelper = require('node_helper');
/**
* @module node_helper
* @description Backend for the module to query data from the API providers.
*
* @requires external:pocketsphinx-continuous
* @requires external:fs
* @requires external:child_process
* @requires external:lmtool
* @requires Bytes
* @requires external:node_helper
*/
module.exports = NodeHelper.create({
/** @member {boolean} listening - Flag to indicate listen state. */
listening: false,
/** @member {(boolean|string)} mode - Contains active module mode. */
mode: false,
/** @member {boolean} hdmi - Flag to indicate hdmi output state. */
hdmi: true,
/** @member {boolean} help - Flag to toggle help modal. */
help: false,
/** @member {string[]} words - List of all words that are registered by the modules. */
words: [],
/**
* @function start
* @description Logs a start message to the console.
* @override
*/
start() {
console.log(`Starting module helper: ${this.name}`);
},
/**
* @function socketNotificationReceived
* @description Receives socket notifications from the module.
* @override
*
* @param {string} notification - Notification name
* @param {*} payload - Detailed payload of the notification.
*/
socketNotificationReceived(notification, payload) {
if (notification === 'START') {
/** @member {Object} config - Module config. */
this.config = payload.config;
/** @member {number} time - Time to listen after keyword. */
this.time = this.config.timeout * 1000;
/** @member {Object} modules - List of modules with their modes and commands. */
this.modules = payload.modules;
this.fillWords();
this.checkFiles();
}
},
/**
* @function fillwords
* @description Sets {@link node_helper.words} with all needed words for the registered
* commands by the modules. This list has unique items and is sorted by alphabet.
*/
fillWords() {
// create array
let words = this.config.keyword.split(' ');
const temp = bytes.q.split(' ');
words = words.concat(temp);
for (let i = 0; i < this.modules.length; i += 1) {
const mode = this.modules[i].mode.split(' ');
words = words.concat(mode);
for (let n = 0; n < this.modules[i].sentences.length; n += 1) {
const sentences = this.modules[i].sentences[n].split(' ');
words = words.concat(sentences);
}
}
// filter duplicates
words = words.filter((item, index, data) => data.indexOf(item) === index);
// sort array
words.sort();
this.words = words;
},
/**
* @function checkFiles
* @description Checks if words.json exists or has different entries as this.word.
*/
checkFiles() {
console.log(`${this.name}: Checking files.`);
fs.stat('modules/MMM-voice/words.json', (error, stats) => {
if (!error && stats.isFile()) {
fs.readFile('modules/MMM-voice/words.json', 'utf8', (err, data) => {
if (!err) {
const words = JSON.parse(data).words;
if (this.arraysEqual(this.words, words)) {
this.startPocketsphinx();
return;
}
}
this.generateDicLM();
});
} else {
this.generateDicLM();
}
});
},
/**
* @function arraysEqual
* @description Compares two arrays.
*
* @param {string[]} a - First array
* @param {string[]} b - Second array
* @returns {boolean} Are the arrays equal or not.
*/
arraysEqual(a, b) {
if (!(a instanceof Array) || !(b instanceof Array)) {
return false;
}
if (a.length !== b.length) {
return false;
}
for (let i = 0; i < a.length; i += 1) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
},
/**
* @function generateDicLM
* @description Generates new Dictionairy and Language Model.
*/
generateDicLM() {
console.log(`${this.name}: Generating dictionairy and language model.`);
fs.writeFile('modules/MMM-voice/words.json', JSON.stringify({ words: this.words }), (err) => {
if (err) {
console.log(`${this.name}: Couldn't save words.json!`);
} else {
console.log(`${this.name}: Saved words.json successfully.`);
}
});
lmtool(this.words, (err, filename) => {
if (err) {
this.sendSocketNotification('ERROR', 'Couldn\'t create necessary files!');
} else {
fs.renameSync(`${filename}.dic`, 'modules/MMM-voice/MMM-voice.dic');
fs.renameSync(`${filename}.lm`, 'modules/MMM-voice/MMM-voice.lm');
this.startPocketsphinx();
fs.unlink(`${filename}.log_pronounce`, this.noOp);
fs.unlink(`${filename}.sent`, this.noOp);
fs.unlink(`${filename}.vocab`, this.noOp);
fs.unlink(`TAR${filename}.tgz`, this.noOp);
}
});
},
/**
* @function noOp
* @description Performs no operation.
*/
noOp() {},
/**
* @function startPocketsphinx
* @description Starts Pocketsphinx binary.
*/
startPocketsphinx() {
console.log(`${this.name}: Starting pocketsphinx.`);
this.ps = new Psc({
setId: this.name,
verbose: true,
microphone: this.config.microphone
});
this.ps.on('data', this.handleData.bind(this));
if (this.config.debug) {
this.ps.on('debug', this.logDebug.bind(this));
}
this.ps.on('error', this.logError.bind(this));
this.sendSocketNotification('READY');
},
/**
* @function handleData
* @description Helper method to handle recognized data.
*
* @param {string} data - Recognized data
*/
handleData(data) {
if (typeof data === 'string') {
if (this.config.debug) {
console.log(`${this.name} has recognized: ${data}`);
this.sendSocketNotification('DEBUG', data);
}
if (data.includes(this.config.keyword) || this.listening) {
this.listening = true;
this.sendSocketNotification('LISTENING');
if (this.timer) {
clearTimeout(this.timer);
}
this.timer = setTimeout(() => {
this.listening = false;
this.sendSocketNotification('SLEEPING');
}, this.time);
} else {
return;
}
let cleanData = this.cleanData(data);
for (let i = 0; i < this.modules.length; i += 1) {
const n = cleanData.indexOf(this.modules[i].mode);
if (n === 0) {
this.mode = this.modules[i].mode;
cleanData = cleanData.substr(n + this.modules[i].mode.length).trim();
break;
}
}
if (this.mode) {
this.sendSocketNotification('VOICE', { mode: this.mode, sentence: cleanData });
if (this.mode === 'VOICE') {
this.checkCommands(cleanData);
}
}
}
},
/**
* @function logDebug
* @description Logs debug information into debug log file.
*
* @param {string} data - Debug information
*/
logDebug(data) {
fs.appendFile('modules/MMM-voice/debug.log', data, (err) => {
if (err) {
console.log(`${this.name}: Couldn't save error to log file!`);
}
});
},
/**
* @function logError
* @description Logs error information into error log file.
*
* @param {string} data - Error information
*/
logError(error) {
if (error) {
fs.appendFile('modules/MMM-voice/error.log', `${error}\n`, (err) => {
if (err) {
console.log(`${this.name}: Couldn't save error to log file!`);
}
this.sendSocketNotification('ERROR', error);
});
}
},
/**
* @function cleanData
* @description Removes prefix/keyword and multiple spaces.
*
* @param {string} data - Recognized data to clean.
* @returns {string} Cleaned data
*/
cleanData(data) {
let temp = data;
const i = temp.indexOf(this.config.keyword);
if (i !== -1) {
temp = temp.substr(i + this.config.keyword.length);
}
temp = temp.replace(/ {2,}/g, ' ').trim();
return temp;
},
/**
* @function checkCommands
* @description Checks for commands of voice module
* @param {string} data - Recognized data
*/
checkCommands(data) {
if (bytes.r[0].test(data) && bytes.r[1].test(data)) {
this.sendSocketNotification('BYTES', bytes.a);
} else if (/(WAKE)/g.test(data) && /(UP)/g.test(data)) {
exec('/opt/vc/bin/tvservice -p && sudo chvt 6 && sudo chvt 7', null);
this.hdmi = true;
} else if (/(GO)/g.test(data) && /(SLEEP)/g.test(data)) {
exec('/opt/vc/bin/tvservice -o', null);
this.hdmi = false;
} else if (/(SHOW)/g.test(data) && /(MODULES)/g.test(data)) {
this.sendSocketNotification('SHOW');
} else if (/(HIDE)/g.test(data) && /(MODULES)/g.test(data)) {
this.sendSocketNotification('HIDE');
} else if (/(HELP)/g.test(data)) {
if (/(CLOSE)/g.test(data) || (this.help && !/(OPEN)/g.test(data))) {
this.sendSocketNotification('CLOSE_HELP');
this.help = false;
} else if (/(OPEN)/g.test(data) || (!this.help && !/(CLOSE)/g.test(data))) {
this.sendSocketNotification('OPEN_HELP');
this.help = true;
}
}
}
});