forked from ioBroker/ioBroker.influxdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
2228 lines (1994 loc) · 95 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';
//noinspection JSUnresolvedFunction
const utils = require('@iobroker/adapter-core'); // Get common adapter utils
const DatabaseInfluxDB1x = require ('./lib/DatabaseInfluxDB1x.js').DatabaseInfluxDB1x; // TODO if else
const DatabaseInfluxDB2x = require ('./lib/DatabaseInfluxDB2x.js').DatabaseInfluxDB2x;
const fs = require('fs');
const path = require('path');
const [appName, adapterName] = require('./package.json').name.split('.');
const Aggregate = require('./lib/aggregate.js');
const dataDir = path.normalize(`${utils.controllerDir}/${require(`${utils.controllerDir}/lib/tools`).getDefaultDataDir()}`);
const cacheFile = `${dataDir}influxdata.json`;
let adapter;
function isEqual(a, b) {
//console.log('Compare ' + JSON.stringify(a) + ' with ' + JSON.stringify(b));
// Create arrays of property names
if (a === null || a === undefined || b === null || b === undefined) {
return a === b;
}
const aProps = Object.getOwnPropertyNames(a);
const bProps = Object.getOwnPropertyNames(b);
// If number of properties is different,
// objects are not equivalent
if (aProps.length !== bProps.length) {
//console.log('num props different: ' + JSON.stringify(aProps) + ' / ' + JSON.stringify(bProps));
return false;
}
for (let i = 0; i < aProps.length; i++) {
const propName = aProps[i];
if (typeof a[propName] !== typeof b[propName]) {
//console.log('type props ' + propName + ' different');
return false;
}
if (typeof a[propName] === 'object') {
if (!isEqual(a[propName], b[propName])) {
return false;
}
}
else {
// If values of same property are not equal,
// objects are not equivalent
if (a[propName] !== b[propName]) {
//console.log('props ' + propName + ' different');
return false;
}
}
}
// If we made it this far, objects
// are considered equivalent
return true;
}
function startAdapter(options) {
options = options || {};
Object.assign(options, {name: adapterName});
adapter = new utils.Adapter(options);
adapter.on('objectChange', (id, obj) => {
const formerAliasId = adapter._aliasMap[id] ? adapter._aliasMap[id] : id;
if (obj && obj.common &&
(obj.common.custom && obj.common.custom[adapter.namespace] && typeof obj.common.custom[adapter.namespace] === 'object' && obj.common.custom[adapter.namespace].enabled)
) {
const realId = id;
let checkForRemove = true;
if (obj.common.custom && obj.common.custom[adapter.namespace] && obj.common.custom[adapter.namespace].aliasId) {
if (obj.common.custom[adapter.namespace].aliasId !== id) {
adapter._aliasMap[id] = obj.common.custom[adapter.namespace].aliasId;
adapter.log.debug(`Registered Alias: ${id} --> ${adapter._aliasMap[id]}`);
id = adapter._aliasMap[id];
checkForRemove = false;
} else {
adapter.log.warn(`Ignoring Alias-ID because identical to ID for ${id}`);
obj.common.custom[adapter.namespace].aliasId = '';
}
}
if (checkForRemove && adapter._aliasMap[id]) {
adapter.log.debug(`Removed Alias: ${id} !-> ${adapter._aliasMap[id]}`);
delete adapter._aliasMap[id];
}
if (!adapter._influxDPs[formerAliasId] && !adapter._subscribeAll) {
// unsubscribe
for (const _id in adapter._influxDPs) {
adapter.unsubscribeForeignStates(adapter._influxDPs[_id].realId);
}
adapter._subscribeAll = true;
adapter.subscribeForeignStates('*');
}
if (obj.common.custom[adapter.namespace].debounce !== undefined && obj.common.custom[adapter.namespace].debounce !== null && obj.common.custom[adapter.namespace].debounce !== '') {
obj.common.custom[adapter.namespace].debounce = parseInt(obj.common.custom[adapter.namespace].debounce, 10) || 0;
} else {
obj.common.custom[adapter.namespace].debounce = adapter.config.debounce;
}
obj.common.custom[adapter.namespace].changesOnly = obj.common.custom[adapter.namespace].changesOnly === 'true' || obj.common.custom[adapter.namespace].changesOnly === true;
obj.common.custom[adapter.namespace].ignoreZero = obj.common.custom[adapter.namespace].ignoreZero === 'true' || obj.common.custom[adapter.namespace].ignoreZero === true;
obj.common.custom[adapter.namespace].ignoreBelowZero = obj.common.custom[adapter.namespace].ignoreBelowZero === 'true' || obj.common.custom[adapter.namespace].ignoreBelowZero === true;
if (obj.common.custom[adapter.namespace].changesRelogInterval !== undefined && obj.common.custom[adapter.namespace].changesRelogInterval !== null && obj.common.custom[adapter.namespace].changesRelogInterval !== '') {
obj.common.custom[adapter.namespace].changesRelogInterval = parseInt(obj.common.custom[adapter.namespace].changesRelogInterval, 10) || 0;
} else {
obj.common.custom[adapter.namespace].changesRelogInterval = adapter.config.changesRelogInterval;
}
if (obj.common.custom[adapter.namespace].changesMinDelta !== undefined && obj.common.custom[adapter.namespace].changesMinDelta !== null && obj.common.custom[adapter.namespace].changesMinDelta !== '') {
obj.common.custom[adapter.namespace].changesMinDelta = parseFloat(obj.common.custom[adapter.namespace].changesMinDelta.toString().replace(/,/g, '.')) || 0;
} else {
obj.common.custom[adapter.namespace].changesMinDelta = adapter.config.changesMinDelta;
}
if (!obj.common.custom[adapter.namespace].storageType) obj.common.custom[adapter.namespace].storageType = false;
if (adapter._influxDPs[formerAliasId] && !adapter._influxDPs[formerAliasId].storageTypeAdjustedInternally && adapter._influxDPs[formerAliasId][adapter.namespace] && isEqual(obj.common.custom[adapter.namespace], adapter._influxDPs[formerAliasId][adapter.namespace])) {
adapter.log.debug(`Object ${id} unchanged. Ignore`);
return;
}
const state = adapter._influxDPs[formerAliasId] ? adapter._influxDPs[formerAliasId].state : null;
const skipped = adapter._influxDPs[formerAliasId] ? adapter._influxDPs[formerAliasId].skipped : null;
adapter._influxDPs[id] = obj.common.custom;
adapter._influxDPs[id].realId = realId;
adapter._influxDPs[id].state = state;
adapter._influxDPs[id].skipped = skipped;
adapter._influxDPs[formerAliasId] && adapter._influxDPs[formerAliasId].relogTimeout && clearTimeout(adapter._influxDPs[formerAliasId].relogTimeout);
writeInitialValue(adapter, realId, id);
adapter.log.info(`enabled logging of ${id}, Alias=${id !== realId}`);
} else {
if (adapter._aliasMap[id]) {
adapter.log.debug(`Removed Alias: ${id} !-> ${adapter._aliasMap[id]}`);
delete adapter._aliasMap[id];
}
id = formerAliasId;
if (adapter._influxDPs[id]) {
adapter._influxDPs[id].relogTimeout && clearTimeout(adapter._influxDPs[id].relogTimeout);
adapter._influxDPs[id].timeout && clearTimeout(adapter._influxDPs[id].timeout);
delete adapter._influxDPs[id];
adapter.log.info(`disabled logging of ${id}`);
}
}
});
adapter.on('stateChange', (id, state) => {
id = adapter._aliasMap[id] ? adapter._aliasMap[id] : id;
pushHistory(adapter, id, state);
});
adapter.on('ready', () => main(adapter));
adapter.on('unload', callback => finish(adapter, callback));
adapter.on('message', msg => processMessage(adapter, msg));
adapter._subscribeAll = false;
adapter._influxDPs = {};
adapter._client = null;
adapter._seriesBufferChecker = null;
adapter._seriesBufferCounter = 0;
adapter._seriesBufferFlushPlanned = false;
adapter._seriesBuffer = {};
adapter._conflictingPoints = {};
adapter._errorPoints = {};
adapter._tasksStart = [];
adapter._connected = null;
adapter._finished = false;
adapter._aliasMap = {};
return adapter;
}
function setConnected(adapter, isConnected) {
if (adapter._connected !== isConnected) {
adapter._connected = isConnected;
adapter.setState('info.connection', adapter._connected, true, err =>
// analyse if the state could be set (because of permissions)
err ? adapter.log.error(`Can not update adapter._connected state: ${err}`) :
adapter.log.debug(`connected set to ${adapter._connected}`));
}
}
function reconnect(adapter) {
setConnected(adapter, false);
stopPing(adapter);
if (!adapter._reconnectTimeout) {
adapter._reconnectTimeout = setTimeout(() => {
adapter._reconnectTimeout = null;
connect(adapter);
}, adapter.config.reconnectInterval);
}
}
function startPing(adapter) {
adapter._pingInterval = adapter._pingInterval || setInterval(() => ping(adapter), adapter.config.pingInterval);
}
function stopPing(adapter) {
adapter._pingInterval && clearInterval(adapter._pingInterval);
adapter._pingInterval = null;
}
function ping(adapter) {
adapter._client.ping && adapter.config.pingserver !== false && adapter._client.ping(adapter.config.pingInterval - 1000 < 0 ? 1000 : adapter.config.pingInterval - 1000)
.then(hosts => {
if (!hosts.some(host => host.online)) {
reconnect(adapter);
} else {
adapter.log.debug('PING OK');
}
},
error => {
adapter.log.error(`Error during ping: ${error}. Attempting reconnect.`);
reconnect(adapter);
});
}
function connect(adapter) {
adapter.log.info(`Connecting ${adapter.config.protocol}://${adapter.config.host}:${adapter.config.port} ...`);
adapter.config.dbname = adapter.config.dbname || appName;
adapter.config.validateSSL = adapter.config.validateSSL !== undefined ? !!adapter.config.validateSSL : true;
adapter.config.seriesBufferMax = parseInt(adapter.config.seriesBufferMax, 10) || 0;
adapter.log.info(`Influx DB Version used: ${adapter.config.dbversion}`);
switch (adapter.config.dbversion) {
case '2.x':
if (/[\x00-\x08\x0E-\x1F\x80-\xFF]/.test(adapter.config.token)) {
adapter.log.error('Token error: Please re-enter the token in Admin. Stopping');
return;
}
adapter._client = new DatabaseInfluxDB2x(
adapter.log,
adapter.config.host,
adapter.config.port, // optional, default 8086
adapter.config.protocol, // optional, default 'http'
adapter.config.token,
adapter.config.organization,
adapter.config.dbname,
adapter.config.requestTimeout,
adapter.config.validateSSL,
adapter.config.usetags
)
break;
case '1.x':
default:
if (/[\x00-\x08\x0E-\x1F\x80-\xFF]/.test(adapter.config.password)) {
return adapter.log.error('Password error: Please re-enter the password in Admin. Stopping');
}
adapter._client = new DatabaseInfluxDB1x(
adapter.log,
adapter.config.host,
adapter.config.port, // optional, default 8086
adapter.config.protocol, // optional, default 'http'
adapter.config.user,
adapter.config.password,
adapter.config.dbname,
adapter.config.requestTimeout,
'ms'
);
break;
}
if (adapter.config.pingserver === false) {
adapter.log.info('Deactivated DB health checks (ping) via configuration');
}
adapter._client.getDatabaseNames((err, dbNames) => {
if (err) {
adapter.log.error(err);
reconnect(adapter);
} else {
setConnected(adapter, true); // ??? to early, move down?
if (!dbNames.includes(adapter.config.dbname)) {
adapter._client.createDatabase(adapter.config.dbname, err => {
if (err) {
adapter.log.error(err);
reconnect(adapter);
}
//Check and potentially update retention policy
adapter._client.applyRetentionPolicyToDB(adapter.config.dbname, adapter.config.retention, err => {
if (err) {
//Ignore issues with creating/altering retention policy, as it might be due to insufficient permissions
adapter.log.warn(err);
}
});
if (adapter.config.dbversion === '2.x') {
checkMetaDataStorageType(adapter);
}
});
} else {
//Check and potentially update retention policy
adapter._client.applyRetentionPolicyToDB(adapter.config.dbname, adapter.config.retention, err => {
if (err) {
//Ignore issues with creating/altering retention policy, as it might be due to insufficient permissions
adapter.log.warn(err);
}
});
if (adapter.config.dbversion === '2.x') {
checkMetaDataStorageType(adapter);
}
}
}
});
}
function checkMetaDataStorageType(adapter) {
adapter._client.getMetaDataStorageType((error,storageType) => {
if (error)
adapter.log.error(`Error checking for metadata storage type: ${error}`);
else {
adapter.log.debug(`Storage type for metadata found in DB: ${storageType}`);
if ((storageType === 'tags' && !adapter.config.usetags) || (storageType === 'fields' && adapter.config.usetags)) {
adapter.log.error(`Cannot use ${adapter.config.usetags ? 'tags' : 'fields'} for metadata (q, ack, from) since ` +
`the selected DB already uses ${storageType} instead. Please change your adapter configuration, or choose a DB ` +
`that already uses ${adapter.config.usetags ? 'tags' : 'fields'}, or is empty.`);
setConnected(adapter, false);
finish(adapter, null);
} else {
setConnected(adapter, true);
processStartValues(adapter);
adapter.log.info('Connected!');
startPing(adapter);
}
}
});
}
function processStartValues(adapter) {
if (adapter._tasksStart && adapter._tasksStart.length) {
const taskId = adapter._tasksStart.shift();
if (adapter._influxDPs[taskId] && adapter._influxDPs[taskId][adapter.namespace].changesOnly) {
pushHistory(adapter, taskId, adapter._influxDPs[taskId].state, true);
}
setImmediate(() => processStartValues(adapter));
}
}
function getRetention(adapter, msg) {
adapter.log.debug('getRetention invoked, checking DB');
try {
adapter._client.getRetentionPolicyForDB(adapter.config.dbname, result => {
adapter.sendTo(msg.from, msg.command, {
result: result,
error: null
}, msg.callback);
});
} catch (ex) {
adapter.sendTo(msg.from, msg.command, {error: ex.toString()}, msg.callback);
}
}
function testConnection(adapter, msg) {
adapter.log.debug(`testConnection msg-object: ${JSON.stringify(msg)}`);
msg.message.config.port = parseInt(msg.message.config.port, 10) || 0;
msg.message.config.requestTimeout = parseInt(msg.message.config.requestTimeout) || 30000;
let timeout;
try {
timeout = setTimeout(() => {
timeout = null;
adapter.sendTo(msg.from, msg.command, {error: 'connect timeout'}, msg.callback);
}, 5000);
let lClient;
adapter.log.debug(`TEST DB Version: ${msg.message.config.dbversion}`);
switch (msg.message.config.dbversion) {
case '2.x':
adapter.log.info('Connecting to InfluxDB 2');
lClient = new DatabaseInfluxDB2x(
adapter.log,
msg.message.config.host,
msg.message.config.port,
msg.message.config.protocol, // optional, default 'http'
msg.message.config.token,
msg.message.config.organization,
msg.message.config.dbname || appName,
msg.message.config.requestTimeout
)
break;
default:
case '1.x':
lClient = new DatabaseInfluxDB1x(
adapter.log,
msg.message.config.host,
msg.message.config.port,
msg.message.config.protocol, // optional, default 'http'
msg.message.config.user,
msg.message.config.password,
msg.message.config.dbname || appName,
msg.message.config.requestTimeout
);
break;
}
lClient.getDatabaseNames((err /* , arrayDatabaseNames*/ ) => {
if (timeout) {
clearTimeout(timeout);
timeout = null;
return adapter.sendTo(msg.from, msg.command, {error: err ? err.toString() : null}, msg.callback);
}
});
} catch (ex) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
if (ex.toString() === 'TypeError: undefined is not a function') {
return adapter.sendTo(msg.from, msg.command, {error: 'Node.js DB driver could not be installed.'}, msg.callback);
} else {
return adapter.sendTo(msg.from, msg.command, {error: ex.toString()}, msg.callback);
}
}
}
function destroyDB(adapter, msg) {
if (!adapter._client) {
return adapter.sendTo(msg.from, msg.command, {error: 'Not connected'}, msg.callback);
}
try {
adapter._client.dropDatabase(adapter.config.dbname, err => {
if (err) {
adapter.log.error(err);
adapter.sendTo(msg.from, msg.command, {error: err.toString()}, msg.callback);
} else {
adapter.sendTo(msg.from, msg.command, {error: null}, msg.callback);
// restart adapter
setTimeout(() => {
adapter.getForeignObject(`system.adapter.${adapter.namespace}`, (err, obj) => {
if (!err) {
adapter.setForeignObject(obj._id, obj);
} else {
adapter.log.error(`Cannot read object "system.adapter.${adapter.namespace}": ${err}`);
adapter.stop();
}
});
}, 2000);
}
});
} catch (err) {
return adapter.sendTo(msg.from, msg.command, {error: err.toString()}, msg.callback);
}
}
function processMessage(adapter, msg) {
adapter.log.debug(`Incoming message ${msg.command} from ${msg.from}`);
if (msg.command === 'features') {
// influxdb 1
if (adapter.config.dbversion === '1.x') {
adapter.sendTo(msg.from, msg.command, {supportedFeatures: ['update', 'delete', 'deleteRange', 'deleteAll', 'storeState']}, msg.callback);
} else {
// not yet implemented
adapter.sendTo(msg.from, msg.command, {supportedFeatures: ['storeState']}, msg.callback);
}
}
else if (msg.command === 'update') {
updateState(adapter, msg);
} else if (msg.command === 'delete') {
deleteState(adapter, msg);
} else if (msg.command === 'deleteAll') {
deleteStateAll(adapter, msg);
} else if (msg.command === 'deleteRange') {
deleteState(adapter, msg);
} else if (msg.command === 'storeState') {
storeState(adapter, msg);
} else if (msg.command === 'getHistory') {
adapter.config.dbversion === '1.x' ? getHistory(adapter, msg) : getHistoryIflx2(adapter, msg);
}
else if (msg.command === 'test') {
testConnection(adapter, msg);
}
else if (msg.command === 'destroy') {
destroyDB(adapter, msg);
}
else if (msg.command === 'query') {
switch (adapter.config.dbversion) {
case '2.x':
// Influx 2.x uses Flux instead of InfluxQL, so for multiple statements there is no delimiter by default, so we introduce ;
multiQuery(adapter, msg);
break;
case '1.x':
default:
query(adapter, msg);
break;
}
}
else if (msg.command === 'getConflictingPoints') {
getConflictingPoints(adapter, msg);
}
else if (msg.command === 'resetConflictingPoints') {
resetConflictingPoints(adapter, msg);
}
else if (msg.command === 'enableHistory') {
enableHistory(adapter, msg);
}
else if (msg.command === 'disableHistory') {
disableHistory(adapter, msg);
}
else if (msg.command === 'getEnabledDPs') {
getEnabledDPs(adapter, msg);
}
else if (msg.command === 'stopInstance') {
finish(adapter, () => {
if (msg.callback) {
adapter.sendTo(msg.from, msg.command, 'stopped', msg.callback);
setTimeout(() => adapter.terminate ? adapter.terminate() : process.exit(), 200);
}
});
}
else if (msg.command === 'getRetention') {
getRetention(adapter, msg);
}
}
function getConflictingPoints(adapter, msg) {
return adapter.sendTo(msg.from, msg.command, {conflictingPoints: adapter._conflictingPoints}, msg.callback);
}
function resetConflictingPoints(adapter, msg) {
const resultMsg = {reset: true, conflictingPoints: adapter._conflictingPoints};
adapter._conflictingPoints = {};
return adapter.sendTo(msg.from, msg.command, resultMsg, msg.callback);
}
function main(adapter) {
adapter.config.port = parseInt(adapter.config.port, 10) || 0;
// set default history if not yet set
adapter.getForeignObject('system.config', (err, obj) => {
if (obj && obj.common && !obj.common.defaultHistory) {
obj.common.defaultHistory = adapter.namespace;
adapter.setForeignObject('system.config', obj, err => {
if (err) {
adapter.log.error(`Cannot set default history instance: ${err}`);
} else {
adapter.log.info(`Set default history instance to "${adapter.namespace}"`);
}
});
}
});
setConnected(adapter, false);
adapter.config.reconnectInterval = parseInt(adapter.config.reconnectInterval, 10) || 10000;
adapter.config.pingInterval = parseInt(adapter.config.pingInterval, 10) || 15000;
if (adapter.config.round !== null && adapter.config.round !== undefined) {
adapter.config.round = Math.pow(10, parseInt(adapter.config.round, 10));
} else {
adapter.config.round = null;
}
if (adapter.config.changesRelogInterval !== null && adapter.config.changesRelogInterval !== undefined) {
adapter.config.changesRelogInterval = parseInt(adapter.config.changesRelogInterval, 10);
} else {
adapter.config.changesRelogInterval = 0;
}
adapter.config.seriesBufferFlushInterval = parseInt(adapter.config.seriesBufferFlushInterval, 10) || 600;
adapter.config.requestTimeout = parseInt(adapter.config.requestTimeout, 10) || 30000;
if (adapter.config.changesMinDelta !== null && adapter.config.changesMinDelta !== undefined) {
adapter.config.changesMinDelta = parseFloat(adapter.config.changesMinDelta.toString().replace(/,/g, '.'));
} else {
adapter.config.changesMinDelta = 0;
}
// analyse if by the last stop the values were cached into file
try {
if (fs.statSync(cacheFile).isFile()) {
const fileContent = fs.readFileSync(cacheFile, 'utf-8');
const tempData = JSON.parse(fileContent, (key, value) =>
key === 'time' ? new Date(value) : value);
if (tempData.seriesBufferCounter) adapter._seriesBufferCounter = tempData.seriesBufferCounter;
if (tempData.seriesBuffer) adapter._seriesBuffer = tempData.seriesBuffer;
if (tempData.conflictingPoints) adapter._conflictingPoints = tempData.conflictingPoints;
adapter.log.info(`Buffer initialized with data for ${adapter._seriesBufferCounter} points and ${Object.keys(adapter._conflictingPoints).length} conflicts from last exit`);
fs.unlinkSync(cacheFile);
}
} catch (err) {
adapter.log.info('No stored data from last exit found');
}
// read all custom settings
adapter.getObjectView('system', 'custom', {}, (err, doc) => {
err && adapter.log.error(`main/getObjectView: ${err}`);
let count = 0;
if (doc && doc.rows) {
const l = doc.rows.length;
for (let i = 0; i < l; i++) {
if (doc.rows[i].value) {
let id = doc.rows[i].id;
const realId = id;
if (doc.rows[i].value[adapter.namespace] && doc.rows[i].value[adapter.namespace].aliasId) {
adapter._aliasMap[id] = doc.rows[i].value[adapter.namespace].aliasId;
adapter.log.debug(`Found Alias: ${id} --> ${adapter._aliasMap[id]}`);
id = adapter._aliasMap[id];
}
adapter._influxDPs[id] = doc.rows[i].value;
if (!adapter._influxDPs[id][adapter.namespace] || typeof adapter._influxDPs[id][adapter.namespace] !== 'object' || adapter._influxDPs[id][adapter.namespace].enabled === false) {
delete adapter._influxDPs[id];
} else {
count++;
adapter.log.info(`enabled logging of ${id}, Alias=${id !== realId}, ${count} points now activated`);
if (adapter._influxDPs[id][adapter.namespace].debounce !== undefined && adapter._influxDPs[id][adapter.namespace].debounce !== null && adapter._influxDPs[id][adapter.namespace].debounce !== '') {
adapter._influxDPs[id][adapter.namespace].debounce = parseInt(adapter._influxDPs[id][adapter.namespace].debounce, 10) || 0;
} else {
adapter._influxDPs[id][adapter.namespace].debounce = adapter.config.debounce;
}
adapter._influxDPs[id][adapter.namespace].changesOnly = adapter._influxDPs[id][adapter.namespace].changesOnly === 'true' || adapter._influxDPs[id][adapter.namespace].changesOnly === true;
adapter._influxDPs[id][adapter.namespace].ignoreZero = adapter._influxDPs[id][adapter.namespace].ignoreZero === 'true' || adapter._influxDPs[id][adapter.namespace].ignoreZero === true;
adapter._influxDPs[id][adapter.namespace].ignoreBelowZero = adapter._influxDPs[id][adapter.namespace].ignoreBelowZero === 'true' || adapter._influxDPs[id][adapter.namespace].ignoreBelowZero === true;
if (adapter._influxDPs[id][adapter.namespace].changesRelogInterval !== undefined && adapter._influxDPs[id][adapter.namespace].changesRelogInterval !== null && adapter._influxDPs[id][adapter.namespace].changesRelogInterval !== '') {
adapter._influxDPs[id][adapter.namespace].changesRelogInterval = parseInt(adapter._influxDPs[id][adapter.namespace].changesRelogInterval, 10) || 0;
} else {
adapter._influxDPs[id][adapter.namespace].changesRelogInterval = adapter.config.changesRelogInterval;
}
if (adapter._influxDPs[id][adapter.namespace].changesMinDelta !== undefined && adapter._influxDPs[id][adapter.namespace].changesMinDelta !== null && adapter._influxDPs[id][adapter.namespace].changesMinDelta !== '') {
adapter._influxDPs[id][adapter.namespace].changesMinDelta = parseFloat(adapter._influxDPs[id][adapter.namespace].changesMinDelta) || 0;
} else {
adapter._influxDPs[id][adapter.namespace].changesMinDelta = adapter.config.changesMinDelta;
}
adapter._influxDPs[id][adapter.namespace].storageType = adapter._influxDPs[id][adapter.namespace].storageType || false;
adapter._influxDPs[id].realId = realId;
writeInitialValue(adapter, realId, id);
}
}
}
}
if (count < 20) {
for (const _id in adapter._influxDPs) {
if (adapter._influxDPs.hasOwnProperty(_id)) {
adapter.subscribeForeignStates(adapter._influxDPs[_id].realId);
}
}
} else {
adapter._subscribeAll = true;
adapter.subscribeForeignStates('*');
}
});
adapter.subscribeForeignObjects('*');
connect(adapter);
if (adapter._client) {
// store all buffered data every x seconds to not lost the data
adapter._seriesBufferChecker = setInterval(() => {
adapter._seriesBufferFlushPlanned = true;
storeBufferedSeries(adapter);
}, adapter.config.seriesBufferFlushInterval * 1000);
}
}
function writeInitialValue(adapter, realId, id) {
adapter.getForeignState(realId, (err, state) => {
if (state && adapter._influxDPs[id]) {
state.from = `system.adapter.${adapter.namespace}`;
adapter._influxDPs[id].state = state;
adapter._tasksStart.push(id);
if (adapter._tasksStart.length === 1 && adapter._connected) {
processStartValues(adapter);
}
}
});
}
function pushHistory(adapter, id, state, timerRelog) {
if (timerRelog === undefined) timerRelog = false;
// Push into InfluxDB
if (adapter._influxDPs[id]) {
const settings = adapter._influxDPs[id][adapter.namespace];
if (!settings || !state) return;
if (state && state.val === undefined) {
adapter.log.warn(`state value undefined received for ${id} which is not allowed. Ignoring.`);
return;
}
if (typeof state.val === 'string' && settings.storageType !== 'String') {
const f = parseFloat(state.val);
if (f == state.val) {
state.val = f;
}
}
if (adapter._influxDPs[id].state && settings.changesOnly && !timerRelog) {
if (settings.changesRelogInterval === 0) {
if (state.ts !== state.lc) {
adapter._influxDPs[id].skipped = state; // remember new timestamp
adapter.log.debug(`value not changed ${id}, last-value=${adapter._influxDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
return;
}
} else if (adapter._influxDPs[id].lastLogTime) {
if ((state.ts !== state.lc) && (Math.abs(adapter._influxDPs[id].lastLogTime - state.ts) < settings.changesRelogInterval * 1000)) {
adapter.log.debug(`value not changed ${id}, last-value=${adapter._influxDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
adapter._influxDPs[id].skipped = state; // remember new timestamp
return;
}
if (state.ts !== state.lc) {
adapter.log.debug(`value-changed-relog ${id}, value=${state.val}, lastLogTime=${adapter._influxDPs[id].lastLogTime}, ts=${state.ts}`);
}
}
if (settings.changesMinDelta !== 0 && typeof state.val === 'number' && Math.abs(adapter._influxDPs[id].state.val - state.val) < settings.changesMinDelta) {
adapter.log.debug(`Min-Delta not reached ${id}, last-value=${adapter._influxDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
adapter._influxDPs[id].skipped = state; // remember new timestamp
return;
} else if (typeof state.val === 'number') {
adapter.log.debug(`Min-Delta reached ${id}, last-value=${adapter._influxDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
} else {
adapter.log.debug(`Min-Delta ignored because no number ${id}, last-value=${adapter._influxDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
}
}
if (adapter._influxDPs[id].relogTimeout) {
clearTimeout(adapter._influxDPs[id].relogTimeout);
adapter._influxDPs[id].relogTimeout = null;
}
if (settings.changesRelogInterval > 0) {
adapter._influxDPs[id].relogTimeout = setTimeout(() => reLogHelper(adapter, id), settings.changesRelogInterval * 1000);
}
let ignoreDebounce = false;
if (timerRelog) {
state.ts = Date.now();
state.from = `system.adapter.${adapter.namespace}`;
adapter.log.debug(`timed-relog ${id}, value=${state.val}, lastLogTime=${adapter._influxDPs[id].lastLogTime}, ts=${state.ts}`);
ignoreDebounce = true;
} else {
if (settings.changesOnly && adapter._influxDPs[id].skipped) {
adapter._influxDPs[id].state = adapter._influxDPs[id].skipped;
pushHelper(adapter, id);
}
if (adapter._influxDPs[id].state && ((adapter._influxDPs[id].state.val === null && state.val !== null) || (adapter._influxDPs[id].state.val !== null && state.val === null))) {
ignoreDebounce = true;
} else if (!adapter._influxDPs[id].state && state.val === null) {
ignoreDebounce = true;
}
// only store state if really changed
adapter._influxDPs[id].state = state;
}
adapter._influxDPs[id].lastLogTime = state.ts;
adapter._influxDPs[id].skipped = null;
if (settings.debounce && !ignoreDebounce) {
// Discard changes in de-bounce time to store last stable value
adapter._influxDPs[id].timeout && clearTimeout(adapter._influxDPs[id].timeout);
adapter._influxDPs[id].timeout = setTimeout(() => pushHelper(adapter, id), settings.debounce);
} else {
pushHelper(adapter, id);
}
}
}
function reLogHelper(adapter, _id) {
if (!adapter._influxDPs[_id]) {
adapter.log.info(`non-existing id ${_id}`);
return;
}
adapter._influxDPs[_id].relogTimeout = null;
if (adapter._influxDPs[_id].skipped) {
adapter._influxDPs[_id].state = adapter._influxDPs[_id].skipped;
adapter._influxDPs[_id].state.from = `system.adapter.${adapter.namespace}`;
adapter._influxDPs[_id].skipped = null;
pushHistory(adapter, _id, adapter._influxDPs[_id].state, true);
}
else {
adapter.getForeignState(adapter._influxDPs[_id].realId, (err, state) => {
if (err) {
adapter.log.info(`init timed Relog: can not get State for ${_id}: ${err}`);
} else if (!state) {
adapter.log.info(`init timed Relog: disable relog because state not set so far for ${_id}: ${JSON.stringify(state)}`);
} else if (adapter._influxDPs[_id]) {
adapter.log.debug(`init timed Relog: getState ${_id}: Value=${state.val}, ack=${state.ack}, ts=${state.ts}, lc=${state.lc}`);
adapter._influxDPs[_id].state = state;
pushHistory(adapter, _id, adapter._influxDPs[_id].state, true);
}
});
}
}
function pushHelper(adapter, _id, cb) {
if (!adapter._influxDPs[_id] || !adapter._influxDPs[_id].state || !adapter._influxDPs[_id][adapter.namespace]) {
return cb && setImmediate(cb, `ID ${_id} not activated for logging`);
}
const _settings = adapter._influxDPs[_id][adapter.namespace];
// if it was not deleted in this time
adapter._influxDPs[_id].timeout = null;
if (adapter._influxDPs[_id].state.val === null) { // InfluxDB can not handle null values
return cb && setImmediate(cb, `null value for ${_id} can not be handled`);
}
if (adapter._influxDPs[_id].state.val === null) { // InfluxDB can not handle null values
return cb && setImmediate(cb, `null value for ${_id} can not be handled`);
}
if (typeof adapter._influxDPs[_id].state.val === 'number' && !isFinite(adapter._influxDPs[_id].state.val)) { // InfluxDB can not handle Infinite values
return cb && setImmediate(cb, `Non Finite value ${adapter._influxDPs[_id].state.val} for ${_id} can not be handled`);
}
if (typeof adapter._influxDPs[_id].state.val === 'object') {
adapter._influxDPs[_id].state.val = JSON.stringify(adapter._influxDPs[_id].state.val);
}
adapter.log.debug(`Datatype ${_id}: Currently: ${typeof adapter._influxDPs[_id].state.val}, StorageType: ${_settings.storageType}`);
if (typeof adapter._influxDPs[_id].state.val === 'string' && _settings.storageType !== 'String') {
adapter.log.debug(`Do Automatic Datatype conversion for ${_id}`);
const f = parseFloat(adapter._influxDPs[_id].state.val);
if (f == adapter._influxDPs[_id].state.val) {
adapter._influxDPs[_id].state.val = f;
} else if (adapter._influxDPs[_id].state.val === 'true') {
adapter._influxDPs[_id].state.val = true;
} else if (adapter._influxDPs[_id].state.val === 'false') {
adapter._influxDPs[_id].state.val = false;
}
}
if (_settings.storageType === 'String' && typeof adapter._influxDPs[_id].state.val !== 'string') {
adapter._influxDPs[_id].state.val = adapter._influxDPs[_id].state.val.toString();
}
else if (_settings.storageType === 'Number' && typeof adapter._influxDPs[_id].state.val !== 'number') {
if (typeof adapter._influxDPs[_id].state.val === 'boolean') {
adapter._influxDPs[_id].state.val = adapter._influxDPs[_id].state.val?1:0;
}
else {
adapter.log.info(`Do not store value "${adapter._influxDPs[_id].state.val}" for ${_id} because no number`);
return cb && setImmediate(cb, `do not store value for ${_id} because no number`);
}
}
else if (_settings.storageType === 'Boolean' && typeof adapter._influxDPs[_id].state.val !== 'boolean') {
adapter._influxDPs[_id].state.val = !!adapter._influxDPs[_id].state.val;
}
pushValueIntoDB(adapter, _id, adapter._influxDPs[_id].state, () =>
cb && setImmediate(cb));
}
function pushValueIntoDB(adapter, id, state, cb) {
if (!adapter._client) {
adapter.log.warn('No connection to DB');
return cb && cb('No connection to DB');
}
if (state.val === null || state.val === undefined) {
return cb && cb('InfluxDB can not handle null/non-existing values');
} // InfluxDB can not handle null/non-existing values
if (typeof state.val === 'number' && !isFinite(state.val)) {
return cb && cb(`InfluxDB can not handle non finite values like ${state.val}`);
}
if (adapter._influxDPs[id] && adapter._influxDPs[id][adapter.namespace] && adapter._influxDPs[id][adapter.namespace].ignoreZero && state.val === 0) {
adapter.log.debug(`pushValueIntoDB called for ${id} was ignored because the value zero or null`);
return cb && cb();
} else
if (state && adapter._influxDPs[id] && adapter._influxDPs[id][adapter.namespace] && adapter._influxDPs[id][adapter.namespace].ignoreBelowZero && typeof state.val === 'number' && state.val < 0) {
adapter.log.debug(`pushValueIntoDB called for ${id} and state: ${JSON.stringify(state)} was ignored because the value is below 0`);
return cb && cb();
}
state.ts = parseInt(state.ts, 10);
// if less 2000.01.01 00:00:00
if (state.ts < 946681200000) state.ts *= 1000;
if (typeof state.val === 'object') {
state.val = JSON.stringify(state.val);
}
/*
if (state.val === 'true') {
state.val = true;
} else if (state.val === 'false') {
state.val = false;
} else {
// try to convert to float
const f = parseFloat(state.val);
if (f == state.val) state.val = f;
}*/
//adapter.log.debug('write value ' + state.val + ' for ' + id);
const influxFields = {
value: state.val,
time: new Date(state.ts),
from: state.from || '',
q: state.q || 0,
ack: !!state.ack
};
if ((adapter._conflictingPoints[id] || adapter.config.seriesBufferMax === 0) && (adapter._connected && adapter._client.request && adapter._client.request.getHostsAvailable().length > 0)) {
if (adapter.config.seriesBufferMax !== 0) {
adapter.log.debug(`Direct writePoint("${id} - ${influxFields.value} / ${influxFields.time}")`);
}
writeOnePointForID(adapter, id, influxFields, true, cb);
} else {
addPointToSeriesBuffer(adapter, id, influxFields, cb);
}
}
function addPointToSeriesBuffer(adapter, id, stateObj, cb) {
if ((adapter._conflictingPoints[id] || adapter.config.seriesBufferMax === 0) && (adapter._connected && adapter._client.request && adapter._client.request.getHostsAvailable().length > 0)) {
if (adapter.config.seriesBufferMax !== 0) {
adapter.log.debug(`Direct writePoint("${id} - ${stateObj.value} / ${stateObj.time}")`);
}
return void writeOnePointForID(adapter, id, stateObj, true, cb);
}
if (!adapter._seriesBuffer[id]) {
adapter._seriesBuffer[id] = [];
}
adapter._seriesBuffer[id].push([stateObj]);
adapter._seriesBufferCounter++;
if (adapter._seriesBufferCounter > adapter.config.seriesBufferMax && adapter._connected && adapter._client.request && adapter._client.request.getHostsAvailable().length > 0 && !adapter._seriesBufferFlushPlanned) {
// flush out
adapter._seriesBufferFlushPlanned = true;
setImmediate(() => storeBufferedSeries(adapter, cb));
} else {
cb && cb();
}
}
function storeBufferedSeries(adapter, id, cb) {
if (typeof id === 'function') {
cb = id;
id = null;
}
if (id && (!adapter._seriesBuffer[id] || !adapter._seriesBuffer[id].length)) {
return cb && cb();
}
if (Object.keys(adapter._seriesBuffer).length === 0) {
return cb && cb();
}
if (!adapter._client || adapter._client.request.getHostsAvailable().length === 0) {
setConnected(adapter, false);
adapter.log.info('Currently no hosts available, try later');
adapter._seriesBufferFlushPlanned = false;
return cb && cb('Currently no hosts available, try later');
}
if (!adapter._connected) {
adapter.log.info('Not connected to InfluxDB, try later');
adapter._seriesBufferFlushPlanned = false;
return cb && cb('Not connected to InfluxDB, try later');
}
if (id) {
const idSeries = adapter._seriesBuffer[id];
adapter._seriesBuffer[id] = [];
adapter.log.debug(`Store ${idSeries.length} buffered influxDB history points for ${id}`);
adapter._seriesBufferCounter -= idSeries.length;
writeSeriesPerID(adapter, id, idSeries, cb);
return;
}
adapter._seriesBufferChecker && clearInterval(adapter._seriesBufferChecker);
adapter.log.info(`Store ${adapter._seriesBufferCounter} buffered influxDB history points`);
const currentBuffer = adapter._seriesBuffer;
if (adapter._seriesBufferCounter > 15000) {
// if we have too many data points in buffer; we better writer them per id
adapter.log.info(`Too many data points (${adapter._seriesBufferCounter}) to write at once; write per ID`);
writeAllSeriesPerID(adapter, currentBuffer, cb);
} else {
writeAllSeriesAtOnce(adapter, currentBuffer, cb);
}
adapter._seriesBuffer = {};
adapter._seriesBufferCounter = 0;
adapter._seriesBufferFlushPlanned = false;
adapter._seriesBufferChecker = setInterval(() =>
storeBufferedSeries(adapter), adapter.config.seriesBufferFlushInterval * 1000);