-
Notifications
You must be signed in to change notification settings - Fork 16
/
main.js
1291 lines (1124 loc) · 46.4 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
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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* 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();
const phonebook = require('./lib/phonebook');
const CallMonitor = require('./lib/callmonitor');
const callList = require('./lib/calllist');
const Deflections = require('./lib/deflections');
const Devices = require('./lib/devices');
const tr064Lib = require('tr-O64');
let tr064Client;
let deflections;
const commandDesc = 'eg. { "service": "urn:dslforum-org:service:WLANConfiguration:1", "action": "X_AVM-DE_SetWPSConfig", "params": { "NewX_AVM-DE_WPSMode": "pbc", "NewX_AVM-DE_WPSClientPIN": "" } }';
let callbackTimers = {};
let pollingTimer = null;
let ringTimeout = null;
let initError = false;
let adapter;
let devices;
let callMonitor;
let refreshCalllistTimeout = null;
// extract from object the attribute by path like "attr1.attr2.subAttr3"
function getProp(obj, propString) {
if (!obj) {
return undefined;
}
const ar = propString.split('.');
const len = ar.length;
for (let i = 0; i < len; i++) {
obj = obj[ar[i]];
if (obj === undefined) {
return undefined;
}
}
return obj;
}
function hasProp(obj, propString) {
if (!obj) {
return false;
}
const ar = propString.split('.');
const len = ar.length;
for (let i = 0; i < len; i++) {
obj = obj[ar[i]];
if (obj === undefined) {
return false;
}
}
return true;
}
function callbackOrTimeout(timeout, callback) {
if (typeof timeout === 'function') {
const cb = timeout;
timeout = callback;
callback = cb;
}
const id = Date.now() + '_' + Math.round(Math.random() * 10000);
callbackTimers[id] = setTimeout(() => {
callback('timeout', null);
callback = null;
delete callbackTimers[id];
}, timeout);
return function(err, data) {
if (callbackTimers[id]) {
clearTimeout(callbackTimers[id]);
delete callbackTimers[id];
}
return callback && callback(err, data);
};
}
function startAdapter(options) {
options = options || {};
Object.assign(options, {name: adapterName});
adapter = new utils.Adapter(options);
adapter.on('message', obj => obj && onMessage(obj));
adapter.on('stateChange', (id, state) => {
if (state && id.startsWith(adapter.namespace + '.')) {
if (initError) {
adapter.log.error('tr-064 adapter not connected to a FritzBox. Terminating');
return adapter.terminate ? adapter.terminate('tr-064 adapter not connected to a FritzBox. Terminating', 1) : setTimeout(() => process.exit(1), 2000);
}
adapter.log.debug('State changed: ' + id + ' = ' + JSON.stringify(state));
if (!state.ack) {
onStateChange(id, state);
} else if (adapter.config.calllists.use && id.includes('callmonitor.lastCall.timestamp')) {
// If multiple updates come we wait for 100ms stability
refreshCalllistTimeout && clearTimeout(refreshCalllistTimeout);
refreshCalllistTimeout = setTimeout(() => {
refreshCalllistTimeout = null;
tr064Client.refreshCalllist();
}, 100);
}
}
});
adapter.on('ready', () => {
devices = new Devices(adapter);
adapter.getForeignObject('system.config', (err, systemConfig) => {
if (adapter.config.password && (!adapter.supportsFeature || !adapter.supportsFeature('ADAPTER_AUTO_DECRYPT_NATIVE'))) {
adapter.config.password = adapter.decrypt((systemConfig && systemConfig.native && systemConfig.native.secret) || 'Zgfr56gFe87jJOM', adapter.config.password);
}
// eslint-disable-next-line no-control-regex
if (/[\x00-\x08\x0E-\x1F\x80-\xFF]/.test(adapter.config.password)) {
adapter.log.error('Password error: Please re-enter the password in Admin. Stopping');
return;
}
main(adapter);
});
});
adapter.on('unload', callback => {
try {
pollingTimer && clearTimeout(pollingTimer);
pollingTimer = null;
ringTimeout && clearTimeout(ringTimeout);
ringTimeout = null;
Object.keys(callbackTimers).forEach(id => clearTimeout(callbackTimers[id]));
callbackTimers = {};
callMonitor && typeof callMonitor.close === 'function' && callMonitor.close();
callMonitor = null;
callback && callback();
} catch (err) {
callback && callback();
}
});
return adapter;
}
const CHANNEL_STATES = 'states';
const CHANNEL_DEVICES = 'devices';
const CHANNEL_PHONEBOOK = 'phonebook';
const CHANNEL_CALLLISTS = 'calllists';
const CHANNEL_CALLMONITOR = 'callmonitor';
let devStates;
let allDevices = [];
const ipActive = {};
const states = {
wps: {name: 'wps', val: false, common: {}, native: {func: 'setWPSMode'}},
wlan: {name: 'wlan', val: false, common: {desc: 'All WLANs'}, native: {func: 'setWLAN'}},
wlan24: {name: 'wlan24', val: true, common: {desc: '2.4 GHz WLAN'}, native: {func: 'setWLAN24'}},
wlan50: {name: 'wlan50', val: true, common: {desc: '5.0 GHz WLAN'}, native: {func: 'setWLAN50'}},
wlanGuest: {name: 'wlanGuest', val: true, common: {desc: 'Guest WLAN'}, native: {func: 'setWLANGuest'}},
wlan24Password: {
name: 'wlan24Password',
val: '',
common: {desc: 'Passphrase for 2.4 GHz WLAN'},
native: {func: 'setWLAN24Password'}
},
wlan50Password: {
name: 'wlan50Password',
val: '',
common: {desc: 'Passphrase for 5.0 GHz WLAN'},
native: {func: 'setWLAN50Password'}
},
wlanGuestPassword: {
name: 'wlanGuestPassword',
val: '',
common: {desc: 'Passphrase for Guest WLAN'},
native: {func: 'setWLANGuestPassword'}
},
abIndex: {name: 'abIndex', val: 0, common: {}, native: {func: 'setABIndex'}},
ab: {name: 'ab', val: false, common: {desc: 'parameter: index, state'}, native: {func: 'setAB'}},
ring: {
name: 'ring',
val: '**610',
common: {desc: 'let a phone ring. Parameter is phonenumber [,duration]. eg. **610'},
native: {func: 'ring'}
},
reconnectInternet: {name: 'reconnectInternet', val: false, common: {role: 'button', read: false, write: true}, native: {func: 'reconnectInternet'}},
command: {name: 'command', val: '', native: {func: 'command', desc: commandDesc}},
commandResult: {name: 'commandResult', val: '', common: {write: false}},
externalIP: {name: 'externalIP', val: '', common: {write: false}},
externalIPv6: {name: 'externalIPv6', val: '', common: {write: false}},
externalIPv6Prefix: {name: 'externalIPv6Prefix', val: '', common: {write: false}},
reboot: {name: 'reboot', val: false, common: {role: 'button', read: false, write: true}, native: {func: 'reboot'}}
};
const pbStates = {
pbNumber: {name: 'number', val: '', common: {name: 'Number'}},
pbName: {name: 'name', val: '', common: {name: 'Name'}},
pbImageUrl: {name: 'image', val: '', common: {name: 'Image URL'}}
// ringing: { name: 'ringing', val: false, common: { name: 'Ringing'} }
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
String.prototype.normalizeNumber = function () {
return this.replace (/\+/g, '00').replace(/[^0-9*]/g, '');
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function createObjects(cb) {
//devStates = new devices.CDevice(0, '');
devStates.setDevice(CHANNEL_CALLLISTS, {common: {name: 'Call lists', role: 'device'}, native: {}});
if (adapter.config.calllists.use) {
const htmlTemplate = systemData.native.callLists.htmlTemplate || '';
adapter.log.debug('Initialize HTML template: ' + htmlTemplate);
devices.root.createNew(callList.S_HTML_TEMPLATE, htmlTemplate);
}
devStates.setDevice(CHANNEL_DEVICES, {common: {name: 'Devices', role: 'device'}, native: {}});
devStates.setDevice(CHANNEL_CALLMONITOR, {common: {name: 'Call monitor', role: 'device'}, native: {}});
devStates.setDevice(CHANNEL_PHONEBOOK, {common: {name: 'Phone book', role: 'device'}, native: {}});
for (const i in pbStates) {
const st = Object.assign({}, pbStates[i]);
devStates.createNew(st.name, st);
}
devStates.setDevice(CHANNEL_STATES, {common: {name: 'States and commands', role: 'device'}, native: {}});
for (const i in states) {
if (i.startsWith('wlan50') && !tr064Client.wlan50 && tr064Client.wlanGuest) {
continue;
}
const st = Object.assign({}, states[i]);
devStates.createNew(st.name, st);
}
devices.update(cb);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function onMessage(obj) {
let onlyActive;
let reread;
adapter.log.debug('onMessage: ' + JSON.stringify(obj));
switch (obj.command) {
case 'discovery': {
if (typeof obj.message === 'object') {
onlyActive = obj.message.onlyActive;
reread = obj.message.reread;
}
if (!obj.callback) {
return false;
}
if (!reread && allDevices.length > 0 && allDevices.onlyActive === onlyActive) {
adapter.log.debug('Discovery result: ' + JSON.stringify(allDevices));
adapter.sendTo(obj.from, obj.command, JSON.stringify(allDevices), obj.callback);
return true;
}
const newAllDevices = [];
newAllDevices.onlyActive = onlyActive;
let responseSent = false;
tr064Client.forEachHostEntry((err, device, cnt, all) => {
const active = !!(~~device.NewActive);
if (!onlyActive || active) {
newAllDevices.push({
name: device.NewHostName,
ip: device.NewIPAddress,
mac: device.NewMACAddress,
active: active
});
}
adapter.log.debug('Discovery Add (' + cnt + '/' + all + '): ' + device.NewHostName + ' ' + device.NewIPAddress + ' ' + device.NewMACAddress + ' ' + device.NewActive);
if (cnt + 1 >= all && !responseSent) {
responseSent = true;
allDevices = newAllDevices;
adapter.log.debug('Discovery result: ' + JSON.stringify(allDevices));
adapter.sendTo(obj.from, obj.command, JSON.stringify(newAllDevices), obj.callback);
}
});
return true;
}
default:
adapter.log.warn('Unknown command: ' + obj.command);
break;
}
obj.callback && adapter.sendTo(obj.from, obj.command, obj.message, obj.callback);
return true;
}
function onStateChange(id, state) {
if (!state) {
return;
}
const as = id.split('.');
if (as.length < 3) {
return;
}
const cmd = as [3];
let func;
switch(as[2]) {
case CHANNEL_STATES:
func = states[cmd] && states[cmd].native ? states[cmd].native.func : null;
if (func && tr064Client[func] && state.val !== null && state.val !== undefined) {
const ret = tr064Client[func](state.val, () => {});
if (ret === true) {
devices.root.clear(id);
}
}
break;
case CHANNEL_CALLLISTS:
case callList.ROOT:
if (cmd === 'htmlTemplate') {
if (state.val) {
systemData.native.callLists.htmlTemplate = state.val.toString();
}
} else if (as[4] === 'count') {
systemData.native.callLists[cmd][as[4]] = ~~state.val;
// save system data in namespace
adapter.setObject(adapter.namespace, systemData);
}
return;
case CHANNEL_PHONEBOOK:
if (state.val) {
onPhonebook(cmd, state.val);
}
return;
// case CHANNEL_DEVICES:
// case CHANNEL_CALLMONITOR:
// return;
case Deflections.CHANNEL_DEFLECTIONS:
deflections && deflections.onStateChange(cmd, as[4], state.val);
break;
default:
return;
}
}
function setPhonebookStates(v) {
devices.root.set(`.${CHANNEL_PHONEBOOK}.number`, (v && v.number) ? v.number : '');
devices.root.set(`.${CHANNEL_PHONEBOOK}.name`, (v && v.name) ? v.name : '');
devices.root.set(`.${CHANNEL_PHONEBOOK}.image`, (v && v.imageurl) ? v.imageurl : '');
devices.update();
}
function onPhonebook(cmd, val) {
if (!adapter.config.usePhonebook) {
return;
}
let v;
switch (cmd) {
case 'number':
v = phonebook.byNumber(val);
setPhonebookStates (v);
break;
case 'name':
v = phonebook.byName(val);
setPhonebookStates(v);
break;
case 'command':
break;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function getLastValidPropEx(obj, propString) {
if (!obj) {
return undefined;
}
const ar = propString.split('.');
const len = ar.length;
for (let i = 0; i < len; i++) {
if (obj[ar[i]] === undefined) {
let ret = { obj: {}, invalidName: '', errPath: ''};
try {
ret = {obj: obj, invalidName: ar[i], errPath: ar.slice(i).join('.')};
} catch {
// do nothing
}
return ret;
}
obj = obj[ar[i]];
}
return { obj: {}, invalidName: '', errPath: ''};
}
function safeFunction(root, path, log) {
const cb = getProp(root, path);
if (typeof cb === 'function') {
return cb;
}
if (log) {
const err = getLastValidPropEx(root, path);
if (typeof log !== 'function') {
log = adapter.log.debug;
}
err && log(`${err.errPath} is not a function (${path})`);
}
return function (params, cb) {
if (typeof params === 'function') {
cb = params;
}
if (typeof cb === 'function') {
cb();
} else {
adapter.log.error(new Error(`${path} is not a function`));
}
};
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
const TR064 = function (user, password, ip, port) {
tr064Lib.TR064.call(this);
this.ip = ip;
this.port = port || 49000;
this.user = user;
this.password = password;
this.abIndex = undefined;
};
TR064.prototype = Object.create(tr064Lib.TR064.prototype);
//TR064.prototype.constructor = TR064;
//TR064.prototype.startTransaction = function (callback) {
// callback (null, this.sslDevice);
// //this.sslDevice.startTransaction(callback);
//};
//
//TR064.prototype.stopTransaction = function (callback) {
// callback (null, this.sslDevice);
// //this.sslDevice.startTransaction(callback);
//};
TR064.prototype.setABIndex = function (val, cb) {
if (val === undefined) {
val = this.abIndex;
}
if (val === undefined) {
val = devices.getval('states.abIdex', 0);
}
this.abIndex = val >> 0;
this.getABInfo({NewIndex: this.abIndex}, (err, data) => {
if (err || !data) {
return;
}
devStates.setAndUpdate('ab', !!data.NewEnable, cb);
});
};
TR064.prototype.setAB = function (val) {
let idx = this.abIndex;
if (typeof val === 'string') {
const ar = val.replace(/\s/g, '').split(',');
if (ar && ar.length > 1) {
val = ar[1];
idx = ar[0] >> 0;
}
}
this.setEnableAB({ NewIndex: idx, NewEnable: val ? 1 : 0}, () => {});
};
const systemData = {
type: 'meta',
common: { name: 'tr-064' },
native: {},
load: async function () {
if (this.native.loaded) {
return;
}
try {
const obj = await adapter.getObjectAsync(adapter.namespace);
if (obj && obj.native.loaded) {
delete obj.acl;
Object.assign(this, obj);
}
} catch (err) {
// ignore
}
if (adapter.config.calllists.use) {
if (!this.native.callLists) {
this.native.callLists = new callList.callLists();
} else {
callList.callLists.call(this.native.callLists);
}
let htmlTemplate = null;
try {
const htmlTemplateState = await adapter.getStateAsync(callList.S_HTML_TEMPLATE);
if (htmlTemplateState) {
htmlTemplate = htmlTemplateState.val;
}
} catch (err) {
adapter.log.info('Error when initializing html Template: ' + err);
}
this.native.callLists.htmlTemplate = htmlTemplate;
}
if (!this.native.loaded) {
this.native.loaded = true;
// save system data in namespace
adapter.setObject(adapter.namespace, this);
}
}
};
TR064.prototype.refreshCalllist = function () {
if (!adapter.config.calllists.use) {
return;
}
this.GetCallList((err, data) => {
callList.refresh(err, data, (list, n, html) => {
const id = callList.ROOT + '.' + n;
list.cfg.generateJson && devices.root.set(id + '.json', JSON.stringify(list.array));
devices.root.set(id + '.count', list.count);
list.cfg.generateHtml && devices.root.set(id + '.html', html);
adapter.log.debug('Calllist ' + n + ' regenerated');
}, () => {
devices.root.update();
adapter.log.debug('Calllist states updated');
});
});
};
TR064.prototype.init = function (callback) {
const self = this;
function getSSLDevice(device, callback) {
return callback(null, device);
/* device.startEncryptedCommunication(function (err, sslDevice) {
if (err || !sslDevice) callback(err);
sslDevice.login(self.user, self.password);
callback(null, sslDevice);
});*/
}
self.initTR064Device(self.ip, self.port, function (err, device) {
if (err || !device) {
return (callback(err || '!device'));
}
getSSLDevice(device, function (err, sslDevice) {
if (err || !sslDevice) {
return callback(err);
}
sslDevice.login(self.user, self.password);
self.sslDevice = sslDevice;
self.hosts = sslDevice.services['urn:dslforum-org:service:Hosts:1'];
self.getWLANConfiguration = sslDevice.services['urn:dslforum-org:service:WLANConfiguration:1'];
self.getWLANConfiguration2 = sslDevice.services['urn:dslforum-org:service:WLANConfiguration:2'];
self.getWLANConfiguration3 = getProp(sslDevice.services, 'urn:dslforum-org:service:WLANConfiguration:3');
self.reboot = sslDevice.services['urn:dslforum-org:service:DeviceConfig:1'].actions.Reboot;
self.getConfigFile = sslDevice.services['urn:dslforum-org:service:DeviceConfig:1'].actions['X_AVM-DE_GetConfigFile']; //in: NewX_AVM-DE_Password, NewX_AVM-DE_ConfigFileUrl
//self.WANIPConnection = sslDevice.services["urn:dslforum-org:service:WANIPConnection:1"];
self.GetCallList = safeFunction(sslDevice, 'services.urn:dslforum-org:service:X_AVM-DE_OnTel:1.actions.GetCallList');
//self.refreshCalllist();
self.getABInfo = safeFunction (sslDevice, 'services.urn:dslforum-org:service:X_AVM-DE_TAM:1.actions.GetInfo');
self.setEnableAB = safeFunction (sslDevice, 'services.urn:dslforum-org:service:X_AVM-DE_TAM:1.actions.SetEnable');
self.wlan24 = { setEnable: getProp(self.getWLANConfiguration, 'actions.SetEnable') };
self.wlan50 = { setEnable: getProp(self.getWLANConfiguration2, 'actions.SetEnable') };
self.wlanGuest = { setEnable: getProp(self.getWLANConfiguration3, 'actions.SetEnable') };
self.wlan24.getInfo = getProp(self.getWLANConfiguration, 'actions.GetInfo');
self.wlan50.getInfo = getProp(self.getWLANConfiguration2, 'actions.GetInfo');
self.wlanGuest.getInfo = getProp(self.getWLANConfiguration3, 'actions.GetInfo');
self.wlan24.getSecurityKeys = getProp(self.getWLANConfiguration, 'actions.GetSecurityKeys');
self.wlan24.setSecurityKeys = getProp(self.getWLANConfiguration, 'actions.SetSecurityKeys');
self.wlan50.getSecurityKeys = getProp(self.getWLANConfiguration2, 'actions.GetSecurityKeys');
self.wlan50.setSecurityKeys = getProp(self.getWLANConfiguration2, 'actions.SetSecurityKeys');
self.wlanGuest.getSecurityKeys = getProp(self.getWLANConfiguration3, 'actions.GetSecurityKeys');
self.wlanGuest.setSecurityKeys = getProp(self.getWLANConfiguration3, 'actions.SetSecurityKeys');
if (!self.getWLANConfiguration3 || !self.wlanGuest.getInfo || !self.wlanGuest.setEnable) {
self.wlanGuest.setEnable = self.wlan50.setEnable;
self.wlanGuest.getInfo = self.wlan50.getInfo;
self.wlanGuest.getSecurityKeys = self.wlan50.getSecurityKeys;
self.wlanGuest.setSecurityKeys = self.wlan50.setSecurityKeys;
delete self.wlan50;
}
self.voip = getProp(self.sslDevice, 'services.urn:dslforum-org:service:X_VoIP:1.actions');
// self.getSpecificHostEntry = self.hosts.actions.GetSpecificHostEntry;
// self.getGenericHostEntry = self.hosts.actions.GetGenericHostEntry;
// self.GetSpecificHostEntryExt = self.hosts.actions['X_AVM-DE_GetSpecificHostEntryExt'];
self.getSpecificHostEntry = safeFunction(self, 'hosts.actions.GetSpecificHostEntry');
self.getGenericHostEntry = safeFunction(self, 'hosts.actions.GetGenericHostEntry');
self.GetSpecificHostEntryExt = safeFunction(self, 'hosts.actions.X_AVM-DE_GetSpecificHostEntryExt');
self.GetChangeCounter = safeFunction(self, 'hosts.actions.X_AVM-DE_GetChangeCounter');
//self.hostsDoUpdate = self.hosts.actions ['X_AVM-DE_HostDoUpdate'];
//self.hostsCheckUpdate = self.hosts.actions ['X_AVM-DE_HostCheckUpdate'];
self.stateVariables = {};
if (self.hosts && self.hosts.stateVariables) {
self.stateVariables.HostNumberOfEntries = self.hosts.stateVariables.HostNumberOfEntries;
self.stateVariables.changeCounter = self.hosts.stateVariables['X_AVM-DE_ChangeCounter'];
}
self.initIGDDevice(self.ip, self.port, function (err, device) {
err && adapter.log.error('initIGDDevice:' + err + ' - ' + JSON.stringify(err));
if (!err && device) {
getSSLDevice(device, function (err, sslDevice) {
err && adapter.log.error('getSSLDevice:' + err + ' - ' + JSON.stringify(err));
self.getExternalIPAddress = sslDevice.services['urn:schemas-upnp-org:service:WANIPConnection:1'].actions.GetExternalIPAddress;
self.getExternalIPv6Address = sslDevice.services['urn:schemas-upnp-org:service:WANIPConnection:1'].actions.X_AVM_DE_GetExternalIPv6Address;
self.getExternalIPv6Prefix = sslDevice.services['urn:schemas-upnp-org:service:WANIPConnection:1'].actions.X_AVM_DE_GetIPv6Prefix;
self.reconnectInternet = sslDevice.services['urn:schemas-upnp-org:service:WANIPConnection:1'].actions.ForceTermination;
});
}
});
self.getWLAN(callbackOrTimeout(2000, callback));
});
//}.bind(this));
});
};
TR064.prototype.ring = function (val) {
const self = this;
if (!val) {
return;
}
const ar = val.toString().split(',');
if (!ar || ar.length < 1 || !this.voip) {
return;
}
adapter.log.debug('Ring : ' + JSON.stringify(ar));
safeFunction(this.voip, 'X_AVM-DE_DialNumber', true)({'NewX_AVM-DE_PhoneNumber': ar[0]}, err => {
if (!err) {
if (ar.length >= 2) {
const duration = ar[1].trim() >> 0;
ringTimeout = setTimeout(() => {
adapter.log.debug('End Ring after ' + duration + 's');
ringTimeout = null;
safeFunction(self.voip, 'X_AVM-DE_DialHangup', true)({}, () => {});
}, duration * 1000);
}
} else {
adapter.log.warn('Ring Error: ' + err);
}
});
};
/*
TR064.prototype.dialNumber = function (number, callback) {
this.sslDevice.services['urn:dslforum-org:service:X_VoIP:1'].actions['X_AVM-DE_DialNumber']({
'NewX_AVM-DE_PhoneNumber': number
}, callback);
};
*/
TR064.prototype.forEachHostEntry = function (callback) {
const self = this;
adapter.log.debug('forEachHostEntry');
//self.hosts.actions.GetHostNumberOfEntries(function (err, obj) {
safeFunction(self, 'hosts.actions.GetHostNumberOfEntries')((err, obj) => {
err && adapter.log.error('GetHostNumberOfEntries:' + err + ' - ' + JSON.stringify(err));
if (err || !obj) {
return;
}
const all = obj.NewHostNumberOfEntries >> 0;
adapter.log.debug('forEachHostEntry: all=' + all);
let cnt = 0;
function doIt() {
if (cnt >= all) {
return;
}
//self.getGenericHostEntry({NewIndex: cnt}, function (err, obj) {
safeFunction(self, 'getGenericHostEntry') ({NewIndex: cnt}, (err, obj) => {
err && adapter.log.error('forEachHostEntry: in getGenericHostEntry ' + (cnt) + ':' + err + ' - ' + JSON.stringify(err));
if (err || !obj) {
return;
}
adapter.log.debug('forEachHostEntry cnt=' + cnt + ' ' + obj.NewHostName);
callback(err, obj, cnt++, all);
setTimeout(doIt, 10);
});
}
doIt();
});
};
TR064.prototype.forEachConfiguredDevice = function (callback) {
let i = 0;
const self = this;
adapter.log.debug('forEachConfiguredDevice');
function doIt() {
if (i >= adapter.config.devices.length) {
return callback && callback(null);
}
const dev = adapter.config.devices[i++];
if (dev.mac && dev.mac !== '') {
safeFunction(self, 'getSpecificHostEntry') ({NewMACAddress: dev.mac}, (err, device) => {
if (err && err.code === 500) {
if (dev.lastResult) {
device = dev.lastResult;
device.NewActive = false;
} else {
adapter.log.info(`forEachConfiguredDevice: in GetSpecificHostEntry ${i - 1}(${dev.name}/${dev.mac}) device seems offline but we never saw it since adapter was started:${err} - ${JSON.stringify(err)}`);
device = null;
}
} else if (err) {
adapter.log.warn(`forEachConfiguredDevice: in GetSpecificHostEntry ${i - 1}(${dev.name}/${dev.mac}):${err} - ${JSON.stringify(err)}`);
device = null;
} else {
dev.lastResult = device; // store last result to reuse if device goes offline and error 500 is returned
}
if (device) {
adapter.log.debug('forEachConfiguredDevice: i=' + (i-1) + ' ' + device.NewHostName + ' active=' + device.NewActive);
device.NewMACAddress = dev.mac;
callback(device);
}
setImmediate(doIt);
});
} else {
setImmediate(doIt);
}
}
doIt();
};
TR064.prototype.dumpServices = function (ar) {
let fs;
let doLog;
if (ar && ar.length) {
switch (ar[1]) {
case 'log':
doLog = true;
break;
case 'fs':
fs = require('fs');
break;
}
}
const services = {};
for (const service in this.sslDevice.services) {
services[service] = {actions: {}};
const oService = this.sslDevice.services[service];
if (oService.actions) {
for (const action in oService.actions) {
let v = oService.actions[action];
v = typeof v === 'function' ? 'fn' : v;
services[service].actions[action] = v;
doLog && adapter.log.debug(`${service}.actions.${action}`);
}
}
}
const dump = JSON.stringify(services);
devStates.setAndUpdate(states.commandResult.name, dump);
if (fs) {
let logName = '';
const controllerDir = require(__dirname + '/lib/utils').controllerDir;
const parts = controllerDir.split('/');
if (parts.length > 1 && parts[parts.length - 2] === 'node_modules') {
parts.splice(parts.length - 2, 2);
logName = parts.join('/');
logName += '/log/tr-64-services.json';
} else {
logName = `${__dirname}/../../log/tr-64-services.json`;
}
try {
fs.writeFileSync(logName, dump);
} catch (e) {
adapter.log.error('Cannot write file: ' + logName, dump);
}
}
};
TR064.prototype.command = function (command, callback) {
if (typeof command === 'string' && command.toLowerCase().startsWith('dumpservices')) {
return this.dumpServices(command.toLowerCase().split('.'));
}
let o;
try {
o = JSON.parse(command);
} catch(e) {
return;
} //xxx
if (!o || typeof o.params !== 'object' || o.params === null) {
return;
}
safeFunction(this.sslDevice.services, o.service + '.actions.' + o.action)(o.params, (err, res) => {
if (err || !res) {
adapter.setState(`${CHANNEL_STATES}.${states.commandResult.name}`, JSON.stringify(err||{}), true, callback);
return;
}
adapter.log.info(JSON.stringify(res));
adapter.setState(`${CHANNEL_STATES}.${states.commandResult.name}`, JSON.stringify(res), true, callback);
});
};
TR064.prototype.setWLAN24 = function (val, callback) {
safeFunction(this.wlan24, 'setEnable', true)({NewEnable: val ? 1 : 0 }, callback);
};
TR064.prototype.setWLAN50 = function (val) {
if (!this.wlan50 || !this.wlan50.setEnable) {
return;
}
safeFunction (this.wlan50, 'setEnable', true)({NewEnable: val ? 1 : 0 }, err => {
err && adapter.log.error('getWLANConfiguration2: ' + err + ' - ' + JSON.stringify(err));
//if (!val) setTimeout(function (err, res) {
// this.setWLAN(true, function (err, res) {
// });
//}, 20000);
});
};
TR064.prototype.setWLANGuest = function (val, callback) {
safeFunction(this.wlanGuest, 'setEnable', true) ({NewEnable: val ? 1 : 0}, callback);
};
TR064.prototype.setWLAN = function (val, callback) {
const self = this;
this.setWLAN24(val, function (err, result) {
err && adapter.log.error('setWLAN24: ' + err + ' - ' + JSON.stringify(err));
if (err || !result) {
return callback(-1);
}
self.setWLANGuest(val, function (err) {
err && adapter.log.error('setWLANGuest: ' + err + ' - ' + JSON.stringify(err));
self.setWLAN50(val, callback);
});
});
};
TR064.prototype.setWLANPassword = function (kind, pw, cb) {
const self = this;
if (!hasProp(self, kind + '.getSecurityKeys')) {
return cb && cb(-1);
}
self[kind].getSecurityKeys (function (err, ret) {
if (err || !ret || ret.NewKeyPassphrase === pw) {
return cb && cb(err,ret);
}
ret.NewKeyPassphrase = pw;
self[kind].setSecurityKeys(ret, function (err,ret) {
cb && cb(err, ret);
});
});
};
TR064.prototype.setWLAN24Password = function (val) {
this.setWLANPassword('wlan24', val);
return true;
};
TR064.prototype.setWLAN50Password = function (val) {
this.setWLANPassword('wlan50', val);
return true;
};
TR064.prototype.setWLANGuestPassword = function (val) {
this.setWLANPassword('wlanGuest', val);
return true;
};
TR064.prototype.setWPSMode = function (modeOrOnOff) {
let mode = modeOrOnOff;
if (typeof modeOrOnOff === 'boolean') {
mode = modeOrOnOff ? 'pbc' : 'stop';
}
if (!this.getWLANConfiguration.actions['X_AVM-DE_SetWPSConfig'] || !this.getWLANConfiguration.actions['X_AVM-DE_GetWPSInfo']) {
adapter.log.error('WPS control options not available');
return;
}
this.getWLANConfiguration.actions['X_AVM-DE_SetWPSConfig']({
'NewX_AVM-DE_WPSMode': mode,
'NewX_AVM-DE_WPSClientPIN': ''
}, () =>
this.getWLANConfiguration.actions['X_AVM-DE_GetWPSInfo'](err =>
err && adapter.log.error('X_AVM-DE_GetWPSInfo error: ' + err)));
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
const errorCounts = {};
function _checkError(err, res) {
if (err) {
const code = err.code ? err.code : 'unknown error code';
if (errorCounts[code] && (new Date().getTime() - errorCounts[code]) > 60 * 60 * 1000) {
delete(errorCounts[code]);
}
if (!errorCounts[code]) {
let msg = err.message ? err.message : 'unknown error text';
switch (code >> 0) {
case 401:
msg = 'Authentication error. Check username and password in configuration';
break;
}
adapter.log.error('_checkError: code=' + code + ' msg=' + msg);
//code=unknown error code Device responded with fault Error: Credentials incorrec
errorCounts[code] = new Date().getTime();
}
}
this(err, res);
}
function checkError(cb) {
return _checkError.bind(cb);
}
*/
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TR064.prototype.getWLAN = function (callback) {
//safeFunction(this.wlan24, 'getInfo', true)(checkError(callback));
safeFunction(this.wlan24, 'getInfo', true)(callback);
};
TR064.prototype.getWLAN5 = function (callback) {
if (!this.wlan50 || !this.wlan50.getInfo) {
return;
}
safeFunction(this.wlan50, 'getInfo', true)(callback);
};
TR064.prototype.getWLANGuest = function (callback) {
safeFunction(this.wlanGuest, 'getInfo', true)(callback);
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function isKnownMac(mac) {
return !!adapter.config.devices.find(function (v) {
return v.mac === mac;
});
}
// function deleteUnusedDevices(callback) {
// const ch = adapter.namespace + '.' + CHANNEL_DEVICES;
// adapter.getObjectView('system', 'state', { startkey: ch + '.', endkey: ch + '.\u9999' }, function (err, res) {
// if (err || !res) return;
// const toDelete = [];
// res.rows.forEach(function (o){
// if ((!o.value.native || !o.value.native.mac) && o.id.substr(ch.length+1).indexOf('.') < 0) { // old device, without native.mac
// toDelete.push(o.id);
// }
// if (o.value.native && o.value.native.mac && !isKnownMac(o.value.native.mac)) {
// toDelete.push(o.id);
// }
// });
// toDelete.forEach(function (id) {