-
Notifications
You must be signed in to change notification settings - Fork 14
/
metaController.js
575 lines (526 loc) · 26.6 KB
/
metaController.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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
'use strict';
const path = require('path');
const { imageHelper } = require(path.join(__dirname,'imageHelper'));
const { labelHelper } = require(path.join(__dirname,'labelHelper'));
const { switchHelper } = require(path.join(__dirname,'switchHelper'));
const { sensorHelper } = require(path.join(__dirname,'sensorHelper'));
const { sliderHelper } = require(path.join(__dirname,'sliderHelper'));
const { directoryHelper } = require(path.join(__dirname,'directoryHelper'));
const { variablesVault } = require(path.join(__dirname,'variablesVault'));
const settings = require(path.join(__dirname,'settings'));
const wol = require('wake_on_lan');
const variablePattern = {'pre':'$','post':''};
const BUTTONHIDE = '__';
const RESULT = variablePattern.pre + 'Result' + variablePattern.post;
const HTTPGET = 'http-get';
const HTTPREST = 'http-rest';
const HTTPGETSOAP = 'http-get-soap';
const HTTPPOST = 'http-post';
const STATIC = 'static';
const CLI = 'cli';
const REPL = 'repl';
const WEBSOCKET = 'webSocket';
const SOCKETIO = 'socketIO';
const JSONTCP = 'jsontcp';
const MQTT = 'mqtt';
const WOL = 'wol';
const { ProcessingManager, httpgetProcessor, httprestProcessor, httpgetSoapProcessor, httppostProcessor, cliProcessor, staticProcessor, webSocketProcessor, socketIOProcessor, jsontcpProcessor, mqttProcessor, replProcessor } = require('./ProcessingManager');
const { metaMessage, LOG_TYPE } = require("./metaMessage");
const processingManager = new ProcessingManager();
const myHttpgetProcessor = new httpgetProcessor();
const myHttpgetSoapProcessor = new httpgetSoapProcessor();
const myHttppostProcessor = new httppostProcessor();
const myCliProcessor = new cliProcessor();
const myStaticProcessor = new staticProcessor();
const myWebSocketProcessor = new webSocketProcessor();
const mySocketIOProcessor = new socketIOProcessor();
const myJsontcpProcessor = new jsontcpProcessor();
const myMqttProcessor = new mqttProcessor();
const myReplProcessor = new replProcessor();
const myHttprestProcessor = new httprestProcessor();
//LOGGING SETUP AND WRAPPING
//Disable the NEEO library console warning.
console.error = console.info = console.debug = console.warn = console.trace = console.dir = console.dirxml = console.group = console.groupEnd = console.time = console.timeEnd = console.assert = console.profile = function() {};
function metaLog(message) {
let initMessage = { component:'metaController', type:LOG_TYPE.INFO, content:'', deviceid: null };
let myMessage = {...initMessage, ...message}
return metaMessage (myMessage);
}
module.exports = function controller(driver) {
this.buttons = []; //structure keeping all buttons of the driver
this.sendComponentUpdate;
this.name = driver.name;
this.vault = new variablesVault();
this.listeners = []; //container for all device listeners.
this.connectionH = []; //helper for all connections.
this.imageH = []; //image helper to store all the getter of the dynamically created images.
this.sensorH = []; //sensor helper to store all the getter and setter of the dynamically created sensors.
this.switchH = []; //sensor switch to store all the getter and setter of the dynamically created switches.
this.labelH = []; //label helper to store all the getter and setter of the dynamically created labels.
this.sliderH = []; //slider helper to store all the getter and setter of the dynamically created sliders.
this.directoryH = []; //directory helper to store all the browse getter and setter of the dynamically created simple directories.
var self = this;
this.assignDiscoverHubController = function (theHubController) {//Assign the hub in order to send it the notifications
metaLog({type:LOG_TYPE.VERBOSE, content:'assignDiscoverHubController - ' + theHubController});
self.sendComponentUpdate = theHubController.sendComponentUpdate;
self.connectionH = theHubController.connectionH;
};
this.addListener = function(params) {
params = JSON.parse(self.vault.readVariables(params, params.deviceId));
metaLog({type:LOG_TYPE.VERBOSE, content:'addListener', deviceId:params.deviceId});
metaLog({type:LOG_TYPE.VERBOSE, content:params, deviceId:params.deviceId});
metaLog({type:LOG_TYPE.VERBOSE, content:self.vault.variables, deviceId:params.deviceId});
let listIndent = self.listeners.findIndex((listen) => {return listen.command == params.command});
if (listIndent < 0) {//the command is new.
if (params.evalwrite) {
params.evalwrite.forEach(pEw => {//for dynamic devices, tracking of which variables to write on.
pEw.deviceId = params.deviceId;
})
}
if (params.evaldo) {
params.evaldo.forEach(pEd => {//for dynamic devices, tracking of which variables to write on.
pEd.deviceId = params.deviceId;
})
}
self.listeners.push(params);
}
else {//we forbid addition of a new duplicate command to listen and we add the evalwrite conditions instead.
if (params.evalwrite) {
params.evalwrite.forEach(pEw => {
let ewI = self.listeners[listIndent].evalwrite.findIndex((ew) => {return ((ew.variable == pEw.variable) && (ew.deviceId == pEw.deviceId))});
if (ewI < 0) {//prevent duplicate evalwrite
pEw.deviceId = params.deviceId; //for dynamic devices, tracking of which variables to write on.
self.listeners[listIndent].evalwrite.push(pEw);
}
});
}
if (params.evaldo) {
params.evaldo.forEach(pEd => {
metaLog({type:LOG_TYPE.VERBOSE, content:'Trying to add a new listener evaldo' + pEd});
let edI = self.listeners[listIndent].evaldo.findIndex((ed) => {return ((ed.variable == pEd.variable) && (ed.deviceId == pEd.deviceId))});
if (edI < 0) {//prevent duplicate evalwrite
pEd.deviceId = params.deviceId; //for dynamic devices, tracking of which variables to write on.
self.listeners[listIndent].evaldo.push(pEd);
}
});
}
}
}
this.addConnection = function(params) {
metaLog({type:LOG_TYPE.VERBOSE, content:'addConnection:'});
metaLog({type:LOG_TYPE.VERBOSE, content:params});
self.connectionH.push(params);
};
this.addButton = function(deviceId, name, value) {
self.buttons.push({'deviceId':deviceId, 'name':name,'value':value});
};
this.addImageHelper = function(deviceId, imageName, listened) {//function called by the MetaDriver to store
const indent = self.imageH.findIndex((elt) => {return (elt.name == imageName && elt.deviceId == deviceId);});
if (indent<0) { //add only if not existant
const newImageH = new imageHelper(deviceId, imageName, listened, self);
self.imageH.push(newImageH);
return self.imageH[self.imageH.length-1];
}
else {return self.imageH[indent];}
};
this.addLabelHelper = function(deviceId, labelName, listened, actionListened) {//function called by the MetaDriver to store
const indent = self.labelH.findIndex((elt) => {return (elt.name == labelName && elt.deviceId == deviceId);});
if (indent<0) { //add only if not existant
const newLabelH = new labelHelper(deviceId, labelName, listened, self, actionListened);
self.labelH.push(newLabelH);
return self.labelH[self.labelH.length-1];
}
else {return self.labelH[indent];}
};
this.addSensorHelper = function(deviceId, sensorName, listened) {//function called by the MetaDriver to store
const indent = self.sensorH.findIndex((elt) => {return (elt.name == sensorName && elt.deviceId == deviceId);});
if (indent<0) { //add only if not existant
const newSensorH = new sensorHelper(deviceId, sensorName, listened, self);
self.sensorH.push(newSensorH);
return self.sensorH[self.sensorH.length-1];
}
else {return self.sensorH[indent];}
};
this.addSwitchHelper = function(deviceId, switchName, listen, evaldo) {//function called by the MetaDriver to store
const indent = self.switchH.findIndex((elt) => {return (elt.name == switchName && elt.deviceId == deviceId);});
if (indent<0) { //add only if not existant
const newSwitchH = new switchHelper(deviceId, switchName, listen, evaldo, self);
self.switchH.push(newSwitchH);
return self.switchH[self.switchH.length-1];
}
else {return self.switchH[indent];}
};
this.addSliderHelper = function(deviceId, listen, evaldo, slidername) {//function called by the MetaDriver to store
const indent = self.sliderH.findIndex((elt) => {return (elt.name == slidername && elt.deviceId == deviceId);});
if (indent<0) { //add only if not existant
const newSliderH = new sliderHelper(deviceId, listen, evaldo, slidername, self);
self.sliderH.push(newSliderH);
return self.sliderH[self.sliderH.length-1];
}
else {return self.sliderH[indent];}
};
this.addDirectoryHelper = function(deviceId, dirname) {//function called by the MetaDriver to store the features of the list
const indent = self.directoryH.findIndex((elt) => {return (elt.name == dirname && elt.deviceId == deviceId);});
if (indent<0) { //add only if not existant
const newDirectoryH = new directoryHelper(deviceId, dirname, self);
self.directoryH.push(newDirectoryH);
return self.directoryH[self.directoryH.length-1];
}
else {return self.directoryH[indent];}
};
this.dynamicallyAssignSubscription = function(deviceId) {
metaLog({type:LOG_TYPE.VERBOSE, content:'dynamicallyAssignSubscription', deviceId:deviceId});
// self.registerInitiationCallback(self.discoverHubController.updateFunction);
//self.discoverHubController.updateFunction
};
this.registerInitiationCallback = function(deviceId) {//technical function called at device initiation to start some listeners
metaLog({type:LOG_TYPE.VERBOSE, content:'Initialisation process. ', deviceId:deviceId});
self.initialise(deviceId);
};
this.assignTo = function(Pattern, inputChain, givenResult) //Assign a value to the input chain. Pattern found is replaced by given value
{
try {
if (givenResult && !(typeof(givenResult) in {'string':'', 'number':'', 'boolean':''}) ) {//in case the response is a json object, convert to string
givenResult = JSON.stringify(givenResult);
}
if (typeof(inputChain) == 'string') {
if (inputChain.startsWith('DYNAMIK ')) {
if (givenResult && (typeof(givenResult) == 'string' )) {
givenResult = givenResult.replace(/\\/g, '\\\\'); // Absolutely necessary to properly escape the escaped character. Or super tricky bug.
givenResult = givenResult.replace(/"/g, '\\"'); // Absolutely necessary to properly escape the escaped character. Or super tricky bug.
givenResult = givenResult.replace(/(\r\n|\n|\r)/gm,''); //Management of NAIM issue but should be useful in general.
}
while (inputChain != inputChain.replace(Pattern, givenResult)) {
inputChain = inputChain.replace(Pattern, givenResult);
}
metaLog({type:LOG_TYPE.VERBOSE, content:'Assign To Before Eval. ' + inputChain});
let evaluatedValue = eval(inputChain.split('DYNAMIK ')[1]);
metaLog({type:LOG_TYPE.VERBOSE, content:'Assign To After Eval. ' + evaluatedValue});
return evaluatedValue;
}
else {
inputChain = inputChain.replace(Pattern, givenResult);
return inputChain;
}
}
return inputChain;
}
catch (err) {
metaLog({type:LOG_TYPE.ERROR, content:'META found an error in the DYNAMIK Function created with ('+Pattern+', '+inputChain+', '+givenResult+'). Error: '});
metaLog({type:LOG_TYPE.ERROR, content:err});
}
};
this.evalWrite = function (evalwrite, result, deviceId) {
metaLog({type:LOG_TYPE.VERBOSE, content:'Processing evalwrite with result ' + result, deviceId:deviceId});
metaLog({type:LOG_TYPE.VERBOSE, content:evalwrite, deviceId:deviceId});
if (evalwrite) { //case we want to write inside a variable
evalwrite.forEach(evalW => {
if (evalW.deviceId) {deviceId = evalW.deviceId} //this is specific for listeners and discovery, when one command should be refreshing data of multiple devices (example hue bulbs)
//process the value
let finalValue = self.vault.readVariables(evalW.value, deviceId);
finalValue = self.assignTo(RESULT, finalValue, result);
metaLog({type:LOG_TYPE.VERBOSE, content:"Value to EvalWrite: " + finalValue, deviceId:deviceId});
self.vault.writeVariable(evalW.variable, finalValue, deviceId);
});
}
};
this.evalDo = function (evaldo, result, deviceId) {
if (evaldo) { //case we want to trigger a button
evaldo.forEach(evalD => {
if (evalD.test == '' || evalD.test == true) {evalD.test = true;} //in case of no test, go to the do function
let finalDoTest = self.vault.readVariables(evalD.test, deviceId);// prepare the test to assign variable and be evaluated.
finalDoTest = self.assignTo(RESULT, finalDoTest, result);
if (finalDoTest) {
if (evalD.then && evalD.then != '')
{
let finalDoThen = self.vault.readVariables(evalD.then, deviceId);
finalDoThen = self.assignTo(RESULT, finalDoThen, result);
self.onButtonPressed(finalDoThen, deviceId);
}
}
else {
if (evalD.or && evalD.or != '')
{
let finalDoOr = self.vault.readVariables(evalD.or, deviceId);
finalDoOr = self.assignTo(RESULT, finalDoOr, result);
self.onButtonPressed(finalDoOr, deviceId);
}
}
});
}
};
this.reInitVariablesValues = function(deviceId) {//it is to make sure that all variable have been interpreted after the register process
self.vault.variables.forEach(element => {
element.value = self.vault.readVariables(element.value, deviceId);
});
};
//TODO SUPPRESS IF NOT USEFULL
this.reInitConnectionsValues = function(deviceId) {//it is to make sure that all variable have been interpreted after the register process
self.connectionH.forEach(element => {
// element.descriptor = self.vault.readVariables(element.descriptor, deviceId);
});
};
this.getConnection = function(commandtype) {
if (self.connectionH) {
return self.connectionH[self.connectionH.findIndex((item) => { return (item.name==commandtype); })];
}
else {return null;}
};
this.assignProcessor = function(commandtype) {
if (commandtype == HTTPGET) {
processingManager.processor = myHttpgetProcessor;
}
else if (commandtype == HTTPREST) {
processingManager.processor = myHttprestProcessor;
}
else if (commandtype == HTTPGETSOAP) {
processingManager.processor = myHttpgetSoapProcessor;
}
else if (commandtype == HTTPPOST) {
processingManager.processor = myHttppostProcessor;
}
else if (commandtype == STATIC) {
processingManager.processor = myStaticProcessor;
}
else if (commandtype == CLI) {
processingManager.processor = myCliProcessor;
}
else if (commandtype == WEBSOCKET) {
processingManager.processor = myWebSocketProcessor;
}
else if (commandtype == SOCKETIO) {
processingManager.processor = mySocketIOProcessor;
}
else if (commandtype == JSONTCP) {
processingManager.processor = myJsontcpProcessor;
}
else if (commandtype == MQTT) {
processingManager.processor = myMqttProcessor;
}
else if (commandtype == REPL) {
processingManager.processor = myReplProcessor;
}
else {metaLog({type:LOG_TYPE.ERROR, content:'Error in meta settings: The commandtype to process is not defined: ' + commandtype, deviceId:deviceId});}
};
this.initiateProcessor = function(commandtype) { // Initiate communication protocoles
return new Promise(function (resolve, reject) {
self.assignProcessor(commandtype); //to get the correct processing manager.
processingManager.initiate(self.getConnection(commandtype))
.then((result) => {
resolve(result);
})
.catch((err) => {
metaLog({type:LOG_TYPE.ERROR, content:'Error during initiation with commandtype : ' + commandtype, deviceId:deviceId});
metaLog({type:LOG_TYPE.ERROR, content:err});
reject (err);
});
});
};
this.wrapUpProcessor = function(commandtype, deviceId) { // close communication protocoles
return new Promise(function (resolve, reject) {
self.assignProcessor(commandtype); //to get the correct processing manager.
processingManager.wrapUp(self.getConnection(commandtype))
.then((result) => {
resolve(result);
})
.catch((err) => {reject (err);});
});
};
this.commandProcessor = function(command, commandtype, deviceId) { // process any command according to the target protocole
return new Promise(function (resolve, reject) {
self.assignProcessor(commandtype);
const connection = self.getConnection(commandtype);
command = self.vault.readVariables(command, deviceId);
command = self.assignTo(RESULT, command, '');
const params = {'command' : command, 'connection' : connection};
metaLog({type:LOG_TYPE.VERBOSE, content:'Final command to be processed: '+command+ ' - ' + commandtype, deviceId:deviceId});
processingManager.process(params)
.then((result) => {
metaLog({type:LOG_TYPE.VERBOSE, content:'Result of the command to be processed: '+result, deviceId:deviceId});
resolve(result);
})
.catch((err) => {reject (err);});
});
};
this.listenProcessor = function(command, commandtype, listener, deviceId) { // process any command according to the target protocole
return new Promise(function (resolve, reject) {
self.assignProcessor(commandtype);
//TODO WARNING BEFORE WAS CONST, SEE IMPACT
let connection = self.getConnection(commandtype);
command = self.vault.readVariables(command, deviceId);
let params = {'command' : command, 'listener' : listener, '_listenCallback' : self.onListenExecute, 'connection' : connection};
processingManager.startListen(params, deviceId)
.then((result) => {
resolve(result);
})
.catch((err) => {reject (err);});
});
};
this.stopListenProcessor = function(listener, deviceId) { // process any command according to the target protocole
return new Promise(function (resolve, reject) {
if (listener.deviceId == deviceId) {
self.assignProcessor(listener.type);
let connection = self.getConnection(listener.commandtype);
processingManager.stopListen(listener, connection);
}
else {
metaLog({type:LOG_TYPE.WARNING, content:'Trying to stop a listener from the wrong device', deviceId:deviceId});
}
});
};
this.queryProcessor = function (data, query, commandtype, deviceId) { // process any command according to the target protocole
return new Promise(function (resolve, reject) {
self.assignProcessor(commandtype);
metaLog({type:LOG_TYPE.VERBOSE, content:'Query Processor : ' + query, deviceId:deviceId});
let myQueryT = [];
const promiseT = [];
if (!Array.isArray(query)) {
myQueryT.push(query);
}
else {
myQueryT = query;
}
for (let index = 0; index < myQueryT.length; index++) { //process all the query result in parallele.
const mypromise = new Promise ((resolve, reject) => {
myQueryT[index] = self.vault.readVariables(myQueryT[index], deviceId);
const params = {'query' : myQueryT[index], 'data' : data};
processingManager.query(params).then((data) => {
resolve(data);
});
});
promiseT.push(mypromise);
}
Promise.all(promiseT).then((values) => {
metaLog({type:LOG_TYPE.VERBOSE, content:'Result of all query processors : ' + values, deviceId:deviceId});
if (values.length == 1) {
resolve(values[0]);
}
else {
const result = [];
for (let index = 0; index < values[0].length; index++) {
const cell = [];
for (let index2 = 0; index2 < values.length; index2++) {
cell.push(values[index2][index]);
}
result.push(cell);
}
resolve(result);
}
});
});
};
this.onListenExecute = function (result, listener, deviceId) {
metaLog({type:LOG_TYPE.VERBOSE, content:'Event received', deviceId:deviceId});
metaLog({type:LOG_TYPE.VERBOSE, content:result, deviceId:deviceId});
self.queryProcessor(result, listener.queryresult, listener.type, deviceId).then((result) => {
if (listener.evalwrite) {self.evalWrite(listener.evalwrite, result, deviceId);}
if (listener.evaldo) {self.evalDo(listener.evaldo, result, deviceId);}
});
};
this.listenStart = function (listener, deviceId) {
return new Promise(function (resolve, reject) {
try {
if (listener.deviceId == deviceId) {
metaLog({type:LOG_TYPE.VERBOSE, content:'Initialising the listener:' + listener.type, deviceId:deviceId});
metaLog({type:LOG_TYPE.VERBOSE, content:listener.command, deviceId:deviceId});
self.listenProcessor(listener.command, listener.type, listener, deviceId);
}
else {
metaLog({type:LOG_TYPE.ERROR, content:'Trying to start a listener which is not from the right device.', deviceId:deviceId});
}
}
catch (err) {reject('Error when starting to listen. ' + err);}
});
};
this.actionManager = function (deviceId, commandtype, command, queryresult, evaldo, evalwrite) {
return new Promise(function (resolve, reject) {
try {
metaLog({type:LOG_TYPE.VERBOSE, content:'ActionManager, command: '+command+ ' - ' + commandtype, deviceId:deviceId});
self.commandProcessor(command, commandtype, deviceId)
.then((result) => {
self.queryProcessor(result, queryresult, commandtype, deviceId).then((result) => {
if (Array.isArray(result) && !Array.isArray(queryresult)) {//For compatibility transform to single value override by making query result a table
result = result[0];
}
if (evalwrite) {self.evalWrite(evalwrite, result, deviceId);}
if (evaldo) {self.evalDo(evaldo, result, deviceId);}
resolve(result);
});
})
.catch((result) => { //if the command doesn't work.
result = 'Command failed:' + result;
if (evalwrite) {self.evalWrite(evalwrite, result, deviceId);}
if (evaldo) {self.evalDo(evaldo, result, deviceId);}
resolve('Error during the post command processing' + result);
});
}
catch {reject('Error while processing the command.');}
});
};
this.initialise = function(deviceId) {
metaLog({type:LOG_TYPE.VERBOSE, content:'Initialising the device driver.', deviceId:deviceId});
self.sliderH.forEach((helper) => {if (helper.deviceId == deviceId) {helper.initialise(deviceId);}});//No need to cleanup as double addition is protected
self.switchH.forEach((helper) => {if (helper.deviceId == deviceId) {helper.initialise(deviceId);}});//No need to cleanup as double addition is protected
self.imageH.forEach((helper) => {if (helper.deviceId == deviceId) {helper.initialise(deviceId);}});//No need to cleanup as double addition is protected
self.labelH.forEach((helper) => {if (helper.deviceId == deviceId) {helper.initialise(deviceId);}});//No need to cleanup as double addition is protected
self.sensorH.forEach((helper) => {if (helper.deviceId == deviceId) {helper.initialise(deviceId);}});//No need to cleanup as double addition is protected
self.connectionH.forEach(connection => {//open all driver connections type
self.initiateProcessor(connection.name);
});
self.listeners.forEach(listener => {
if (listener.deviceId == deviceId) {//we start only the listeners of this device !!!
self.listenStart(listener, deviceId);
}
});
};
this.onButtonPressed = function(name, deviceId) {
return new Promise(function (resolve, reject) {
metaLog({type:LOG_TYPE.VERBOSE, content:'[CONTROLLER] - ' + name + ' - button pressed', deviceId:deviceId});
if (name == '__INITIALISE') {//Device resources and connection management.
self.initialise(deviceId);
}
if (name == '__CLEANUP') {//listener management to listen to other devices. Stop listening on power off.
self.listeners.forEach(listener => {
if (listener.deviceId == deviceId) {//we stop only the listeners of this device !!!
self.stopListenProcessor(listener, deviceId);
}
});
self.connectionH.forEach(connection => {
self.wrapUpProcessor(connection.name);
});
}
if (name == '__PERSIST') {//Device resources and connection management.
self.vault.snapshotDataStore();
}
let theButton = self.buttons[self.buttons.findIndex((button) => {return button.name == name && button.deviceId == deviceId;})];
if (theButton != undefined) {
theButton = theButton.value;
if (theButton.type != WOL) { //all the cases
if (!name.startsWith(BUTTONHIDE)) {
self.commandProcessor("{\"topic\":\""+ settings.mqtt_topic + self.name + "/" + deviceId + "/button/" + name + "\",\"message\":\"PRESSED\"}", MQTT, deviceId)
}
self.actionManager(deviceId, theButton.type, theButton.command, theButton.queryresult, theButton.evaldo, theButton.evalwrite)
.then(()=>{
metaLog({type:LOG_TYPE.VERBOSE, content:'Action done.', deviceId:deviceId});
resolve('Action done.');
})
.catch((err) => {
metaLog({type:LOG_TYPE.ERROR, content:'Error when processing the command : ' + err, deviceId:deviceId});
resolve(err);
});
}
else if (theButton.type == 'wol') {
resolve("wol");
wol.wake(theButton.command, function(error) {
if (error) {
} else {
// done sending packets
}
});
//var magic_packet = wol.createMagicPacket(theButton.command);
}
}
else {resolve("no real button pressed")}
})
};
};