-
Notifications
You must be signed in to change notification settings - Fork 22
/
main.js
1427 lines (1196 loc) · 55 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
'use strict';
/*
* Created with @iobroker/create-adapter v1.17.0
*/
// The adapter-core module gives you access to the core ioBroker functions
// you need to create an adapter
const utils = require('@iobroker/adapter-core');
// Load your modules here
const UnifiClass = require('node-unifi');
const jsonLogic = require('./admin/lib/json_logic.js');
class Unifi extends utils.Adapter {
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
constructor(options) {
super({
...options,
name: 'unifi',
});
this.on('ready', this.onReady.bind(this));
this.on('stateChange', this.onStateChange.bind(this));
this.on('unload', this.onUnload.bind(this));
this.controllers = {};
this.objectsFilter = {};
this.settings = {};
this.update = {};
this.clients = {};
this.vouchers = {};
this.dpi = {};
this.statesFilter = {};
this.queryTimeout = null;
this.ownObjects = {};
this.stopped = false;
}
/**
* Is called when adapter received configuration.
*/
async onReady() {
try {
// subscribe to all state changes
this.subscribeStates('*.wlans.*.enabled');
this.subscribeStates('*.vouchers.create_vouchers');
this.subscribeStates('trigger_update');
this.subscribeStates('*.port_table.port_*.port_poe_enabled');
this.subscribeStates('*.port_table.port_*.port_poe_cycle');
this.subscribeStates('*.clients.*.reconnect');
this.subscribeStates('*.clients.*.blocked');
this.subscribeStates('*.devices.*.led_override');
this.subscribeStates('*.devices.*.restart');
this.log.info('UniFi adapter is ready');
// Load configuration
this.settings.updateInterval = (parseInt(this.config.updateInterval, 10) * 1000) || (60 * 1000);
this.settings.controllerIp = this.config.controllerIp;
this.settings.controllerPort = this.config.controllerPort;
this.settings.controllerUsername = this.config.controllerUsername;
this.settings.controllerPassword = this.config.controllerPassword;
this.settings.ignoreSSLErrors = this.config.ignoreSSLErrors !== undefined ? this.config.ignoreSSLErrors : true;
this.update.blacklist = this.config.blacklistClients;
this.update.clients = this.config.updateClients;
this.update.devices = this.config.updateDevices;
this.update.health = this.config.updateHealth;
this.update.networks = this.config.updateNetworks;
this.update.sysinfo = this.config.updateSysinfo;
this.update.vouchers = this.config.updateVouchers;
this.update.vouchersNoUsed = this.config.updateVouchersNoUsed;
this.update.wlans = this.config.updateWlans;
this.update.alarms = this.config.updateAlarms;
this.update.alarmsNoArchived = this.config.updateAlarmsNoArchived;
this.update.dpi = this.config.updateDpi;
this.update.gatewayTraffic = this.config.updateGatewayTraffic;
this.update.gatewayTrafficMaxDays = this.config.gatewayTrafficMaxDays;
// @ts-ignore
this.objectsFilter = this.config.blacklist || this.config.objectsFilter; // blacklist was renamed to objectsFilter in v0.5.3
// @ts-ignore
this.statesFilter = this.config.whitelist || this.config.statesFilter; // blacklist was renamed to statesFilter in v0.5.3
// @ts-ignore
this.clients.isOnlineOffset = (parseInt(this.config.clientsIsOnlineOffset, 10) * 1000) || (60 * 1000);
this.vouchers.number = this.config.createVouchersNumber;
this.vouchers.duration = this.config.createVouchersDuration;
this.vouchers.quota = this.config.createVouchersQuota;
this.vouchers.uploadLimit = !this.config.createVouchersUploadLimit ? null : this.config.createVouchersUploadLimit;
this.vouchers.downloadLimit = !this.config.createVouchersDownloadLimit ? null : this.config.createVouchersDownloadLimit;
this.vouchers.byteQuota = !this.config.createVouchersByteQuota ? null : this.config.createVouchersByteQuota;
this.vouchers.note = this.config.createVouchersNote;
if (this.settings.controllerIp !== '' && this.settings.controllerUsername !== '' && this.settings.controllerPassword !== '') {
// Send some log messages
this.log.debug(`controller = ${this.settings.controllerIp}:${this.settings.controllerPort}`);
this.log.debug(`updateInterval = ${this.settings.updateInterval / 1000}`);
// Start main function
this.updateUnifiData();
} else {
this.log.error('Adapter deactivated due to missing configuration.');
await this.setStateAsync('info.connection', { ack: true, val: false });
this.setForeignState(`system.adapter.${this.namespace}.alive`, false);
}
} catch (err) {
this.handleError(err, undefined, 'onReady');
}
}
/**
* Is called if a subscribed state changes
* @param {string} id
* @param {ioBroker.State | null | undefined} state
*/
async onStateChange(id, state) {
if (state && !state.ack) {
// The state was changed
const idParts = id.split('.');
const site = idParts[2];
const mac = idParts[4];
try {
if (idParts[3] === 'wlans' && idParts[5] === 'enabled') {
await this.updateWlanStatus(site, id, state);
} else if (idParts[3] === 'vouchers' && idParts[4] === 'create_vouchers') {
await this.createUnifiVouchers(site);
} else if (idParts[2] === 'trigger_update') {
await this.updateUnifiData(true);
} else if (idParts[7] === 'port_poe_enabled') {
const portNumber = idParts[6].split('_').pop();
this.switchPoeOfPort(site, mac, portNumber, state.val);
} else if (idParts[7] === 'port_poe_cycle') {
const portNumber = idParts[6].split('_').pop();
const mac = idParts[4];
this.log.info(`onStateChange: port power cycle (port: ${portNumber}, device: ${mac})`);
await this.controllers[site].powerCycleSwitchPort(mac, portNumber);
} else if (idParts[5] === 'reconnect') {
await this.reconnectClient(id, idParts, site);
} else if (idParts[5] === 'blocked') {
await this.blockClient(id, site, idParts, state.val);
} else if (idParts[5] === 'led_override') {
const deviceId = await this.getStateAsync(id.substring(0, id.lastIndexOf('.')) + '.device_id');
this.log.info(`onStateChange: override led to '${state.val}' (device: ${deviceId.val})`);
await this.controllers[site].setLEDOverride(deviceId.val, state.val);
} else if (idParts[5] === 'restart') {
const mac = idParts[4];
this.log.info(`onStateChange: restart device '${mac}'`);
await this.controllers[site].restartDevice(mac, 'soft');
}
} catch (err) {
this.handleError(err, site, 'onStateChange');
}
}
}
/**
* Is called when adapter shuts down - callback has to be called under any circumstances!
* @param {() => void} callback
*/
onUnload(callback) {
try {
this.stopped = true;
if (this.queryTimeout) {
clearTimeout(this.queryTimeout);
}
this.log.info('cleaned everything up...');
callback();
} catch (e) {
callback();
}
}
/**
* Function to handle error messages
* @param {Object} err
* @param {String} site
* @param {String | undefined} methodName
*/
async handleError(err, site, methodName = undefined) {
if (err.message === 'api.err.Invalid') {
this.log.error(`Error site ${site}: Incorrect username or password.`);
} else if (err.message === 'api.err.LoginRequired') {
this.log.error(`Error site ${site}: Login required. Check username and password.`);
} else if (err.message === 'api.err.Ubic2faTokenRequired') {
this.log.error(`Error site ${site}: 2-Factor-Authentication required by UniFi controller. 2FA is not supported by this adapter.`);
} else if (err.message === 'api.err.ServerBusy') {
this.log.error(`Error site ${site}: Server is busy. There seems to be a problem with the UniFi controller.`);
} else if (err.message === 'api.err.NoPermission' || (err.response && err.response.data && err.response.data.meta && err.response.data.meta.msg && err.response.data.meta.msg === 'api.err.NoPermission')) {
this.log.error(`Error site ${site}: Permission denied. Check access rights.`);
} else if (err.message.includes('connect EHOSTUNREACH') || err.message.includes('connect ENETUNREACH')) {
this.log.error(`Error site ${site}: Host or network cannot be reached.`);
} else if (err.message.includes('connect ECONNREFUSED')) {
this.log.error(`Error site ${site}: Connection refused. Incorrect IP or port.`);
} else if (err.message.includes('connect ETIMEDOUT')) {
this.log.error(`Error site ${site}: Connection timedout.`);
} else if (err.message.includes('read ECONNRESET')) {
this.log.error(`Error site ${site}: Connection was closed by the UniFi controller.`);
} else if (err.message.includes('getaddrinfo EAI_AGAIN')) {
this.log.error(`Error site ${site}: This error is not related to the adapter. There seems to be a DNS issue. Please google for "getaddrinfo EAI_AGAIN" to fix the issue.`);
} else if (err.message.includes('getaddrinfo ENOTFOUND')) {
this.log.error(`Error site ${site}: Host not found. Incorrect IP or port.`);
} else if (err.message.includes('socket hang up')) {
this.log.error(`Error site ${site}: Socket hang up: ${err.message}`);
} else if (err.message.includes('socket disconnected')) {
this.log.error(`Error site ${site}: Socket disconnected: ${err.message}`);
} else if (err.message.includes('SSL routines') || err.message.includes('ssl3_') || err.message.includes('certificate has expired')) {
this.log.error(`Error site ${site}: SSL/Certificate issue: ${err.message}`);
} else if (err.message === 'api.err.InvalidArgs' || err.message === 'api.err.IncorrectNumberRange') {
this.log.error(`Parameters for this call are invalid (${err.message})! Please check the parameters`);
} else if (err.message === 'aborted') {
this.log.error(`Request aborted.`);
} else if (err.message.includes('Returned data is not in valid format')) {
this.log.error(err.message);
} else {
if (err.response && err.response.data) {
this.log.error(`Error site ${site} (data): ${JSON.stringify(err.response.data)}`);
}
if (methodName) {
this.log.error(`[${methodName} site ${site}] error: ${err.message}, stack: ${err.stack}`);
} else {
this.log.error(`Error site ${site}: ${err.message}, stack: ${err.stack}`);
}
if (this.supportsFeature && this.supportsFeature('PLUGINS')) {
const sentryInstance = this.getPluginInstance('sentry');
if (sentryInstance) {
sentryInstance.getSentryObject().captureException(err);
}
}
}
}
/**
* Function that takes care of the API calls and processes
* the responses afterwards
*/
async updateUnifiData(preventReschedule = false) {
try {
this.log.debug('Update started');
const defaultController = new UnifiClass.Controller({
host: this.settings.controllerIp,
port: this.settings.controllerPort,
username: this.settings.controllerUsername,
password: this.settings.controllerPassword,
sslverify: !this.settings.ignoreSSLErrors,
timeout: 10000
});
try {
await defaultController.login();
} catch (err) {
this.handleError(err, undefined, 'updateUnifiData-login');
// In case of connection timeout, try again later
if (err.code === 'ECONNABORTED') {
this.queryTimeout = setTimeout(() => {
this.updateUnifiData();
}, this.settings.updateInterval);
}
return;
}
this.log.debug('Login successful');
try {
const sites = await this.fetchSites(defaultController);
for (const site of sites) {
if (this.stopped) {
return;
}
try {
if (!this.controllers[site]) {
if (site === 'default') {
this.controllers[site] = defaultController;
/*
try {
defaultController.onAny((event, data) => {
this.log.debug(`EVENT [${site}] ${event} : ${JSON.stringify(data)}`);
});
await defaultController.listen();
} catch (err) {
this.handleError(err, site, 'subscribe Events');
}*/
} else {
this.controllers[site] = new UnifiClass.Controller({
host: this.settings.controllerIp,
port: this.settings.controllerPort,
username: this.settings.controllerUsername,
password: this.settings.controllerPassword,
site,
sslverify: !this.settings.ignoreSSLErrors
});
await this.controllers[site].login();
}
}
this.log.debug(`Update site: ${site}`);
if (this.update.sysinfo === true) {
await this.fetchSiteSysinfo(site);
}
if (this.update.clients === true) {
await this.fetchClients(site);
}
if (this.update.devices === true) {
await this.fetchDevices(site);
}
if (this.update.wlans === true) {
await this.fetchWlans(site);
}
if (this.update.networks === true) {
await this.fetchNetworks(site);
}
if (this.update.health === true) {
await this.fetchHealth(site);
}
if (this.update.vouchers === true) {
await this.fetchVouchers(site);
}
if (this.update.dpi === true) {
await this.fetchDpi(site);
}
if (this.update.gatewayTraffic === true) {
await this.fetchGatewayTraffic(site);
}
if (this.update.alarms === true) {
await this.fetchAlarms(site);
}
// finalize, logout and finish
//await this.controllers[site].logout();
} catch (err) {
this.handleError(err, site, 'updateUnifiData');
}
}
// Update is_online of offline clients
await this.setClientOnlineStatus();
} catch (err) {
this.handleError(err, undefined, 'updateUnifiData-fetchSites');
return;
}
await this.setStateAsync('info.connection', { ack: true, val: true });
this.log.debug('Update done');
} catch (err) {
await this.setStateAsync('info.connection', { ack: true, val: false });
this.handleError(err, undefined, 'updateUnifiData');
}
if (preventReschedule === false) {
// schedule a new execution of updateUnifiData in X seconds
this.queryTimeout = setTimeout(() => {
this.updateUnifiData();
}, this.settings.updateInterval);
}
}
/**
* Function to fetch site{Object} siteController
*
* @param {UnifiClass} siteController
*/
async fetchSites(siteController) {
const data = await siteController.getSites();
if (data === undefined) {
throw new Error(`fetchSites: Returned data is not in valid format: ${JSON.stringify(data)}`);
}
const sites = data.map((s) => {
return s.name;
});
this.log.debug(`fetchSites: ${sites}`);
await this.processSites(sites, data);
return sites;
}
/**
* Function that receives the sites as a JSON data array
* @param {String[]} sites
* @param {Object[]} data
*/
async processSites(sites, data) {
const objects = require('./admin/lib/objects_sites.json');
for (const site of sites) {
const x = sites.indexOf(site);
const siteData = data[x];
this.log.silly(`processSites: site: ${site}, data: ${JSON.stringify(data[x])}`);
await this.applyJsonLogic('', siteData, objects, ['site']);
}
}
/**
* Function to fetch site sysinfo
* @param {String} site
*/
async fetchSiteSysinfo(site) {
const data = await this.controllers[site].getSiteSysinfo();
if (data === undefined) {
throw new Error(`fetchSiteSysinfo ${site}: Returned data is not in valid format: ${JSON.stringify(data)}`);
}
this.log.debug(`fetchSiteSysinfo ${site}: ${data.length}`);
this.log.silly(`fetchSiteSysinfo ${site}: ${JSON.stringify(data)}`);
await this.processSiteSysinfo(site, data);
return data;
}
/**
* Function that receives the site sysinfo as a JSON data array
* @param {String} site
* @param {Object} data
*/
async processSiteSysinfo(site, data) {
const objects = require('./admin/lib/objects_sysinfo.json');
await this.applyJsonLogic(site, data, objects, this.statesFilter.sysinfo);
}
/**
* Function to fetch clients
* @param {String} site
*/
async fetchClients(site) {
const data = await this.controllers[site].getClientDevices();
if (!Array.isArray(data)) {
throw new Error(`fetchClients ${site}: Returned data is not in valid format: ${JSON.stringify(data)}`);
}
this.log.debug(`fetchClients ${site}: ${data.length}`);
this.log.silly(`fetchClients ${site}: ${JSON.stringify(data)}`);
await this.processClients(site, data);
await this.processBlockedClients(site);
return data;
}
/**
* Function that receives the clients as a JSON data array
* @param {String} site
* @param {Object} data
*/
async processClients(site, data) {
const objects = require('./admin/lib/objects_clients.json');
if(this.update.blacklist === true){
if (data) {
// Process objectsFilter
const siteData = data.filter((item) => {
if (this.objectsFilter.clients.includes(item.mac) == true ||
this.objectsFilter.clients.includes(item.ip) == true ||
this.objectsFilter.clients.includes(item.name) == true ||
this.objectsFilter.clients.includes(item.hostname) == true) {
return item;
}
});
if (siteData.length > 0) {
await this.applyJsonLogic(site, siteData, objects, this.statesFilter.clients);
}
}
}
if(this.update.blacklist === false){
if (data) {
// Process objectsFilter
const siteData = data.filter((item) => {
if (this.objectsFilter.clients.includes(item.mac) !== true &&
this.objectsFilter.clients.includes(item.ip) !== true &&
this.objectsFilter.clients.includes(item.name) !== true &&
this.objectsFilter.clients.includes(item.hostname) !== true) {
return item;
}
});
this.log.silly(`processClients: filtered data: ${JSON.stringify(siteData)}`);
if (siteData.length > 0) {
await this.applyJsonLogic(site, siteData, objects, this.statesFilter.clients);
}
}
}
}
/**
* Function to identify blocked clients and set the correct state
* @param {Object} site
*/
async processBlockedClients(site) {
if (this.statesFilter.clients.includes('clients.client.blocked')) {
const blockedClients = await this.controllers[site].getBlockedUsers();
const allClients = await this.getStatesAsync(`*.clients.*.blocked`);
// this.log.warn(JSON.stringify(blockedClients));
for (const id in allClients) {
if (blockedClients && blockedClients.length > 0) {
const clientMac = id.match(/([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})/)[0];
const index = blockedClients.findIndex(x => x.mac === clientMac);
if (index === -1) {
await this.setStateAsync(id, false, true);
} else {
await this.setStateAsync(id, true, true);
this.log.debug(`client '${clientMac}' is blocked`);
}
} else {
await this.setStateAsync(id, false, true);
}
}
}
}
/**
* Update is_online of offline clients
*/
async setClientOnlineStatus() {
const wlanStates = await this.getStatesAsync('*.clients.*.last_seen_by_uap');
const wiredStates = await this.getStatesAsync('*.clients.*.last_seen_by_usw');
// Workaround for UniFi bug "wireless clients shown as wired clients"
// https://community.ui.com/questions/Wireless-clients-shown-as-wired-clients/49d49818-4dab-473a-ba7f-d51bc4c067d1
for (const [key, value] of Object.entries(wlanStates)) {
const wiredStateId = key.replace('last_seen_by_uap', 'last_seen_by_usw');
if (Object.prototype.hasOwnProperty.call(wiredStates, wiredStateId)) {
delete wiredStates[wiredStateId];
}
}
const states = {
...wlanStates,
...wiredStates
};
const now = Math.floor(Date.now() / 1000) * 1000;
for (const [key, value] of Object.entries(states)) {
if (value !== null && typeof value.val === 'string') {
const lastSeen = Date.parse(value.val.replace(' ', 'T'));
const isOnline = (lastSeen - (now - this.settings.updateInterval - this.clients.isOnlineOffset) >= 0);
const stateId = key.replace(/last_seen_by_(usw|uap)/gi, 'is_online');
const oldState = await this.getStateAsync(stateId);
if (oldState === null) {
// This is the case if the client is new to the adapter with older JS-Controller versions
// Check if object is available and set the value
const oldObject = await this.getForeignObjectAsync(stateId);
if (oldObject !== null) {
await this.setForeignStateAsync(stateId, { ack: true, val: isOnline });
}
} else if (oldState.val != isOnline) {
await this.setForeignStateAsync(stateId, { ack: true, val: isOnline });
}
}
}
}
/**
* Function to fetch devices
* @param {String} site
*/
async fetchDevices(site) {
const data = await this.controllers[site].getAccessDevices();
if (!Array.isArray(data)) {
throw new Error(`fetchDevices ${site}: Returned data is not in valid format: ${JSON.stringify(data)}`);
}
this.log.debug(`fetchDevices ${site}: ${data.length}`);
this.log.silly(`fetchDevices ${site}: ${JSON.stringify(data)}`);
await this.processDevices(site, data);
return data;
}
/**
* Function that receives the devices as a JSON data array
* @param {String} site
* @param {Object} data
*/
async processDevices(site, data) {
const objects = require('./admin/lib/objects_devices.json');
if (data) {
// Process objectsFilter
const siteData = data.filter((item) => {
if (this.objectsFilter.devices.includes(item.mac) !== true &&
this.objectsFilter.devices.includes(item.ip) !== true &&
this.objectsFilter.devices.includes(item.name) !== true) {
return item;
}
});
this.log.silly(`processDevices: filtered data: ${JSON.stringify(siteData)}`);
if (siteData.length > 0) {
await this.applyJsonLogic(site, siteData, objects, this.statesFilter.devices);
}
}
}
/**
* Function to fetch WLANs
* @param {String} site
*/
async fetchWlans(site) {
const data = await this.controllers[site].getWLanSettings();
if (!Array.isArray(data)) {
throw new Error(`fetchWlans ${site}: Returned data is not in valid format: ${JSON.stringify(data)}`);
}
this.log.debug(`fetchWlans ${site}: ${data.length}`);
this.log.silly(`fetchWlans ${site}: ${JSON.stringify(data)}`);
await this.processWlans(site, data);
return data;
}
/**
* Function that receives the WLANs as a JSON data array
* @param {String} site
* @param {Object} data
*/
async processWlans(site, data) {
const objects = require('./admin/lib/objects_wlans.json');
if (data) {
// Process objectsFilter
const siteData = data.filter((item) => {
if (this.objectsFilter.wlans.includes(item.name) !== true) {
return item;
}
});
this.log.silly(`processWlans: filtered data: ${JSON.stringify(siteData)}`);
if (siteData.length > 0) {
await this.applyJsonLogic(site, siteData, objects, this.statesFilter.wlans);
}
}
}
/**
* Function to fetch networks
* @param {String} site
*/
async fetchNetworks(site) {
const data = await this.controllers[site].getNetworkConf();
if (!Array.isArray(data)) {
throw new Error(`fetchNetworks ${site}: Returned data is not in valid format: ${JSON.stringify(data)}`);
}
this.log.debug(`fetchNetworks ${site}: ${data.length}`);
this.log.silly(`fetchNetworks ${site}: ${JSON.stringify(data)}`);
await this.processNetworks(site, data);
return data;
}
/**
* Function that receives the networks as a JSON data array
* @param {String} site
* @param {Object} data
*/
async processNetworks(site, data) {
const objects = require('./admin/lib/objects_networks.json');
if (data) {
// Process objectsFilter
const siteData = data.filter((item) => {
if (this.objectsFilter.networks.includes(item.name) !== true) {
return item;
}
});
this.log.silly(`processNetworks: filtered data: ${JSON.stringify(siteData)}`);
if (siteData.length > 0) {
await this.applyJsonLogic(site, siteData, objects, this.statesFilter.networks);
}
}
}
/**
* Function to fetch health
* @param {String} site
*/
async fetchHealth(site) {
const data = await this.controllers[site].getHealth();
if (!Array.isArray(data)) {
throw new Error(`fetchHealth ${site}: Returned data is not in valid format: ${JSON.stringify(data)}`);
}
this.log.debug(`fetchHealth ${site}: ${data.length}`);
this.log.silly(`fetchHealth ${site}: ${JSON.stringify(data)}`);
await this.processHealth(site, data);
return data;
}
/**
* Function that receives the health as a JSON data array
* @param {String} site
* @param {Object} data
*/
async processHealth(site, data) {
const objects = require('./admin/lib/objects_health.json');
if (data) {
// Process objectsFilter
const siteData = data.filter((item) => {
if (this.objectsFilter.health.includes(item.subsystem) !== true) {
return item;
}
});
this.log.silly(`processHealth: filtered data: ${JSON.stringify(siteData)}`);
if (siteData.length > 0) {
await this.applyJsonLogic(site, siteData, objects, this.statesFilter.health);
}
}
}
/**
* Function to fetch vouchers
* @param {String} site
*/
async fetchVouchers(site) {
const data = await this.controllers[site].getVouchers();
if (!Array.isArray(data)) {
throw new Error(`fetchVouchers ${site}: Returned data is not in valid format: ${JSON.stringify(data)}`);
}
this.log.debug(`fetchVouchers ${site}: ${data.length}`);
this.log.silly(`fetchVouchers ${site}: ${JSON.stringify(data)}`);
await this.processVouchers(site, data);
return data;
}
/**
* Function that receives the vouchers as a JSON data array
* @param {String} site
* @param {Object} data
*/
async processVouchers(site, data) {
const objects = require('./admin/lib/objects_vouchers.json');
if (data) {
let siteData = data;
if (this.update.vouchersNoUsed) {
// Remove used vouchers
siteData = siteData.filter((item) => {
if (item.used === 0) {
return item;
}
});
this.log.silly(`processVouchers: filtered data: ${JSON.stringify(siteData)}`);
const existingVouchers = await this.getForeignObjectsAsync(`${this.namespace}.${site}.vouchers.voucher_*`, 'channel');
for (const voucher in existingVouchers) {
const voucherId = voucher.replace(`${this.namespace}.${site}.vouchers.voucher_`, '');
if (!siteData.find(item => item.code === voucherId)) {
const voucherChannelId = `${this.namespace}.${site}.vouchers.voucher_${voucherId}`;
this.log.debug(`deleting data points of voucher with id '${voucherId}'`);
// voucher id not exist in api request result -> get dps and delete them
const dpsOfVoucherId = await this.getForeignObjectsAsync(`${voucherChannelId}.*`);
for (const id in dpsOfVoucherId) {
// delete datapoint
await this.delObjectAsync(id);
if (this.ownObjects[id.replace(`${this.namespace}.`, '')]) {
// remove from own objects if exist
await delete this.ownObjects[id.replace(`${this.namespace}.`, '')];
}
}
// delete voucher channel
await this.delObjectAsync(`${voucherChannelId}`);
if (this.ownObjects[voucherChannelId.replace(`${this.namespace}.`, '')]) {
// remove from own objects if exist
await delete this.ownObjects[voucherChannelId.replace(`${this.namespace}.`, '')];
}
}
}
}
await this.applyJsonLogic(site, siteData, objects, this.statesFilter.vouchers);
}
}
/**
* Function to fetch dpi
* @param {String} site
*/
async fetchDpi(site) {
const data = await this.controllers[site].getDPIStats(site);
if (!Array.isArray(data)) {
throw new Error(`fetchDpi ${site}: Returned data is not in valid format. This option is only available for gateways!: ${JSON.stringify(data)}`);
}
if (data[0] && data[0].by_cat && data[0].by_app) {
this.log.debug(`fetchDpi ${site}: categories: ${data[0].by_cat.length}, apps: ${data[0].by_app.length}`);
}
this.log.silly(`fetchDpi ${site}: ${JSON.stringify(data)}`);
await this.processDpi(site, data);
return data;
}
/**
* Function that receives the dpi as a JSON data array
* @param {String} site
* @param {Object} data
*/
async processDpi(site, data) {
const objects = require('./admin/lib/objects_dpi.json');
if (data) {
// Process objectsFilter
const siteData = data.filter((item) => {
// if (this.objectsFilter.dpi.includes(item.subsystem) !== true) {
// return item;
// }
return item;
});
this.log.silly(`processDpi: filtered data: ${JSON.stringify(siteData)}`);
if (siteData.length > 0) {
await this.applyJsonLogic(site, siteData, objects, this.statesFilter.dpi);
}
}
}
/**
* Function to fetch daily gateway traffic
* @param {String} site
*/
async fetchGatewayTraffic(site) {
let start = undefined;
let end = undefined;
if (this.update.gatewayTrafficMaxDays > 0) {
const now = new Date();
end = now.getTime();
now.setDate(now.getDate() - this.update.gatewayTrafficMaxDays);
start = now.getTime();
this.log.silly(`fetchGatewayTraffic: start: ${new Date(start).toLocaleDateString()}, end: ${new Date(end).toLocaleDateString()}`);
}
const data = await this.controllers[site].getDailyGatewayStats(start, end, ['lan-rx_bytes', 'lan-tx_bytes']);
if (!Array.isArray(data)) {
throw new Error(`fetchGatewayTraffic ${site}: Returned data is not in valid format. This option is only available for gateways!: ${JSON.stringify(data)}`);
}
this.log.debug(`fetchGatewayTraffic ${site}: ${data.length}`);
this.log.silly(`fetchGatewayTraffic ${site}: ${JSON.stringify(data)}`);
await this.processGatewayTraffic(site, data);
return data;
}
/**
* Function that receives the daily gateway traffic as a JSON data array
* @param {String} site
* @param {Object} data
*/
async processGatewayTraffic(site, data) {
const objects = require('./admin/lib/objects_gateway_traffic.json');
if (data) {
// Process objectsFilter
const siteData = data.filter((item) => {
// if (this.objectsFilter.dpi.includes(item.subsystem) !== true) {
// return item;
// }
return item;
});
this.log.silly(`processGatewayTraffic: filtered data: ${JSON.stringify(siteData)}`);
if (siteData.length > 0) {
await this.applyJsonLogic(site, siteData, objects, this.statesFilter.gateway_traffic);
}
}
}
/**
* Function to fetch alarms
* @param {String} site
*/
async fetchAlarms(site) {
const data = await this.controllers[site].getAlarms();
if (!Array.isArray(data)) {
throw new Error(`fetchAlarms ${site}: Returned data is not in valid format: ${JSON.stringify(data)}`);
}
this.log.debug(`fetchAlarms ${site}: ${data.length}`);
this.log.silly(`fetchAlarms ${site}: ${JSON.stringify(data)}`);
await this.processAlarms(site, data);
return data;
}
/**
* Function that receives the alarms as a JSON data array
* @param {String} site
* @param {Object} data
*/
async processAlarms(site, data) {
const objects = require('./admin/lib/objects_alarms.json');
if (data) {
// Process objectsFilter
const siteData = data.filter((item) => {
// if (this.objectsFilter.dpi.includes(item.subsystem) !== true) {
// return item;
// }
return item;
});
this.log.silly(`processAlarms: filtered data: ${JSON.stringify(siteData)}`);
if (this.update.alarmsNoArchived) {
const existingAlarms = await this.getForeignObjectsAsync(`${this.namespace}.${site}.alarms.alarm_*`, 'channel');
const alarmDatapoints = await this.getUnifiObjectsLibIds('alarms');
for (const alarm in existingAlarms) {
const alarmId = alarm.replace(`${this.namespace}.${site}.alarms.alarm_`, '');
if (!siteData.find(item => item._id === alarmId)) {
this.log.debug(`deleting data points of alarm with id '${alarmId}'`);
for (const dp of alarmDatapoints) {
const dpId = `${site}.${dp.replace('.alarm', `.alarm_${alarmId}`)}`;
if (await this.getObjectAsync(dpId)) {
await this.delObjectAsync(dpId);
}
if (this.ownObjects[dpId]) {
// remove from own objects if exist
await delete this.ownObjects[dpId];
}
}
}
}
}
if (siteData.length > 0) {
await this.applyJsonLogic(site, siteData, objects, this.statesFilter.alarms);
}
}
}