iobroker.sql 3.0.1 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +142 -428
  3. package/admin/i18n/de/translations.json +1 -1
  4. package/admin/i18n/en/translations.json +1 -1
  5. package/admin/i18n/es/translations.json +12 -12
  6. package/admin/i18n/fr/translations.json +1 -1
  7. package/admin/i18n/it/translations.json +1 -1
  8. package/admin/i18n/nl/translations.json +1 -1
  9. package/admin/i18n/pt/translations.json +1 -1
  10. package/admin/i18n/ru/translations.json +1 -1
  11. package/admin/jsonConfig.json +423 -321
  12. package/admin/words.js +12 -12
  13. package/build/lib/aggregate.js +1484 -0
  14. package/build/lib/aggregate.js.map +1 -0
  15. package/build/lib/connection-factory.js +7 -0
  16. package/build/lib/connection-factory.js.map +1 -0
  17. package/build/lib/mssql-client.js +67 -0
  18. package/build/lib/mssql-client.js.map +1 -0
  19. package/build/lib/mssql.js +267 -0
  20. package/build/lib/mssql.js.map +1 -0
  21. package/build/lib/mysql-client.js +61 -0
  22. package/build/lib/mysql-client.js.map +1 -0
  23. package/build/lib/mysql.js +245 -0
  24. package/build/lib/mysql.js.map +1 -0
  25. package/build/lib/postgresql-client.js +56 -0
  26. package/build/lib/postgresql-client.js.map +1 -0
  27. package/build/lib/postgresql.js +241 -0
  28. package/build/lib/postgresql.js.map +1 -0
  29. package/build/lib/sql-client-pool.js +369 -0
  30. package/build/lib/sql-client-pool.js.map +1 -0
  31. package/build/lib/sql-client.js +110 -0
  32. package/build/lib/sql-client.js.map +1 -0
  33. package/build/lib/sqlite.js +244 -0
  34. package/build/lib/sqlite.js.map +1 -0
  35. package/build/lib/sqlite3-client.js +68 -0
  36. package/build/lib/sqlite3-client.js.map +1 -0
  37. package/build/main.js +3624 -0
  38. package/build/main.js.map +1 -0
  39. package/docker-compose.yaml +57 -0
  40. package/io-package.json +54 -31
  41. package/package.json +28 -20
  42. package/admin/.gitignore +0 -0
  43. package/lib/aggregate.js +0 -1000
  44. package/lib/mssql-client.js +0 -61
  45. package/lib/mssql.js +0 -278
  46. package/lib/mysql-client.js +0 -62
  47. package/lib/mysql.js +0 -263
  48. package/lib/postgresql-client.js +0 -202
  49. package/lib/postgresql.js +0 -260
  50. package/lib/sqlite.js +0 -260
  51. package/lib/tools.js +0 -99
  52. package/main.js +0 -3469
package/main.js DELETED
@@ -1,3469 +0,0 @@
1
- /* jshint -W097 */
2
- /* jshint strict: false */
3
- /* jslint node: true */
4
- 'use strict';
5
-
6
- const utils = require('@iobroker/adapter-core'); // Get common adapter utils
7
- const adapterName = require('./package.json').name.split('.').pop();
8
- const SQL = require('sql-client');
9
- const commons = require('./lib/aggregate');
10
- const fs = require('fs');
11
- const path = require('path');
12
- let SQLFuncs = null;
13
-
14
- const clients = {
15
- postgresql: {name: 'PostgreSQLClient', multiRequests: true},
16
- mysql: {name: 'MySQL2Client', multiRequests: true},
17
- sqlite: {name: 'SQLite3Client', multiRequests: false},
18
- mssql: {name: 'MSSQLClient', multiRequests: true}
19
- };
20
-
21
- const types = {
22
- number: 0,
23
- string: 1,
24
- boolean: 2,
25
- object: 1,
26
- };
27
-
28
- const dbNames = [
29
- 'ts_number',
30
- 'ts_string',
31
- 'ts_bool',
32
- ];
33
-
34
- const storageTypes = [
35
- 'Number',
36
- 'String',
37
- 'Boolean',
38
- ];
39
-
40
- const sqlDPs = {};
41
- const from = {};
42
- const MAXTASKS = 100;
43
- const tasks = [];
44
- const tasksReadType = [];
45
- const tasksStart = [];
46
- const isFromRunning = {};
47
- const aliasMap = {};
48
-
49
- let finished = false;
50
- let connected = null;
51
- let multiRequests = true;
52
- let subscribeAll = false;
53
- let clientPool;
54
- let reconnectTimeout = null;
55
- let testConnectTimeout = null;
56
- let dpOverviewTimeout = null;
57
- let bufferChecker = null;
58
- let activeConnections = 0;
59
- let poolBorrowGuard = []; // required until https://github.com/intellinote/sql-client/issues/7 is fixed
60
- const logConnectionUsage = true;
61
-
62
- function isEqual(a, b) {
63
- //console.log('Compare ' + JSON.stringify(a) + ' with ' + JSON.stringify(b));
64
- // Create arrays of property names
65
- if (a === null || a === undefined || b === null || b === undefined) {
66
- return a === b;
67
- }
68
-
69
- const aProps = Object.getOwnPropertyNames(a);
70
- const bProps = Object.getOwnPropertyNames(b);
71
-
72
- // If number of properties is different,
73
- // objects are not equivalent
74
- if (aProps.length !== bProps.length) {
75
- //console.log('num props different: ' + JSON.stringify(aProps) + ' / ' + JSON.stringify(bProps));
76
- return false;
77
- }
78
-
79
- for (let i = 0; i < aProps.length; i++) {
80
- const propName = aProps[i];
81
-
82
- if (typeof a[propName] !== typeof b[propName]) {
83
- //console.log('type props ' + propName + ' different');
84
- return false;
85
- } else
86
- if (typeof a[propName] === 'object') {
87
- if (!isEqual(a[propName], b[propName])) {
88
- return false;
89
- }
90
- } else {
91
- // If values of same property are not equal,
92
- // objects are not equivalent
93
- if (a[propName] !== b[propName]) {
94
- //console.log('props ' + propName + ' different');
95
- return false;
96
- }
97
- }
98
- }
99
-
100
- // If we made it this far, objects
101
- // are considered equivalent
102
- return true;
103
- }
104
-
105
- let adapter;
106
- function startAdapter(options) {
107
- options = options || {};
108
-
109
- Object.assign(options, {name: adapterName});
110
-
111
- adapter = new utils.Adapter(options);
112
-
113
- adapter.on('objectChange', (id, obj) => {
114
- let tmpState;
115
- const now = Date.now();
116
- const formerAliasId = aliasMap[id] ? aliasMap[id] : id;
117
-
118
- 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) {
119
- const realId = id;
120
- let checkForRemove = true;
121
-
122
- if (obj.common.custom && obj.common.custom[adapter.namespace] && obj.common.custom[adapter.namespace].aliasId) {
123
- if (obj.common.custom[adapter.namespace].aliasId !== id) {
124
- aliasMap[id] = obj.common.custom[adapter.namespace].aliasId;
125
- adapter.log.debug(`Registered Alias: ${id} --> ${aliasMap[id]}`);
126
- id = aliasMap[id];
127
- checkForRemove = false;
128
- } else {
129
- adapter.log.warn(`Ignoring Alias-ID because identical to ID for ${id}`);
130
- obj.common.custom[adapter.namespace].aliasId = '';
131
- }
132
- }
133
-
134
- if (checkForRemove && aliasMap[id]) {
135
- adapter.log.debug(`Removed Alias: ${id} !-> ${aliasMap[id]}`);
136
- delete aliasMap[id];
137
- }
138
-
139
- if (!(sqlDPs[formerAliasId] && sqlDPs[formerAliasId][adapter.namespace]) && !subscribeAll) {
140
- // un-subscribe
141
- for (const _id in sqlDPs) {
142
- if (sqlDPs.hasOwnProperty(_id) && sqlDPs.hasOwnProperty(sqlDPs[_id].realId)) {
143
- adapter.unsubscribeForeignStates(sqlDPs[_id].realId);
144
- }
145
- }
146
- subscribeAll = true;
147
- adapter.subscribeForeignStates('*');
148
- }
149
-
150
- if (sqlDPs[id] && sqlDPs[id].index === undefined) {
151
- getId(id, sqlDPs[id].dbtype, () => reInit(id, realId, formerAliasId, obj));
152
- } else {
153
- reInit(id, realId, formerAliasId, obj);
154
- }
155
- } else {
156
- if (aliasMap[id]) {
157
- adapter.log.debug(`Removed Alias: ${id} !-> ${aliasMap[id]}`);
158
- delete aliasMap[id];
159
- }
160
-
161
- id = formerAliasId;
162
-
163
- if (sqlDPs[id] && sqlDPs[id][adapter.namespace]) {
164
- adapter.log.info(`disabled logging of ${id}`);
165
- if (sqlDPs[id].relogTimeout) {
166
- clearTimeout(sqlDPs[id].relogTimeout);
167
- sqlDPs[id].relogTimeout = null;
168
- }
169
- if (sqlDPs[id].timeout) {
170
- clearTimeout(sqlDPs[id].timeout);
171
- sqlDPs[id].timeout = null;
172
- }
173
-
174
- tmpState = Object.assign({}, sqlDPs[id].state);
175
- const state = sqlDPs[id].state ? tmpState : null;
176
-
177
- if (sqlDPs[id][adapter.namespace]) {
178
- sqlDPs[id][adapter.namespace].enabled = false;
179
- if (sqlDPs[id].skipped && !sqlDPs[id][adapter.namespace].disableSkippedValueLogging) {
180
- pushValueIntoDB(id, sqlDPs[id].skipped, false, true);
181
- sqlDPs[id].skipped = null;
182
- }
183
-
184
- if (adapter.config.writeNulls) {
185
- const nullValue = {
186
- val: null,
187
- ts: now,
188
- lc: now,
189
- q: 0x40,
190
- from: `system.adapter.${adapter.namespace}`
191
- };
192
-
193
- if (sqlDPs[id][adapter.namespace].changesOnly && state && state.val !== null) {
194
- (function (_id, _state, _nullValue) {
195
- _state.ts = now;
196
- _state.from = `system.adapter.${adapter.namespace}`;
197
- nullValue.ts += 4;
198
- nullValue.lc += 4; // because of MS SQL
199
- adapter.log.debug(`Write 1/2 "${_state.val}" _id: ${_id}`);
200
- pushValueIntoDB(_id, _state, false, true, () => {
201
- // terminate values with null to indicate adapter stop. timestamp + 1
202
- adapter.log.debug(`Write 2/2 "null" _id: ${_id}`);
203
- pushValueIntoDB(_id, _nullValue, () => delete sqlDPs[id]);
204
- });
205
- })(id, state, nullValue);
206
- } else {
207
- // terminate values with null to indicate adapter stop. timestamp + 1
208
- adapter.log.debug(`Write 0 NULL _id: ${id}`);
209
- pushValueIntoDB(id, nullValue, () => delete sqlDPs[id]);
210
- }
211
- } else {
212
- storeCached(id, () => delete sqlDPs[id]);
213
- }
214
- } else {
215
- delete sqlDPs[id];
216
- }
217
- }
218
- }
219
- });
220
-
221
- adapter.on('stateChange', (id, state) => {
222
- id = aliasMap[id] ? aliasMap[id] : id;
223
- pushHistory(id, state);
224
- });
225
-
226
- adapter.on('unload', callback => finish(callback));
227
-
228
- adapter.on('ready', () => main());
229
-
230
- adapter.on('message', msg => processMessage(msg));
231
-
232
- return adapter;
233
- }
234
-
235
- function borrowClientFromPool(callback) {
236
- if (typeof callback !== 'function') {
237
- return;
238
- }
239
-
240
- if (!clientPool) {
241
- setConnected(false);
242
- return callback('No database connection');
243
- }
244
- setConnected(true);
245
-
246
- if (activeConnections >= adapter.config.maxConnections) {
247
- logConnectionUsage && adapter.log.debug(`Borrow connection not possible: ${activeConnections} >= Max - Store for Later`);
248
- poolBorrowGuard.push(callback);
249
- return;
250
- }
251
- activeConnections++;
252
- logConnectionUsage && adapter.log.debug(`Borrow connection from pool: ${activeConnections} now`);
253
- clientPool.borrow((err, client) => {
254
- if (!err && client) {
255
- // make sure we always have at least one error listener to prevent crashes
256
- if (client.on && client.listenerCount && client.listenerCount('error') === 0) {
257
- client.on('error', err =>
258
- adapter.log.warn(`SQL client error: ${err}`));
259
- }
260
- } else if (!client) {
261
- activeConnections--;
262
- }
263
-
264
- callback(err, client);
265
- });
266
- }
267
-
268
- function returnClientToPool(client) {
269
- if (client) {
270
- activeConnections--;
271
- }
272
- logConnectionUsage && adapter.log.debug(`Return connection to pool: ${activeConnections} now`);
273
- if (clientPool && client) {
274
- if (poolBorrowGuard.length) {
275
- activeConnections++;
276
- logConnectionUsage && adapter.log.debug(`Borrow returned connection directly: ${activeConnections} now`);
277
- const callback = poolBorrowGuard.shift();
278
- callback(null, client);
279
- } else {
280
- try {
281
- clientPool.return(client);
282
- } catch (err) {
283
- // Ignore
284
- }
285
- }
286
- }
287
- }
288
-
289
- function reInit(id, realId, formerAliasId, obj) {
290
-
291
- // maxLength
292
- if (!obj.common.custom[adapter.namespace].maxLength && obj.common.custom[adapter.namespace].maxLength !== '0' && obj.common.custom[adapter.namespace].maxLength !== 0) {
293
- obj.common.custom[adapter.namespace].maxLength = parseInt(adapter.config.maxLength, 10) || 0;
294
- } else {
295
- obj.common.custom[adapter.namespace].maxLength = parseInt(obj.common.custom[adapter.namespace].maxLength, 10);
296
- }
297
-
298
- // retention
299
- if (obj.common.custom[adapter.namespace].retention || obj.common.custom[adapter.namespace].retention === 0) {
300
- obj.common.custom[adapter.namespace].retention = parseInt(obj.common.custom[adapter.namespace].retention, 10) || 0;
301
- } else {
302
- obj.common.custom[adapter.namespace].retention = adapter.config.retention;
303
- }
304
- if (obj.common.custom[adapter.namespace].retention === -1) {
305
- // customRetentionDuration
306
- if (obj.common.custom[adapter.namespace].customRetentionDuration !== undefined && obj.common.custom[adapter.namespace].customRetentionDuration !== null && obj.common.custom[adapter.namespace].customRetentionDuration !== '') {
307
- obj.common.custom[adapter.namespace].customRetentionDuration = parseInt(obj.common.custom[adapter.namespace].customRetentionDuration, 10) || 0;
308
- } else {
309
- obj.common.custom[adapter.namespace].customRetentionDuration = adapter.config.customRetentionDuration;
310
- }
311
- obj.common.custom[adapter.namespace].retention = obj.common.custom[adapter.namespace].customRetentionDuration * 24 * 60 * 60
312
- }
313
-
314
- // debounceTime and debounce compatibility handling
315
- if (!obj.common.custom[adapter.namespace].blockTime && obj.common.custom[adapter.namespace].blockTime !== '0' && obj.common.custom[adapter.namespace].blockTime !== 0) {
316
- if (!obj.common.custom[adapter.namespace].debounce && obj.common.custom[adapter.namespace].debounce !== '0' && obj.common.custom[adapter.namespace].debounce !== 0) {
317
- obj.common.custom[adapter.namespace].blockTime = parseInt(adapter.config.blockTime, 10) || 0;
318
- } else {
319
- obj.common.custom[adapter.namespace].blockTime = parseInt(obj.common.custom[adapter.namespace].debounce, 10) || 0;
320
- }
321
- } else {
322
- obj.common.custom[adapter.namespace].blockTime = parseInt(obj.common.custom[adapter.namespace].blockTime, 10) || 0;
323
- }
324
- if (!obj.common.custom[adapter.namespace].debounceTime && obj.common.custom[adapter.namespace].debounceTime !== '0' && obj.common.custom[adapter.namespace].debounceTime !== 0) {
325
- obj.common.custom[adapter.namespace].debounceTime = parseInt(adapter.config.debounceTime, 10) || 0;
326
- } else {
327
- obj.common.custom[adapter.namespace].debounceTime = parseInt(obj.common.custom[adapter.namespace].debounceTime, 10) || 0;
328
- }
329
-
330
- // changesOnly
331
- obj.common.custom[adapter.namespace].changesOnly = obj.common.custom[adapter.namespace].changesOnly === 'true' || obj.common.custom[adapter.namespace].changesOnly === true;
332
-
333
- // ignoreZero
334
- obj.common.custom[adapter.namespace].ignoreZero = obj.common.custom[adapter.namespace].ignoreZero === 'true' || obj.common.custom[adapter.namespace].ignoreZero === true;
335
-
336
- // round
337
- if (obj.common.custom[adapter.namespace].round !== null && obj.common.custom[adapter.namespace].round !== undefined && obj.common.custom[adapter.namespace] !== '') {
338
- obj.common.custom[adapter.namespace].round = parseInt(obj.common.custom[adapter.namespace], 10);
339
- if (!isFinite(obj.common.custom[adapter.namespace].round) || obj.common.custom[adapter.namespace].round < 0) {
340
- obj.common.custom[adapter.namespace].round = adapter.config.round;
341
- } else {
342
- obj.common.custom[adapter.namespace].round = Math.pow(10, parseInt(obj.common.custom[adapter.namespace].round, 10));
343
- }
344
- } else {
345
- obj.common.custom[adapter.namespace].round = adapter.config.round;
346
- }
347
-
348
- // ignoreAboveNumber
349
- if (obj.common.custom[adapter.namespace].ignoreAboveNumber !== undefined && obj.common.custom[adapter.namespace].ignoreAboveNumber !== null && obj.common.custom[adapter.namespace].ignoreAboveNumber !== '') {
350
- obj.common.custom[adapter.namespace].ignoreAboveNumber = parseFloat(obj.common.custom[adapter.namespace].ignoreAboveNumber) || null;
351
- }
352
-
353
- // ignoreBelowNumber incl. ignoreBelowZero compatibility handling
354
- if (obj.common.custom[adapter.namespace].ignoreBelowNumber !== undefined && obj.common.custom[adapter.namespace].ignoreBelowNumber !== null && obj.common.custom[adapter.namespace].ignoreBelowNumber !== '') {
355
- obj.common.custom[adapter.namespace].ignoreBelowNumber = parseFloat(obj.common.custom[adapter.namespace].ignoreBelowNumber) || null;
356
- } else if (obj.common.custom[adapter.namespace].ignoreBelowZero === 'true' || obj.common.custom[adapter.namespace].ignoreBelowZero === true) {
357
- obj.common.custom[adapter.namespace].ignoreBelowNumber = 0;
358
- }
359
-
360
- // disableSkippedValueLogging
361
- if (obj.common.custom[adapter.namespace].disableSkippedValueLogging !== undefined && obj.common.custom[adapter.namespace].disableSkippedValueLogging !== null && obj.common.custom[adapter.namespace].disableSkippedValueLogging !== '') {
362
- obj.common.custom[adapter.namespace].disableSkippedValueLogging = obj.common.custom[adapter.namespace].disableSkippedValueLogging === 'true' || obj.common.custom[adapter.namespace].disableSkippedValueLogging === true;
363
- } else {
364
- obj.common.custom[adapter.namespace].disableSkippedValueLogging = adapter.config.disableSkippedValueLogging;
365
- }
366
-
367
- // enableDebugLogs
368
- if (obj.common.custom[adapter.namespace].enableDebugLogs !== undefined && obj.common.custom[adapter.namespace].enableDebugLogs !== null && obj.common.custom[adapter.namespace].enableDebugLogs !== '') {
369
- obj.common.custom[adapter.namespace].enableDebugLogs = obj.common.custom[adapter.namespace].enableDebugLogs === 'true' || obj.common.custom[adapter.namespace].enableDebugLogs === true;
370
- } else {
371
- obj.common.custom[adapter.namespace].enableDebugLogs = adapter.config.enableDebugLogs;
372
- }
373
-
374
- // changesRelogInterval
375
- if (obj.common.custom[adapter.namespace].changesRelogInterval || obj.common.custom[adapter.namespace].changesRelogInterval === 0) {
376
- obj.common.custom[adapter.namespace].changesRelogInterval = parseInt(obj.common.custom[adapter.namespace].changesRelogInterval, 10) || 0;
377
- } else {
378
- obj.common.custom[adapter.namespace].changesRelogInterval = adapter.config.changesRelogInterval;
379
- }
380
-
381
- // changesMinDelta
382
- if (obj.common.custom[adapter.namespace].changesMinDelta || obj.common.custom[adapter.namespace].changesMinDelta === 0) {
383
- obj.common.custom[adapter.namespace].changesMinDelta = parseFloat(obj.common.custom[adapter.namespace].changesMinDelta.toString().replace(/,/g, '.')) || 0;
384
- } else {
385
- obj.common.custom[adapter.namespace].changesMinDelta = adapter.config.changesMinDelta;
386
- }
387
-
388
- // storageType
389
- if (!obj.common.custom[adapter.namespace].storageType) {
390
- obj.common.custom[adapter.namespace].storageType = false;
391
- }
392
-
393
- // add one day if retention is too small
394
- if (obj.common.custom[adapter.namespace].retention && obj.common.custom[adapter.namespace].retention <= 604800) {
395
- obj.common.custom[adapter.namespace].retention += 86400;
396
- }
397
-
398
- if (sqlDPs[formerAliasId] &&
399
- sqlDPs[formerAliasId][adapter.namespace] &&
400
- isEqual(obj.common.custom[adapter.namespace], sqlDPs[formerAliasId][adapter.namespace])) {
401
- return obj.common.custom[adapter.namespace].enableDebugLogs && adapter.log.debug(`Object ${id} unchanged. Ignore`);
402
- }
403
-
404
- // relogTimeout
405
- if (sqlDPs[formerAliasId] && sqlDPs[formerAliasId].relogTimeout) {
406
- clearTimeout(sqlDPs[formerAliasId].relogTimeout);
407
- sqlDPs[formerAliasId].relogTimeout = null;
408
- }
409
-
410
- const writeNull = !(sqlDPs[id] && sqlDPs[id][adapter.namespace]);
411
- const state = sqlDPs[id] ? sqlDPs[id].state : null;
412
- const list = sqlDPs[id] ? sqlDPs[id].list : null;
413
- const inFlight = sqlDPs[id] ? sqlDPs[id].inFlight: null;
414
- const timeout = sqlDPs[id] ? sqlDPs[id].timeout : null;
415
- const ts = sqlDPs[id] ? sqlDPs[id].ts : null;
416
- const lastCheck = sqlDPs[id] ? sqlDPs[id].lastCheck : null;
417
-
418
- sqlDPs[id] = obj.common.custom;
419
- sqlDPs[id].state = state;
420
- sqlDPs[id].list = list || [];
421
- sqlDPs[id].inFlight = inFlight || {};
422
- sqlDPs[id].timeout = timeout;
423
- sqlDPs[id].ts = ts;
424
- sqlDPs[id].realId = realId;
425
- sqlDPs[id].lastCheck = lastCheck || Date.now() - Math.floor(Math.random() * 21600000/* 6 hours */); // randomize lastCheck to avoid all datapoints to be checked at same timepoint
426
- ;
427
-
428
- // changesRelogInterval
429
- if (sqlDPs[id][adapter.namespace].changesOnly && sqlDPs[id][adapter.namespace].changesRelogInterval > 0) {
430
- sqlDPs[id].relogTimeout = setTimeout(reLogHelper, (sqlDPs[id][adapter.namespace].changesRelogInterval * 500 * Math.random()) + sqlDPs[id][adapter.namespace].changesRelogInterval * 500, id);
431
- }
432
-
433
- if (writeNull && adapter.config.writeNulls) {
434
- writeNulls(id);
435
- }
436
-
437
- adapter.log.info(`enabled logging of ${id}, Alias=${id !== realId}, WriteNulls=${writeNull}`);
438
- }
439
-
440
- function setConnected(isConnected) {
441
- if (connected !== isConnected) {
442
- connected = isConnected;
443
- adapter.setState('info.connection', connected, true);
444
- }
445
- }
446
-
447
- let postgresDbCreated = false;
448
- function connect(callback) {
449
- if (reconnectTimeout) {
450
- clearTimeout(reconnectTimeout);
451
- reconnectTimeout = null;
452
- }
453
-
454
- if (!clientPool) {
455
- setConnected(false);
456
-
457
- let params = {
458
- server: adapter.config.host, // needed for MSSQL
459
- host: adapter.config.host, // needed for PostgreSQL , MySQL
460
- user: adapter.config.user || '',
461
- password: adapter.config.password || '',
462
- max_idle: (adapter.config.dbtype === 'sqlite') ? 1 : 2
463
- };
464
-
465
- if (adapter.config.maxConnections) {
466
- params.max_active = adapter.config.maxConnections + 1; // we use our own Pool limiter logic, so let library have one more to not block us too early
467
- params.max_wait = 10000; // hard code for now
468
- params.when_exhausted = 'block';
469
- }
470
-
471
- if (adapter.config.port) {
472
- params.port = adapter.config.port;
473
- }
474
-
475
- if (!adapter.config.dbtype) {
476
- return adapter.log.error('DB Type is not defined!');
477
- } else
478
- if (!clients[adapter.config.dbtype] || !clients[adapter.config.dbtype].name) {
479
- return adapter.log.error(`Unknown type "${adapter.config.dbtype}"`);
480
- } else
481
- if (!SQL[clients[adapter.config.dbtype].name]) {
482
- return adapter.log.error(`SQL package "${clients[adapter.config.dbtype].name}" is not installed.`);
483
- }
484
-
485
- if (adapter.config.dbtype === 'postgresql') {
486
- params.database = 'postgres';
487
- if (adapter.config.encrypt) {
488
- params.ssl = {
489
- rejectUnauthorized: !!adapter.config.rejectUnauthorized
490
- };
491
- }
492
- } else if (adapter.config.dbtype === 'mssql') {
493
- params.options = {
494
- encrypt: !!adapter.config.encrypt,
495
- };
496
- if (adapter.config.encrypt) {
497
- params.options.trustServerCertificate = !adapter.config.rejectUnauthorized
498
- }
499
- } else if (adapter.config.dbtype === 'mysql') {
500
- if (adapter.config.encrypt) {
501
- params.ssl = {
502
- rejectUnauthorized: !!adapter.config.rejectUnauthorized
503
- };
504
- }
505
- }
506
-
507
- if (adapter.config.dbtype === 'sqlite') {
508
- params = getSqlLiteDir(adapter.config.fileName);
509
- } else
510
- // special solution for postgres. Connect first to Db "postgres", create new DB "iobroker" and then connect to "iobroker" DB.
511
- if (adapter.config.dbtype === 'postgresql' && !postgresDbCreated) {
512
- // connect first to DB postgres and create iobroker DB
513
- adapter.log.info(`Postgres connection options: ${JSON.stringify(params).replace(params.password, '****')}`);
514
- const _client = new SQL[clients[adapter.config.dbtype].name](params);
515
- _client.on && _client.on('error', err =>
516
- adapter.log.warn(`SQL client error: ${err}`));
517
-
518
- return _client.connect(err => {
519
- if (err) {
520
- adapter.log.error(err);
521
- reconnectTimeout && clearTimeout(reconnectTimeout);
522
- reconnectTimeout = setTimeout(() => connect(callback), 30000);
523
- return;
524
- }
525
-
526
- if (adapter.config.doNotCreateDatabase) {
527
- _client.disconnect();
528
- postgresDbCreated = true;
529
- reconnectTimeout && clearTimeout(reconnectTimeout);
530
- reconnectTimeout = setTimeout(() => connect(callback), 100);
531
- } else {
532
- _client.execute(`CREATE DATABASE ${adapter.config.dbname};`, (err /* , rows, fields */) => {
533
- _client.disconnect();
534
- if (err && err.code !== '42P04') { // if error not about yet exists
535
- postgresDbCreated = false;
536
- adapter.log.error(err);
537
- reconnectTimeout && clearTimeout(reconnectTimeout);
538
- reconnectTimeout = setTimeout(() => connect(callback), 30000);
539
- } else {
540
- postgresDbCreated = true;
541
- reconnectTimeout && clearTimeout(reconnectTimeout);
542
- reconnectTimeout = setTimeout(() => connect(callback), 100);
543
- }
544
- });
545
- }
546
- });
547
- }
548
-
549
- if (adapter.config.dbtype === 'postgresql') {
550
- params.database = adapter.config.dbname;
551
- }
552
-
553
- try {
554
- if (!clients[adapter.config.dbtype].name) {
555
- adapter.log.error(`Unknown SQL type selected: "${adapter.config.dbtype}"`);
556
- } else if (!SQL[`${clients[adapter.config.dbtype].name}Pool`]) {
557
- adapter.log.error(`Selected SQL DB was not installed properly: "${adapter.config.dbtype}". SQLite requires build tools on system. See README.md`);
558
- } else {
559
- clientPool = new SQL[`${clients[adapter.config.dbtype].name}Pool`](params);
560
-
561
- return clientPool.open(err => {
562
- activeConnections = 0;
563
- if (err) {
564
- clientPool = null;
565
- setConnected(false);
566
- adapter.log.error(err);
567
- reconnectTimeout && clearTimeout(reconnectTimeout);
568
- reconnectTimeout = setTimeout(() => connect(callback), 30000);
569
- } else {
570
- reconnectTimeout && clearTimeout(reconnectTimeout);
571
- reconnectTimeout = setImmediate(() => connect(callback));
572
- }
573
- });
574
- }
575
- } catch (ex) {
576
- if (ex.toString() === 'TypeError: undefined is not a function') {
577
- adapter.log.error(`Node.js DB driver for "${adapter.config.dbtype}" could not be installed.`);
578
- } else {
579
- adapter.log.error(ex.toString());
580
- adapter.log.error(ex.stack);
581
- }
582
- clientPool = null;
583
- activeConnections = 0;
584
- setConnected(false);
585
- reconnectTimeout && clearTimeout(reconnectTimeout);
586
- reconnectTimeout = setTimeout(() => connect(callback), 30000);
587
- return;
588
- }
589
- }
590
-
591
- allScripts(SQLFuncs.init(adapter.config.dbname, adapter.config.doNotCreateDatabase), err => {
592
- if (err) {
593
- //adapter.log.error(err);
594
- reconnectTimeout && clearTimeout(reconnectTimeout);
595
- reconnectTimeout = setTimeout(() => connect(callback), 30000);
596
- } else {
597
- adapter.log.info(`Connected to ${adapter.config.dbtype}`);
598
- // read all DB IDs and all FROM ids
599
- getAllIds(() =>
600
- getAllFroms(callback));
601
- }
602
- });
603
- }
604
-
605
- // Find sqlite data directory
606
- function getSqlLiteDir(fileName) {
607
- fileName = fileName || 'sqlite.db';
608
- fileName = fileName.replace(/\\/g, '/');
609
- if (fileName[0] === '/' || fileName.match(/^\w:\//)) {
610
- return fileName;
611
- } else {
612
- // normally /opt/iobroker/node_modules/iobroker.js-controller
613
- // but can be /example/ioBroker.js-controller
614
- let config = path.join(utils.getAbsoluteDefaultDataDir(), 'sqlite');
615
-
616
- // create sqlite directory
617
- if (!fs.existsSync(config)) {
618
- fs.mkdirSync(config);
619
- }
620
-
621
- return path.normalize(path.join(config, fileName));
622
- }
623
- }
624
-
625
- function testConnection(msg) {
626
- if (!msg.message.config) {
627
- return msg.callback && adapter.sendTo(msg.from, msg.command, {error: 'invalid config'}, msg.callback);
628
- }
629
-
630
- msg.message.config.port = parseInt(msg.message.config.port, 10) || 0;
631
- let params = {
632
- server: msg.message.config.host,
633
- host: msg.message.config.host,
634
- user: msg.message.config.user,
635
- password: msg.message.config.password
636
- };
637
-
638
- if (msg.message.config.port) {
639
- params.port = msg.message.config.port;
640
- }
641
-
642
- if (msg.message.config.dbtype === 'postgresql' && !SQL.PostgreSQLClient) {
643
- const postgres = require('./lib/postgresql-client');
644
- Object.keys(postgres)
645
- .filter(attr => !SQL[attr])
646
- .forEach(attr => SQL[attr] = postgres[attr]);
647
- } else if (msg.message.config.dbtype === 'mssql' && !SQL.MSSQLClient) {
648
- const mssql = require('./lib/mssql-client');
649
- Object.keys(mssql)
650
- .filter(attr => !SQL[attr])
651
- .forEach(attr => SQL[attr] = mssql[attr]);
652
- } else if (msg.message.config.dbtype === 'mysql' && !SQL.MySQL2Client) {
653
- const mysql = require('./lib/mysql-client');
654
- Object.keys(mysql)
655
- .filter(attr => !SQL[attr])
656
- .forEach(attr => SQL[attr] = mysql[attr]);
657
- }
658
-
659
- if (msg.message.config.dbtype === 'postgresql') {
660
- params.database = 'postgres';
661
- } else if (msg.message.config.dbtype === 'sqlite') {
662
- params = getSqlLiteDir(msg.message.config.fileName);
663
- }
664
-
665
- if (msg.message.config.dbtype === 'postgresql') {
666
- if (msg.message.config.encrypt) {
667
- params.ssl = {
668
- rejectUnauthorized: !!msg.message.config.rejectUnauthorized
669
- };
670
- }
671
- } else if (msg.message.config.dbtype === 'mssql') {
672
- params.options = {
673
- encrypt: !!msg.message.config.encrypt,
674
- };
675
- if (msg.message.config.encrypt) {
676
- params.options. trustServerCertificate= !msg.message.config.rejectUnauthorized
677
- }
678
- } else if (msg.message.config.dbtype === 'mysql') {
679
- if (msg.message.config.encrypt) {
680
- params.ssl = {
681
- rejectUnauthorized: !!msg.message.config.rejectUnauthorized
682
- };
683
- }
684
- }
685
-
686
- try {
687
- const client = new SQL[clients[msg.message.config.dbtype].name](params);
688
- client.on && client.on('error', err =>
689
- adapter.log.warn(`SQL client error: ${err}`));
690
-
691
- testConnectTimeout = setTimeout(() => {
692
- testConnectTimeout = null;
693
- adapter.sendTo(msg.from, msg.command, {error: 'connect timeout'}, msg.callback);
694
- }, 5000);
695
-
696
- client.connect(err => {
697
- if (err) {
698
- if (testConnectTimeout) {
699
- clearTimeout(testConnectTimeout);
700
- testConnectTimeout = null;
701
- }
702
- return adapter.sendTo(msg.from, msg.command, {error: err.toString()}, msg.callback);
703
- }
704
-
705
- client.execute('SELECT 2 + 3 AS x', (err /* , rows, fields */) => {
706
- client.disconnect();
707
-
708
- if (testConnectTimeout) {
709
- clearTimeout(testConnectTimeout);
710
- testConnectTimeout = null;
711
- return adapter.sendTo(msg.from, msg.command, {error: err ? err.toString() : null}, msg.callback);
712
- }
713
- });
714
- });
715
- } catch (ex) {
716
- if (testConnectTimeout) {
717
- clearTimeout(testConnectTimeout);
718
- testConnectTimeout = null;
719
- }
720
- if (ex.toString() === 'TypeError: undefined is not a function') {
721
- return adapter.sendTo(msg.from, msg.command, {error: 'Node.js DB driver could not be installed.'}, msg.callback);
722
- } else {
723
- return adapter.sendTo(msg.from, msg.command, {error: ex.toString()}, msg.callback);
724
- }
725
- }
726
- }
727
-
728
- function destroyDB(msg) {
729
- try {
730
- allScripts(SQLFuncs.destroy(adapter.config.dbname), err => {
731
- if (err) {
732
- adapter.log.error(err);
733
- adapter.sendTo(msg.from, msg.command, {error: err.toString()}, msg.callback);
734
- } else {
735
- adapter.sendTo(msg.from, msg.command, {error: null, result: 'deleted'}, msg.callback);
736
- // restart adapter
737
- setTimeout(() =>
738
- adapter.getForeignObject(`system.adapter.${adapter.namespace}`, (err, obj) => {
739
- if (!err) {
740
- adapter.setForeignObject(obj._id, obj);
741
- } else {
742
- adapter.log.error(`Cannot read object "system.adapter.${adapter.namespace}": ${err}`);
743
- adapter.stop();
744
- }
745
- }), 2000);
746
- }
747
- });
748
- } catch (ex) {
749
- return adapter.sendTo(msg.from, msg.command, {error: ex.toString()}, msg.callback);
750
- }
751
- }
752
-
753
- function _userQuery(msg, callback) {
754
- try {
755
- if (typeof msg.message !== 'string' || !msg.message.length) {
756
- throw new Error('No query provided');
757
- }
758
- adapter.log.debug(msg.message);
759
-
760
- borrowClientFromPool((err, client) => {
761
- if (err) {
762
- adapter.sendTo(msg.from, msg.command, {error: err.toString()}, msg.callback);
763
- returnClientToPool(client);
764
- callback && callback();
765
- } else {
766
- client.execute(msg.message, (err, rows /* , fields */) => {
767
- if (rows && rows.rows) rows = rows.rows;
768
- returnClientToPool(client);
769
- //convert ts for postgresql and ms sqlserver
770
- if (!err && rows && rows[0] && typeof rows[0].ts === 'string') {
771
- for (let i = 0; i < rows.length; i++) {
772
- rows[i].ts = parseInt(rows[i].ts, 10);
773
- }
774
- }
775
- adapter.sendTo(msg.from, msg.command, {error: err ? err.toString() : null, result: rows}, msg.callback);
776
- callback && callback();
777
- });
778
- }
779
- });
780
- } catch (err) {
781
- adapter.sendTo(msg.from, msg.command, {error: err.toString()}, msg.callback);
782
- callback && callback();
783
- }
784
- }
785
-
786
- // execute custom query
787
- function query(msg) {
788
- if (!multiRequests) {
789
- if (tasks.length > MAXTASKS) {
790
- const error = `Cannot queue new requests, because more than ${MAXTASKS}`;
791
- adapter.log.error(error);
792
- adapter.sendTo(msg.from, msg.command, {error}, msg.callback);
793
- } else {
794
- tasks.push({operation: 'userQuery', msg});
795
- tasks.length === 1 && processTasks();
796
- }
797
- } else {
798
- _userQuery(msg);
799
- }
800
- }
801
-
802
- // one script
803
- function oneScript(script, cb) {
804
- try {
805
- borrowClientFromPool((err, client) => {
806
- if (err || !client) {
807
- clientPool && clientPool.close();
808
- activeConnections = 0;
809
- clientPool = null;
810
- setConnected(false);
811
- adapter.log.error(err);
812
- return cb && cb(err);
813
- }
814
-
815
- adapter.log.debug(script);
816
-
817
- client.execute(script, (err /* , rows, fields */) => {
818
- adapter.log.debug(`Response: ${JSON.stringify(err)}`);
819
- if (err) {
820
- // Database 'iobroker' already exists. Choose a different database name.
821
- if (err.number === 1801 ||
822
- //There is already an object named 'sources' in the database.
823
- err.number === 2714) {
824
- // do nothing
825
- err = null;
826
- } else
827
- if (err.message && err.message.match(/^SQLITE_ERROR: table [\w_]+ already exists$/)) {
828
- // do nothing
829
- err = null;
830
- } else
831
- if (err.errno == 1007 || err.errno == 1050) { // if database exists or table exists
832
- // do nothing
833
- err = null;
834
- } else
835
- if (err.code === '42P04') {// if database exists or table exists
836
- // do nothing
837
- err = null;
838
- }
839
- else if (err.code === '42P07') {
840
- const match = script.match(/CREATE\s+TABLE\s+(\w*)\s+\(/);
841
- if (match) {
842
- adapter.log.debug(`OK. Table "${match[1]}" yet exists`);
843
- err = null;
844
- } else {
845
- adapter.log.error(script);
846
- adapter.log.error(err);
847
- }
848
- } else if (script.startsWith('CREATE INDEX')) {
849
- adapter.log.info('Ignore Error on Create index. You might want to create the index yourself!');
850
- adapter.log.info(script);
851
- adapter.log.info(`${err.code}: ${err}`);
852
- err = null;
853
- } else {
854
- adapter.log.error(script);
855
- adapter.log.error(err);
856
- }
857
- }
858
- returnClientToPool(client);
859
- cb && cb(err);
860
- });
861
- });
862
- } catch (ex) {
863
- adapter.log.error(ex);
864
- cb && cb(ex);
865
- }
866
-
867
- }
868
-
869
- // all scripts
870
- function allScripts(scripts, index, cb) {
871
- if (typeof index === 'function') {
872
- cb = index;
873
- index = 0;
874
- }
875
- index = index || 0;
876
-
877
- if (scripts && index < scripts.length) {
878
- oneScript(scripts[index], err => {
879
- if (err) {
880
- cb && cb(err);
881
- } else {
882
- allScripts(scripts, index + 1, cb);
883
- }
884
- });
885
- } else {
886
- cb && cb();
887
- }
888
- }
889
-
890
- function finish(callback) {
891
-
892
- function allFinished() {
893
- if (clientPool) {
894
- clientPool.close();
895
- activeConnections = 0;
896
- clientPool = null;
897
- setConnected(false);
898
- }
899
- if (typeof finished === 'object') {
900
- setTimeout(cb => {
901
- for (let f = 0; f < cb.length; f++) {
902
- typeof cb[f] === 'function' && cb[f]();
903
- }
904
- }, 500, finished);
905
- finished = true;
906
- }
907
- }
908
-
909
- function finishId(id) {
910
- if (!sqlDPs[id]) {
911
- return;
912
- }
913
- if (sqlDPs[id].relogTimeout) {
914
- clearTimeout(sqlDPs[id].relogTimeout);
915
- sqlDPs[id].relogTimeout = null;
916
- }
917
- if (sqlDPs[id].timeout) {
918
- clearTimeout(sqlDPs[id].timeout);
919
- sqlDPs[id].timeout = null;
920
- }
921
- let tmpState = Object.assign({}, sqlDPs[id].state);
922
- const state = sqlDPs[id].state ? tmpState : null;
923
-
924
- if (sqlDPs[id].skipped && !(sqlDPs[id][adapter.namespace] && sqlDPs[id][adapter.namespace].disableSkippedValueLogging)) {
925
- count++;
926
- pushValueIntoDB(id, sqlDPs[id].skipped, false, true,() => {
927
- if (!--count) {
928
- pushValuesIntoDB(id, sqlDPs[id].list, () => {
929
- allFinished();
930
- });
931
- }
932
- });
933
- sqlDPs[id].skipped = null;
934
- }
935
-
936
- const nullValue = {val: null, ts: now, lc: now, q: 0x40, from: `system.adapter.${adapter.namespace}`};
937
-
938
- if (sqlDPs[id][adapter.namespace] && adapter.config.writeNulls) {
939
- if (sqlDPs[id][adapter.namespace].changesOnly && state && state.val !== null) {
940
- count++;
941
- (function (_id, _state, _nullValue) {
942
- _state.ts = now;
943
- _state.from = `system.adapter.${adapter.namespace}`;
944
- nullValue.ts += 4;
945
- nullValue.lc += 4; // because of MS SQL
946
- adapter.log.debug(`Write 1/2 "${_state.val}" _id: ${_id}`);
947
- pushValueIntoDB(_id, _state, false, true,() => {
948
- // terminate values with null to indicate adapter stop. timestamp + 1
949
- adapter.log.debug(`Write 2/2 "null" _id: ${_id}`);
950
- pushValueIntoDB(_id, _nullValue, false, true,() => {
951
- if (!--count) {
952
- pushValuesIntoDB(id, sqlDPs[id].list, () => {
953
- allFinished();
954
- });
955
- }
956
- });
957
- });
958
- })(id, state, nullValue);
959
- } else {
960
- // terminate values with null to indicate adapter stop. timestamp + 1
961
- count++;
962
- adapter.log.debug(`Write 0 NULL _id: ${id}`);
963
- pushValueIntoDB(id, nullValue, false, true,() => {
964
- if (!--count) {
965
- pushValuesIntoDB(id, sqlDPs[id].list, () => {
966
- allFinished();
967
- });
968
- }
969
- });
970
- }
971
- }
972
- }
973
-
974
- if (!subscribeAll) {
975
- for (const _id in sqlDPs) {
976
- if (sqlDPs.hasOwnProperty(_id) && sqlDPs.hasOwnProperty(sqlDPs[_id].realId)) {
977
- adapter.unsubscribeForeignStates(sqlDPs[_id].realId);
978
- }
979
- }
980
- } else {
981
- subscribeAll = false;
982
- adapter.unsubscribeForeignStates('*');
983
- }
984
-
985
- if (reconnectTimeout) {
986
- clearTimeout(reconnectTimeout);
987
- reconnectTimeout = null;
988
- }
989
- if (testConnectTimeout) {
990
- clearTimeout(testConnectTimeout);
991
- testConnectTimeout = null;
992
- }
993
- if (dpOverviewTimeout) {
994
- clearTimeout(dpOverviewTimeout);
995
- dpOverviewTimeout = null;
996
- }
997
- if (bufferChecker) {
998
- clearInterval(bufferChecker);
999
- bufferChecker = null;
1000
- }
1001
-
1002
- let count = 0;
1003
- if (finished) {
1004
- if (callback) {
1005
- if (finished === true) {
1006
- callback();
1007
- } else {
1008
- finished.push(callback);
1009
- }
1010
- }
1011
- return;
1012
- }
1013
- finished = [callback];
1014
- const now = Date.now();
1015
- let dpcount = 0;
1016
- let delay = 0;
1017
- for (const id in sqlDPs) {
1018
- if (!sqlDPs.hasOwnProperty(id)) {
1019
- continue;
1020
- }
1021
- dpcount++;
1022
- delay += (dpcount%50 === 0) ? 1000: 0;
1023
- setTimeout(finishId, delay, id);
1024
- }
1025
-
1026
- if (!dpcount && callback) {
1027
- if (clientPool) {
1028
- clientPool.close();
1029
- activeConnections = 0;
1030
- clientPool = null;
1031
- setConnected(false);
1032
- }
1033
- callback();
1034
- }
1035
- }
1036
-
1037
- function processMessage(msg) {
1038
- if (msg.command === 'features') {
1039
- adapter.sendTo(msg.from, msg.command, {supportedFeatures: ['update', 'delete', 'deleteRange', 'deleteAll', 'storeState']}, msg.callback);
1040
- } else
1041
- if (msg.command === 'getHistory') {
1042
- getHistory(msg);
1043
- } else if (msg.command === 'getCounter') {
1044
- getCounterDiff(msg);
1045
- } else if (msg.command === 'test') {
1046
- testConnection(msg);
1047
- } else if (msg.command === 'destroy') {
1048
- destroyDB(msg);
1049
- } else if (msg.command === 'query') {
1050
- query(msg);
1051
- } else if (msg.command === 'update') {
1052
- updateState(msg);
1053
- } else if (msg.command === 'delete') {
1054
- deleteState(msg);
1055
- } else if (msg.command === 'deleteAll') {
1056
- deleteStateAll(msg);
1057
- } else if (msg.command === 'deleteRange') {
1058
- deleteState(msg);
1059
- } else if (msg.command === 'storeState') {
1060
- storeState(msg);
1061
- } else if (msg.command === 'getDpOverview') {
1062
- getDpOverview(msg);
1063
- } else if (msg.command === 'enableHistory') {
1064
- enableHistory(msg);
1065
- } else if (msg.command === 'disableHistory') {
1066
- disableHistory(msg);
1067
- } else if (msg.command === 'getEnabledDPs') {
1068
- getEnabledDPs(msg);
1069
- } else if (msg.command === 'stopInstance') {
1070
- finish(() => {
1071
- if (msg.callback) {
1072
- adapter.sendTo(msg.from, msg.command, 'stopped', msg.callback);
1073
- setTimeout(() => adapter.stop(), 200);
1074
- }
1075
- });
1076
- }
1077
- }
1078
-
1079
- function processStartValues(callback) {
1080
- if (tasksStart && tasksStart.length) {
1081
- const task = tasksStart.shift();
1082
- if (sqlDPs[task.id][adapter.namespace].changesOnly) {
1083
- adapter.getForeignState(sqlDPs[task.id].realId, (err, state) => {
1084
- const now = task.now || Date.now();
1085
- pushHistory(task.id, {
1086
- val: null,
1087
- ts: state ? now - 4 : now, // 4 is because of MS SQL
1088
- lc: state ? now - 4 : now, // 4 is because of MS SQL
1089
- ack: true,
1090
- q: 0x40,
1091
- from: `system.adapter.${adapter.namespace}`,
1092
- });
1093
-
1094
- if (state) {
1095
- state.ts = now;
1096
- state.lc = now;
1097
- state.from = `system.adapter.${adapter.namespace}`;
1098
- pushHistory(task.id, state);
1099
- }
1100
-
1101
- setImmediate(processStartValues);
1102
- });
1103
- }
1104
- else {
1105
- const now = Date.now();
1106
- pushHistory(task.id, {
1107
- val: null,
1108
- ts: task.now || now,
1109
- lc: task.now || now,
1110
- ack: true,
1111
- q: 0x40,
1112
- from: `system.adapter.${adapter.namespace}`
1113
- });
1114
-
1115
- setImmediate(processStartValues);
1116
- }
1117
- if (sqlDPs[task.id][adapter.namespace] && sqlDPs[task.id][adapter.namespace].changesOnly && sqlDPs[task.id][adapter.namespace].changesRelogInterval > 0) {
1118
- sqlDPs[task.id].relogTimeout && clearTimeout(sqlDPs[task.id].relogTimeout);
1119
- sqlDPs[task.id].relogTimeout = setTimeout(reLogHelper, (sqlDPs[task.id][adapter.namespace].changesRelogInterval * 500 * Math.random()) + sqlDPs[task.id][adapter.namespace].changesRelogInterval * 500, task.id);
1120
- }
1121
- } else {
1122
- callback && callback();
1123
- }
1124
- }
1125
-
1126
- function writeNulls(id, now) {
1127
- if (!id) {
1128
- now = Date.now();
1129
-
1130
- Object.keys(sqlDPs)
1131
- .filter(_id => sqlDPs[_id] && sqlDPs[_id][adapter.namespace])
1132
- .forEach(_id => writeNulls(_id, now));
1133
- } else {
1134
- now = now || Date.now();
1135
-
1136
- tasksStart.push({id, now});
1137
-
1138
- if (tasksStart.length === 1 && connected) {
1139
- processStartValues();
1140
- }
1141
- }
1142
- }
1143
-
1144
- function pushHistory(id, state, timerRelog) {
1145
- if (timerRelog === undefined) {
1146
- timerRelog = false;
1147
- }
1148
-
1149
- // Push into DB
1150
- if (sqlDPs[id]) {
1151
- const settings = sqlDPs[id][adapter.namespace];
1152
-
1153
- if (!settings || !state) {
1154
- return;
1155
- }
1156
-
1157
- if (state && state.val === undefined) {
1158
- return adapter.log.warn(`state value undefined received for ${id} which is not allowed. Ignoring.`);
1159
- }
1160
-
1161
- if (typeof state.val === 'string' && settings.storageType !== 'String') {
1162
- if (isFinite(state.val)) {
1163
- state.val = parseFloat(state.val);
1164
- }
1165
- }
1166
-
1167
- settings.enableDebugLogs && adapter.log.debug(`new value received for ${id} (storageType ${settings.storageType}), new-value=${state.val}, ts=${state.ts}, relog=${timerRelog}`);
1168
-
1169
- let ignoreDebonce = false;
1170
-
1171
- if (!timerRelog) {
1172
- const valueUnstable = !!sqlDPs[id].timeout;
1173
- // When a debounce timer runs and the value is the same as the last one, ignore it
1174
- if (sqlDPs[id].timeout && state.ts !== state.lc) {
1175
- settings.enableDebugLogs && adapter.log.debug(`value not changed debounce ${id}, value=${state.val}, ts=${state.ts}, debounce timer keeps running`);
1176
- return;
1177
- } else if (sqlDPs[id].timeout) { // if value changed, clear timer
1178
- settings.enableDebugLogs && adapter.log.debug(`value changed during debounce time ${id}, value=${state.val}, ts=${state.ts}, debounce timer restarted`);
1179
- clearTimeout(sqlDPs[id].timeout);
1180
- sqlDPs[id].timeout = null;
1181
- }
1182
-
1183
- if (!valueUnstable && settings.blockTime && sqlDPs[id].state && (sqlDPs[id].state.ts + settings.blockTime) > state.ts) {
1184
- settings.enableDebugLogs && adapter.log.debug(`value ignored blockTime ${id}, value=${state.val}, ts=${state.ts}, lastState.ts=${sqlDPs[id].state.ts}, blockTime=${settings.blockTime}`);
1185
- return;
1186
- }
1187
-
1188
- if (settings.ignoreZero && (state.val === undefined || state.val === null || state.val === 0)) {
1189
- settings.enableDebugLogs && adapter.log.debug(`value ignore because zero or null ${id}, new-value=${state.val}, ts=${state.ts}`);
1190
- return;
1191
- } else
1192
- if (typeof settings.ignoreBelowNumber === 'number' && typeof state.val === 'number' && state.val < settings.ignoreBelowNumber) {
1193
- settings.enableDebugLogs && adapter.log.debug(`value ignored because below ${settings.ignoreBelowNumber} for ${id}, new-value=${state.val}, ts=${state.ts}`);
1194
- return;
1195
- }
1196
- if (typeof settings.ignoreAboveNumber === 'number' && typeof state.val === 'number' && state.val > settings.ignoreAboveNumber) {
1197
- settings.enableDebugLogs && adapter.log.debug(`value ignored because above ${settings.ignoreAboveNumber} for ${id}, new-value=${state.val}, ts=${state.ts}`);
1198
- return;
1199
- }
1200
-
1201
- if (sqlDPs[id].state && settings.changesOnly) {
1202
- if (settings.changesRelogInterval === 0) {
1203
- if ((sqlDPs[id].state.val !== null || state.val === null) && state.ts !== state.lc) {
1204
- // remember new timestamp
1205
- if (!valueUnstable && !settings.disableSkippedValueLogging) {
1206
- sqlDPs[id].skipped = state;
1207
- }
1208
- settings.enableDebugLogs && adapter.log.debug(`value not changed ${id}, last-value=${sqlDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
1209
- return;
1210
- }
1211
- } else if (sqlDPs[id].lastLogTime) {
1212
- if ((sqlDPs[id].state.val !== null || state.val === null) && (state.ts !== state.lc) && (Math.abs(sqlDPs[id].lastLogTime - state.ts) < settings.changesRelogInterval * 1000)) {
1213
- // remember new timestamp
1214
- if (!valueUnstable && !settings.disableSkippedValueLogging) {
1215
- sqlDPs[id].skipped = state;
1216
- }
1217
- settings.enableDebugLogs && adapter.log.debug(`value not changed ${id}, last-value=${sqlDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
1218
- return;
1219
- }
1220
- if (state.ts !== state.lc) {
1221
- settings.enableDebugLogs && adapter.log.debug(`value-not-changed-relog ${id}, value=${state.val}, lastLogTime=${sqlDPs[id].lastLogTime}, ts=${state.ts}`);
1222
- ignoreDebonce = true;
1223
- }
1224
- }
1225
- if (typeof state.val === 'number') {
1226
- if (
1227
- sqlDPs[id].state.val !== null &&
1228
- settings.changesMinDelta !== 0 &&
1229
- Math.abs(sqlDPs[id].state.val - state.val) < settings.changesMinDelta
1230
- ) {
1231
- if (!valueUnstable && !settings.disableSkippedValueLogging) {
1232
- sqlDPs[id].skipped = state;
1233
- }
1234
- settings.enableDebugLogs && adapter.log.debug(`Min-Delta not reached ${id}, last-value=${sqlDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
1235
- return;
1236
- } else if (settings.changesMinDelta !== 0) {
1237
- settings.enableDebugLogs && adapter.log.debug(`Min-Delta reached ${id}, last-value=${sqlDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
1238
- }
1239
- } else {
1240
- settings.enableDebugLogs && adapter.log.debug(`Min-Delta ignored because no number ${id}, last-value=${sqlDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
1241
- }
1242
- }
1243
- }
1244
-
1245
- if (settings.counter && sqlDPs[id].state) {
1246
- if (sqlDPs[id].type !== types.number) {
1247
- adapter.log.error('Counter must have type "number"!');
1248
- } else if (state.val < sqlDPs[id].state.val) {
1249
- // if the actual value is less then last seen counter, store both values
1250
- pushValueIntoDB(id, sqlDPs[id].state, true);
1251
- pushValueIntoDB(id, state, true);
1252
- }
1253
- }
1254
-
1255
- if (sqlDPs[id].relogTimeout) {
1256
- clearTimeout(sqlDPs[id].relogTimeout);
1257
- sqlDPs[id].relogTimeout = null;
1258
- }
1259
-
1260
- if (timerRelog) {
1261
- state = Object.assign({}, state);
1262
- state.ts = Date.now();
1263
- state.from = `system.adapter.${adapter.namespace}`;
1264
- settings.enableDebugLogs && adapter.log.debug(`timed-relog ${id}, value=${state.val}, lastLogTime=${sqlDPs[id].lastLogTime}, ts=${state.ts}`);
1265
- ignoreDebonce = true;
1266
- } else {
1267
- if (settings.changesOnly && sqlDPs[id].skipped) {
1268
- settings.enableDebugLogs && adapter.log.debug(`Skipped value logged ${id}, value=${sqlDPs[id].skipped.val}, ts=${sqlDPs[id].skipped.ts}`);
1269
- pushHelper(id, sqlDPs[id].skipped);
1270
- sqlDPs[id].skipped = null;
1271
- }
1272
- if (sqlDPs[id].state && ((sqlDPs[id].state.val === null && state.val !== null) || (sqlDPs[id].state.val !== null && state.val === null))) {
1273
- ignoreDebonce = true;
1274
- } else if (!sqlDPs[id].state && state.val === null) {
1275
- ignoreDebonce = true;
1276
- }
1277
- }
1278
-
1279
- if (settings.debounceTime && !ignoreDebonce && !timerRelog) {
1280
- // Discard changes in the debounce time to store last stable value
1281
- sqlDPs[id].timeout && clearTimeout(sqlDPs[id].timeout);
1282
- sqlDPs[id].timeout = setTimeout((id, state) => {
1283
- if (!sqlDPs[id]) return;
1284
- sqlDPs[id].timeout = null;
1285
- sqlDPs[id].state = state;
1286
- sqlDPs[id].lastLogTime = state.ts;
1287
- settings.enableDebugLogs && adapter.log.debug(`Value logged ${id}, value=${sqlDPs[id].state.val}, ts=${sqlDPs[id].state.ts}`);
1288
- pushHelper(id);
1289
- if (settings.changesOnly && settings.changesRelogInterval > 0) {
1290
- sqlDPs[id].relogTimeout = setTimeout(reLogHelper, settings.changesRelogInterval * 1000, id);
1291
- }
1292
- }, settings.debounceTime, id, state);
1293
- } else {
1294
- if (!timerRelog) {
1295
- sqlDPs[id].state = state;
1296
- }
1297
- sqlDPs[id].lastLogTime = state.ts;
1298
-
1299
- settings.enableDebugLogs && adapter.log.debug(`Value logged ${id}, value=${sqlDPs[id].state.val}, ts=${sqlDPs[id].state.ts}`);
1300
- pushHelper(id, state);
1301
- if (settings.changesOnly && settings.changesRelogInterval > 0) {
1302
- sqlDPs[id].relogTimeout = setTimeout(reLogHelper, settings.changesRelogInterval * 1000, id);
1303
- }
1304
- }
1305
- }
1306
- }
1307
-
1308
- function reLogHelper(_id) {
1309
- if (!sqlDPs[_id]) {
1310
- adapter.log.info(`non-existing id ${_id}`);
1311
- } else {
1312
- sqlDPs[_id].relogTimeout = null;
1313
- if (sqlDPs[_id].skipped) {
1314
- pushHistory(_id, sqlDPs[_id].skipped, true);
1315
- } else if (sqlDPs[_id].state) {
1316
- pushHistory(_id, sqlDPs[_id].state, true);
1317
- } else {
1318
- adapter.getForeignState(sqlDPs[_id].realId, (err, state) => {
1319
- if (err) {
1320
- adapter.log.info(`init timed Relog: can not get State for ${_id} : ${err}`);
1321
- } else if (!state) {
1322
- adapter.log.info(`init timed Relog: disable relog because state not set so far for ${_id}: ${JSON.stringify(state)}`);
1323
- } else {
1324
- adapter.log.debug(`init timed Relog: getState ${_id}: Value=${state.val}, ack=${state.ack}, ts=${state.ts}, lc=${state.lc}`);
1325
- sqlDPs[_id].state = state;
1326
- pushHistory(_id, sqlDPs[_id].state, true);
1327
- }
1328
- });
1329
- }
1330
- }
1331
- }
1332
-
1333
- function pushHelper(_id, state, cb) {
1334
- if (!sqlDPs[_id] || (!sqlDPs[_id].state && !state)) {
1335
- return;
1336
- }
1337
- if (!state) {
1338
- state = sqlDPs[_id].state;
1339
- }
1340
-
1341
- const _settings = sqlDPs[_id] && sqlDPs[_id][adapter.namespace] || {};
1342
-
1343
- if (state.val !== null && (typeof state.val === 'object' || typeof state.val === 'undefined')) {
1344
- state.val = JSON.stringify(state.val);
1345
- }
1346
-
1347
- if (state.val !== null && state.val !== undefined) {
1348
- _settings.enableDebugLogs && adapter.log.debug(`Datatype ${_id}: Currently: ${typeof state.val}, StorageType: ${_settings.storageType}`);
1349
-
1350
- if (typeof state.val === 'string' && _settings.storageType !== 'String') {
1351
- _settings.enableDebugLogs && adapter.log.debug(`Do Automatic Datatype conversion for ${_id}`);
1352
- if (isFinite(state.val)) {
1353
- state.val = parseFloat(state.val);
1354
- } else if (state.val === 'true') {
1355
- state.val = true;
1356
- } else if (state.val === 'false') {
1357
- state.val = false;
1358
- }
1359
- }
1360
-
1361
- if (_settings.storageType === 'String' && typeof state.val !== 'string') {
1362
- state.val = state.val.toString();
1363
- } else if (_settings.storageType === 'Number' && typeof state.val !== 'number') {
1364
- if (typeof state.val === 'boolean') {
1365
- state.val = state.val ? 1 : 0;
1366
- } else {
1367
- return adapter.log.info(`Do not store value "${state.val}" for ${_id} because no number`);
1368
- }
1369
- } else if (_settings.storageType === 'Boolean' && typeof state.val !== 'boolean') {
1370
- state.val = !!state.val;
1371
- }
1372
- } else {
1373
- _settings.enableDebugLogs && adapter.log.debug(`Datatype ${_id}: Currently: null`);
1374
- }
1375
-
1376
- pushValueIntoDB(_id, state, cb);
1377
- }
1378
-
1379
- function getAllIds(cb) {
1380
- const query = SQLFuncs.getIdSelect(adapter.config.dbname);
1381
- adapter.log.debug(query);
1382
-
1383
- borrowClientFromPool((err, client) => {
1384
- if (err) {
1385
- returnClientToPool(client);
1386
- return cb && cb(err);
1387
- }
1388
-
1389
- client.execute(query, (err, rows /* , fields */) => {
1390
- returnClientToPool(client);
1391
- if (rows && rows.rows) rows = rows.rows;
1392
- if (err) {
1393
- adapter.log.error(`Cannot select ${query}: ${err}`);
1394
- return cb && cb(err);
1395
- }
1396
-
1397
- if (rows.length) {
1398
- let id;
1399
- for (let r = 0; r < rows.length; r++) {
1400
- id = rows[r].name;
1401
- sqlDPs[id] = sqlDPs[id] || {};
1402
- sqlDPs[id].index = rows[r].id;
1403
- if (rows[r].type !== null) sqlDPs[id].dbtype = rows[r].type;
1404
- }
1405
- }
1406
- cb && cb();
1407
- });
1408
- });
1409
- }
1410
-
1411
- function getAllFroms(cb) {
1412
- const query = SQLFuncs.getFromSelect(adapter.config.dbname);
1413
- adapter.log.debug(query);
1414
-
1415
- borrowClientFromPool((err, client) => {
1416
- if (err) {
1417
- returnClientToPool(client);
1418
- return cb && cb(err);
1419
- }
1420
-
1421
- client.execute(query, (err, rows /* , fields */) => {
1422
- returnClientToPool(client);
1423
- if (rows && rows.rows) rows = rows.rows;
1424
- if (err) {
1425
- adapter.log.error(`Cannot select ${query}: ${err}`);
1426
- return cb && cb(err);
1427
- }
1428
-
1429
- if (rows.length) {
1430
- for (let r = 0; r < rows.length; r++) {
1431
- from[rows[r].name] = rows[r].id;
1432
- }
1433
- }
1434
-
1435
- cb && cb();
1436
- });
1437
- });
1438
- }
1439
-
1440
- function _checkRetention(query, cb) {
1441
- adapter.log.debug(query);
1442
-
1443
- borrowClientFromPool((err, client) => {
1444
- if (err) {
1445
- returnClientToPool(client);
1446
- adapter.log.error(err);
1447
- cb && cb();
1448
- } else {
1449
- client.execute(query, (err /* , rows, fields */ ) => {
1450
- returnClientToPool(client);
1451
- err && adapter.log.warn(`Retention: Cannot delete ${query}: ${err}`);
1452
- cb && cb();
1453
- });
1454
- }
1455
- });
1456
- }
1457
-
1458
- function checkRetention(id) {
1459
- if (sqlDPs[id] && sqlDPs[id][adapter.namespace] && sqlDPs[id][adapter.namespace].retention) {
1460
- const dt = Date.now();
1461
- // check every 6 hours
1462
- if (!sqlDPs[id].lastCheck || dt - sqlDPs[id].lastCheck >= 21600000/* 6 hours */) {
1463
- sqlDPs[id].lastCheck = dt;
1464
-
1465
- if (!dbNames[sqlDPs[id].type]) {
1466
- adapter.log.error(`No type ${sqlDPs[id].type} found for ${id}. Retention is not possible.`);
1467
- } else {
1468
- const query = SQLFuncs.retention(adapter.config.dbname, sqlDPs[id].index, dbNames[sqlDPs[id].type], sqlDPs[id][adapter.namespace].retention);
1469
-
1470
- if (!multiRequests) {
1471
- if (tasks.length > MAXTASKS) {
1472
- return adapter.log.error(`Cannot queue new requests, because more than ${MAXTASKS}`);
1473
- }
1474
-
1475
- let start = tasks.length === 1;
1476
- tasks.push({operation: 'delete', query});
1477
-
1478
- // delete counters too
1479
- if (sqlDPs[id] && sqlDPs[id].type === 0) { // 0 === number
1480
- const query = SQLFuncs.retention(adapter.config.dbname, sqlDPs[id].index, 'ts_counter', sqlDPs[id][adapter.namespace].retention);
1481
- tasks.push({operation: 'delete', query});
1482
- }
1483
-
1484
- start && processTasks();
1485
- } else {
1486
- _checkRetention(query, () => {
1487
- // delete counters too
1488
- if (sqlDPs[id] && sqlDPs[id].type === 0) { // 0 === number
1489
- const query = SQLFuncs.retention(adapter.config.dbname, sqlDPs[id].index, 'ts_counter', sqlDPs[id][adapter.namespace].retention);
1490
- _checkRetention(query);
1491
- }
1492
- });
1493
- }
1494
- }
1495
- }
1496
- }
1497
- }
1498
-
1499
- function _insertValueIntoDB(query, id, cb) {
1500
- adapter.log.debug(query);
1501
-
1502
- borrowClientFromPool((err, client) => {
1503
- if (err) {
1504
- returnClientToPool(client);
1505
- adapter.log.error(err);
1506
- cb && cb(); // BF asked (2021.12.14): may be return here err?
1507
- } else {
1508
- client.execute(query, (err /* , rows, fields */) => {
1509
- returnClientToPool(client);
1510
- if (err) {
1511
- adapter.log.error(`Cannot insert ${query}: ${err} (id: ${id})`);
1512
- } else {
1513
- checkRetention(id);
1514
- }
1515
- cb && cb(); // BF asked (2021.12.14): may be return here err?
1516
- });
1517
- }
1518
- });
1519
- }
1520
-
1521
- function _executeQuery(query, id, cb) {
1522
- adapter.log.debug(query);
1523
-
1524
- borrowClientFromPool((err, client) => {
1525
- if (err) {
1526
- returnClientToPool(client);
1527
- adapter.log.error(err);
1528
- cb && cb();
1529
- } else {
1530
- client.execute(query, (err /* , rows, fields */) => {
1531
- returnClientToPool(client);
1532
- err && adapter.log.error(`Cannot query ${query}: ${err} (id: ${id})`);
1533
- cb && cb();
1534
- });
1535
- }
1536
- });
1537
- }
1538
-
1539
- function processReadTypes() {
1540
- if (tasksReadType && tasksReadType.length) {
1541
- const task = tasksReadType[0];
1542
-
1543
- if (!sqlDPs[task.id]) {
1544
- adapter.log.warn(`Ignore type lookup for ${task.id} because not enabled anymore`);
1545
- task.cb && task.cb(`Ignore type lookup for ${task.id} because not enabled anymore`);
1546
- task.cb = null;
1547
- return setImmediate(() => {
1548
- tasksReadType.shift();
1549
- processReadTypes();
1550
- });
1551
- }
1552
-
1553
- adapter.log.debug(`Type set in Def for ${task.id}: ${sqlDPs[task.id][adapter.namespace] && sqlDPs[task.id][adapter.namespace].storageType}`);
1554
-
1555
- if (sqlDPs[task.id][adapter.namespace] && sqlDPs[task.id][adapter.namespace].storageType) {
1556
- sqlDPs[task.id].type = types[sqlDPs[task.id][adapter.namespace].storageType.toLowerCase()];
1557
- adapter.log.debug(`Type (from Def) for ${task.id}: ${sqlDPs[task.id].type}`);
1558
- processVerifyTypes(task);
1559
- } else if (sqlDPs[task.id].dbtype !== undefined) {
1560
- sqlDPs[task.id].type = sqlDPs[task.id].dbtype;
1561
- if (sqlDPs[task.id][adapter.namespace]) {
1562
- sqlDPs[task.id][adapter.namespace].storageType = storageTypes[sqlDPs[task.id].type];
1563
- }
1564
- adapter.log.debug(`Type (from DB-Type) for ${task.id}: ${sqlDPs[task.id].type}`);
1565
- processVerifyTypes(task);
1566
- } else {
1567
- adapter.getForeignObject(sqlDPs[task.id].realId, (err, obj) => {
1568
- err && adapter.log.warn(`Error while get Object for Def for ${sqlDPs[task.id].realId}: ${err}`);
1569
-
1570
- if (!sqlDPs[task.id]) {
1571
- adapter.log.warn(`Ignore type lookup for ${task.id} because not enabled anymore`);
1572
- task.cb && task.cb(`Ignore type lookup for ${task.id} because not enabled anymore`)
1573
- task.cb = null;
1574
- return setImmediate(() => {
1575
- tasksReadType.shift();
1576
- processReadTypes();
1577
- });
1578
- } else
1579
- // read type from object
1580
- if (obj && obj.common && obj.common.type && types[obj.common.type.toLowerCase()] !== undefined) {
1581
- adapter.log.debug(`${obj.common.type.toLowerCase()} / ${types[obj.common.type.toLowerCase()]} / ${JSON.stringify(obj.common)}`);
1582
- sqlDPs[task.id].type = types[obj.common.type.toLowerCase()];
1583
- if (sqlDPs[task.id][adapter.namespace]) {
1584
- sqlDPs[task.id][adapter.namespace].storageType = storageTypes[sqlDPs[task.id].type];
1585
- }
1586
- adapter.log.debug(`Type (from Obj) for ${task.id}: ${sqlDPs[task.id].type}`);
1587
- processVerifyTypes(task);
1588
- } else if (sqlDPs[task.id].type === undefined) {
1589
- adapter.getForeignState(sqlDPs[task.id].realId, (err, state) => {
1590
- if (!sqlDPs[task.id]) {
1591
- adapter.log.warn(`Ignore type lookup for ${task.id} because not enabled anymore`);
1592
- task.cb && task.cb(`Ignore type lookup for ${task.id} because not enabled anymore`)
1593
- task.cb = null;
1594
- return setImmediate(() => {
1595
- tasksReadType.shift();
1596
- processReadTypes();
1597
- });
1598
- }
1599
-
1600
- if (err && task.state) {
1601
- adapter.log.warn(`Fallback to type of current state value because no other valid type found`);
1602
- state = task.state;
1603
- }
1604
- if (state && state.val !== null && state.val !== undefined && types[typeof state.val] !== undefined) {
1605
- sqlDPs[task.id].type = types[typeof state.val];
1606
- if (sqlDPs[task.id][adapter.namespace]) {
1607
- sqlDPs[task.id][adapter.namespace].storageType = storageTypes[sqlDPs[task.id].type];
1608
- }
1609
- } else {
1610
- adapter.log.warn(`Store data for ${task.id} as string because no other valid type found (${state ? (typeof state.val) : 'state not existing'})`);
1611
- sqlDPs[task.id].type = 1; // string
1612
- }
1613
-
1614
- adapter.log.debug(`Type (from State) for ${task.id}: ${sqlDPs[task.id].type}`);
1615
- processVerifyTypes(task);
1616
- });
1617
- } else {
1618
- // all OK
1619
- task.cb && task.cb();
1620
- task.cb = null;
1621
- tasksReadType.shift();
1622
- processReadTypes();
1623
- }
1624
- });
1625
- }
1626
- }
1627
- }
1628
-
1629
- function processVerifyTypes(task) {
1630
- if (sqlDPs[task.id].index !== undefined && sqlDPs[task.id].type !== undefined && sqlDPs[task.id].type !== sqlDPs[task.id].dbtype) {
1631
- sqlDPs[task.id].dbtype = sqlDPs[task.id].type;
1632
-
1633
- const query = SQLFuncs.getIdUpdate(adapter.config.dbname, sqlDPs[task.id].index, sqlDPs[task.id].type);
1634
-
1635
- adapter.log.debug(query);
1636
-
1637
- return borrowClientFromPool((err, client) => {
1638
- if (err) {
1639
- returnClientToPool(client);
1640
- return processVerifyTypes(task);
1641
- }
1642
-
1643
- client.execute(query, (err, rows /* , fields */) => {
1644
- returnClientToPool(client);
1645
- if (err) {
1646
- adapter.log.error(`error updating history config for ${task.id} to pin datatype: ${query}: ${err}`);
1647
- } else {
1648
- adapter.log.info(`changed history configuration to pin detected datatype for ${task.id}`);
1649
- }
1650
- processVerifyTypes(task);
1651
- });
1652
- });
1653
- }
1654
-
1655
- task.cb && task.cb();
1656
- task.cb = null;
1657
-
1658
- setTimeout(() => {
1659
- tasksReadType.shift();
1660
- processReadTypes();
1661
- }, 50);
1662
- }
1663
-
1664
- function prepareTaskReadDbId(id, state, isCounter, cb) {
1665
- if (!sqlDPs[id]) {
1666
- return cb && cb(`${id} not active any more`);
1667
- }
1668
- const type = sqlDPs[id].type;
1669
-
1670
- if (type === undefined) { // Can not happen anymore
1671
- let warn;
1672
- if (state.val === null) {
1673
- warn = `Ignore null value for ${id} because no type defined till now.`;
1674
- } else {
1675
- warn = `Cannot store values of type "${typeof state.val}" for ${id}`;
1676
- }
1677
-
1678
- adapter.log.warn(warn);
1679
- return cb && cb(warn);
1680
- }
1681
-
1682
- let tmpState;
1683
- // get sql id of state
1684
- if (sqlDPs[id].index === undefined) {
1685
- sqlDPs[id].isRunning = sqlDPs[id].isRunning || [];
1686
-
1687
- tmpState = Object.assign({}, state);
1688
-
1689
- sqlDPs[id].isRunning.push({id, state: tmpState, cb, isCounter});
1690
-
1691
- if (sqlDPs[id].isRunning.length === 1) {
1692
- // read or create in DB
1693
- return getId(id, type, (err, _id) => {
1694
- adapter.log.debug(`prepareTaskCheckTypeAndDbId getId Result - isRunning length = ${sqlDPs[_id].isRunning ? sqlDPs[_id].isRunning.length : 'none'}`);
1695
- if (err) {
1696
- adapter.log.warn(`Cannot get index of "${_id}": ${err}`);
1697
- sqlDPs[_id].isRunning &&
1698
- sqlDPs[_id].isRunning.forEach(r => r.cb && r.cb(`Cannot get index of "${r.id}": ${err}`));
1699
- } else {
1700
- sqlDPs[_id].isRunning &&
1701
- sqlDPs[_id].isRunning.forEach(r => r.cb && r.cb());
1702
- }
1703
-
1704
- sqlDPs[_id].isRunning = null;
1705
- });
1706
- } else {
1707
- return;
1708
- }
1709
- }
1710
-
1711
- // get from
1712
- if (!isCounter && state.from && !from[state.from]) {
1713
- isFromRunning[state.from] = isFromRunning[state.from] || [];
1714
- tmpState = Object.assign({}, state);
1715
-
1716
- isFromRunning[state.from].push({id, state: tmpState, cb});
1717
-
1718
- if (isFromRunning[state.from].length === 1) {
1719
- // read or create in DB
1720
- return getFrom(state.from, (err, from) => {
1721
- adapter.log.debug(`prepareTaskCheckTypeAndDbId getFrom ${from} Result - isRunning length = ${isFromRunning[from] ? isFromRunning[from].length : 'none'}`)
1722
- if (err) {
1723
- adapter.log.warn(`Cannot get "from" for "${from}": ${err}`);
1724
- isFromRunning[from] &&
1725
- isFromRunning[from].forEach(f => f.cb && f.cb(`Cannot get "from" for "${from}": ${err}`));
1726
- } else {
1727
- isFromRunning[from] &&
1728
- isFromRunning[from].forEach(f => f.cb && f.cb());
1729
- }
1730
- isFromRunning[from] = null;
1731
- });
1732
- } else {
1733
- return;
1734
- }
1735
- }
1736
-
1737
- state.ts = parseInt(state.ts, 10);
1738
-
1739
- try {
1740
- if (state.val !== null && (typeof state.val === 'object' || typeof state.val === 'undefined')) {
1741
- state.val = JSON.stringify(state.val);
1742
- }
1743
- } catch (err) {
1744
- const error = `Cannot convert the object value "${id}"`;
1745
- adapter.log.error(error);
1746
- return cb && cb(error);
1747
- }
1748
-
1749
- cb && cb();
1750
- }
1751
-
1752
- function prepareTaskCheckTypeAndDbId(id, state, isCounter, cb) {
1753
- // check if we know about this ID
1754
- if (!sqlDPs[id]) {
1755
- return cb && setImmediate(cb, `Unknown ID: ${id}`);
1756
- }
1757
-
1758
- // Check sql connection
1759
- if (!clientPool) {
1760
- adapter.log.warn('No Connection to database');
1761
- return cb && setImmediate(cb, 'No Connection to database');
1762
- }
1763
- adapter.log.debug(`prepareTaskCheckTypeAndDbId CALLED for ${id}`);
1764
-
1765
- // read type of value
1766
- if (sqlDPs[id].type !== undefined) {
1767
- prepareTaskReadDbId(id, state, isCounter, cb)
1768
- } else {
1769
- // read type from DB
1770
- tasksReadType.push({id, state, cb: err => {
1771
- if (err) {
1772
- return cb && cb(err);
1773
- }
1774
- prepareTaskReadDbId(id, state, isCounter, cb);
1775
- }});
1776
-
1777
- tasksReadType.length === 1 && processReadTypes();
1778
- }
1779
- }
1780
-
1781
- function pushValueIntoDB(id, state, isCounter, storeInCacheOnly, cb) {
1782
- if (typeof storeInCacheOnly === 'function') {
1783
- cb = storeInCacheOnly;
1784
- storeInCacheOnly = false;
1785
- }
1786
-
1787
- if (typeof isCounter === 'function') {
1788
- cb = isCounter;
1789
- isCounter = false;
1790
- }
1791
-
1792
- if (!sqlDPs[id] || !state) {
1793
- return cb && cb()
1794
- }
1795
-
1796
- adapter.log.debug(`pushValueIntoDB called for ${id} (type: ${sqlDPs[id].type}, ID: ${sqlDPs[id].index}) and state: ${JSON.stringify(state)}`);
1797
-
1798
- prepareTaskCheckTypeAndDbId(id, state, isCounter, err => {
1799
- if (!sqlDPs[id]) {
1800
- return cb && cb()
1801
- }
1802
- adapter.log.debug(`pushValueIntoDB-prepareTaskCheckTypeAndDbId RESULT for ${id} (type: ${sqlDPs[id].type}, ID: ${sqlDPs[id].index}) and state: ${JSON.stringify(state)}: ${err}`);
1803
- if (err) {
1804
- return cb && cb(err);
1805
- }
1806
-
1807
- const type = sqlDPs[id].type;
1808
-
1809
- // increase timestamp if last is the same
1810
- if (!isCounter && sqlDPs[id].ts && state.ts === sqlDPs[id].ts) {
1811
- state.ts++;
1812
- }
1813
-
1814
- // remember last timestamp
1815
- sqlDPs[id].ts = state.ts;
1816
-
1817
- // if it was not deleted in this time
1818
- sqlDPs[id].list = sqlDPs[id].list || [];
1819
-
1820
- sqlDPs[id].list.push({state, from: from[state.from] || 0, db: isCounter ? 'ts_counter' : dbNames[type]});
1821
-
1822
- const _settings = sqlDPs[id][adapter.namespace] || {};
1823
- const maxLength = _settings.maxLength !== undefined ? _settings.maxLength : parseInt(adapter.config.maxLength, 10) || 0;
1824
- if ((cb || _settings && sqlDPs[id].list.length > maxLength) && !storeInCacheOnly) {
1825
- storeCached(id, cb);
1826
- } else if (cb && storeInCacheOnly) {
1827
- setImmediate(cb);
1828
- }
1829
- });
1830
- }
1831
-
1832
- function storeCached(onlyId, cb) {
1833
- let count = 0;
1834
- for (const id in sqlDPs) {
1835
- if (!sqlDPs.hasOwnProperty(id) || (onlyId !== undefined && onlyId !== id)) {
1836
- continue;
1837
- }
1838
-
1839
- const _settings = sqlDPs[id][adapter.namespace] || {};
1840
- if (_settings && sqlDPs[id].list && sqlDPs[id].list.length) {
1841
- _settings.enableDebugLogs && adapter.log.debug(`inserting ${sqlDPs[id].list.length} entries from ${id} to DB`);
1842
- const inFlightId = `${id}_${Date.now()}_${Math.random()}`;
1843
- sqlDPs[id].inFlight = sqlDPs[id].inFlight || {};
1844
- sqlDPs[id].inFlight[inFlightId] = sqlDPs[id].list;
1845
- sqlDPs[id].list = [];
1846
- count++;
1847
- pushValuesIntoDB(id, sqlDPs[id].inFlight[inFlightId], err => {
1848
- sqlDPs[id] && sqlDPs[id].inFlight && sqlDPs[id].inFlight[inFlightId] && delete sqlDPs[id].inFlight[inFlightId];
1849
- if (!--count && cb) {
1850
- cb(err);
1851
- cb = null;
1852
- }
1853
- });
1854
- if (onlyId !== undefined) {
1855
- break;
1856
- }
1857
- }
1858
- }
1859
- if (!count && cb) {
1860
- cb();
1861
- }
1862
- }
1863
-
1864
- function pushValuesIntoDB(id, list, cb) {
1865
- if (!list.length) {
1866
- return cb && setImmediate(cb);
1867
- }
1868
-
1869
- if (!multiRequests) {
1870
- if (tasks.length > MAXTASKS) {
1871
- const error = `Cannot queue new requests, because more than ${MAXTASKS}`;
1872
- adapter.log.error(error);
1873
- cb && cb(error);
1874
- } else {
1875
- tasks.push({operation: 'insert', index: sqlDPs[id].index, list, id, callback: cb});
1876
- tasks.length === 1 && processTasks();
1877
- }
1878
- } else {
1879
- const query = SQLFuncs.insert(adapter.config.dbname, sqlDPs[id].index, list);
1880
- _insertValueIntoDB(query, id, cb);
1881
- }
1882
-
1883
- }
1884
-
1885
- let lockTasks = false;
1886
- function processTasks() {
1887
- if (lockTasks) {
1888
- return adapter.log.debug('Tries to execute task, but last one not finished!');
1889
- }
1890
-
1891
- lockTasks = true;
1892
-
1893
- if (tasks.length) {
1894
- if (tasks[0].operation === 'query') {
1895
- _executeQuery(tasks[0].query, tasks[0].id, () => {
1896
- tasks[0].callback && tasks[0].callback();
1897
- tasks.shift();
1898
- lockTasks = false;
1899
- tasks.length && setTimeout(processTasks, adapter.config.requestInterval);
1900
- });
1901
- } else if (tasks[0].operation === 'insert') {
1902
- const callbacks = [];
1903
- if (tasks[0].callback) {
1904
- callbacks.push(tasks[0].callback);
1905
- }
1906
- for (let i = 1; i < tasks.length; i++) {
1907
- if (tasks[i].operation === 'insert' && tasks[0].index === tasks[i].index) {
1908
- tasks[0].list = tasks[0].list.concat(tasks[i].list);
1909
- if (tasks[i].callback) {
1910
- callbacks.push(tasks[i].callback);
1911
- }
1912
- tasks.splice(i, 1);
1913
- i--;
1914
- }
1915
- }
1916
- const query = SQLFuncs.insert(adapter.config.dbname, tasks[0].index, tasks[0].list);
1917
- _insertValueIntoDB(query, tasks[0].id, () => {
1918
- callbacks.forEach(cb => cb());
1919
- tasks.shift();
1920
- lockTasks = false;
1921
- tasks.length && setTimeout(processTasks, adapter.config.requestInterval);
1922
- });
1923
- } else if (tasks[0].operation === 'select') {
1924
- _getDataFromDB(tasks[0].query, tasks[0].options, (err, rows) => {
1925
- tasks[0].callback && tasks[0].callback(err, rows);
1926
- tasks.shift();
1927
- lockTasks = false;
1928
- tasks.length && setTimeout(processTasks, adapter.config.requestInterval);
1929
- });
1930
- } else if (tasks[0].operation === 'userQuery') {
1931
- _userQuery(tasks[0].msg, () => {
1932
- tasks[0].callback && tasks[0].callback();
1933
- tasks.shift();
1934
- lockTasks = false;
1935
- tasks.length && setTimeout(processTasks, adapter.config.requestInterval);
1936
- });
1937
- } else if (tasks[0].operation === 'delete') {
1938
- _checkRetention(tasks[0].query, () => {
1939
- tasks[0].callback && tasks[0].callback();
1940
- tasks.shift();
1941
- lockTasks = false;
1942
- tasks.length && setTimeout(processTasks, adapter.config.requestInterval);
1943
- });
1944
- } else {
1945
- adapter.log.error(`unknown task: ${tasks[0].operation}`);
1946
- tasks[0].callback && tasks[0].callback();
1947
- tasks.shift();
1948
- lockTasks = false;
1949
- tasks.length && setTimeout(processTasks, adapter.config.requestInterval);
1950
- }
1951
- }
1952
- }
1953
-
1954
- // may be it is required to cache all the data in memory
1955
- function getId(id, type, cb) {
1956
- let query = SQLFuncs.getIdSelect(adapter.config.dbname, id);
1957
- adapter.log.debug(query);
1958
-
1959
- borrowClientFromPool((err, client) => {
1960
- if (err) {
1961
- returnClientToPool(client);
1962
- return cb && cb(err, id);
1963
- }
1964
-
1965
- client.execute(query, (err, rows /* , fields */) => {
1966
- if (!sqlDPs[id]) {
1967
- returnClientToPool(client);
1968
- return cb && cb(new Error(`ID ${id} no longer active`), id);
1969
- }
1970
- if (rows && rows.rows) {
1971
- rows = rows.rows;
1972
- }
1973
-
1974
- if (err) {
1975
- returnClientToPool(client);
1976
- adapter.log.error(`Cannot select ${query}: ${err}`);
1977
- return cb && cb(err, id);
1978
- } else if (!rows.length) {
1979
- if (type !== null && type !== undefined) {
1980
- // insert
1981
- query = SQLFuncs.getIdInsert(adapter.config.dbname, id, type);
1982
-
1983
- adapter.log.debug(query);
1984
-
1985
- client.execute(query, (err /* , rows, fields */) => {
1986
- if (err) {
1987
- returnClientToPool(client);
1988
- adapter.log.error(`Cannot insert ${query}: ${err}`);
1989
- cb && cb(err, id);
1990
- } else {
1991
- query = SQLFuncs.getIdSelect(adapter.config.dbname,id);
1992
-
1993
- adapter.log.debug(query);
1994
-
1995
- client.execute(query, (err, rows /* , fields */) => {
1996
- returnClientToPool(client);
1997
- if (rows && rows.rows) {
1998
- rows = rows.rows;
1999
- }
2000
-
2001
- if (err) {
2002
- adapter.log.error(`Cannot select ${query}: ${err}`);
2003
- cb && cb(err, id);
2004
- } else if (rows[0]) {
2005
- sqlDPs[id].index = rows[0].id;
2006
- sqlDPs[id].type = rows[0].type;
2007
-
2008
- cb && cb(null, id);
2009
- } else {
2010
- adapter.log.error(`No result for select ${query}: after insert`);
2011
- cb && cb(new Error(`No result for select ${query}: after insert`), id);
2012
- }
2013
- });
2014
- }
2015
- });
2016
- } else {
2017
- returnClientToPool(client);
2018
- cb && cb('id not found', id);
2019
- }
2020
- } else {
2021
- sqlDPs[id].index = rows[0].id;
2022
- if (rows[0].type === null || typeof rows[0].type !== 'number') {
2023
- sqlDPs[id].type = type;
2024
-
2025
- const query = SQLFuncs.getIdUpdate(adapter.config.dbname, sqlDPs[id].index, sqlDPs[id].type);
2026
-
2027
- adapter.log.debug(query);
2028
-
2029
- client.execute(query, (err, rows /* , fields */) => {
2030
- returnClientToPool(client);
2031
- if (err) {
2032
- adapter.log.error(`error updating history config for ${id} to pin datatype: ${query}: ${err}`);
2033
- } else {
2034
- adapter.log.info(`changed history configuration to pin detected datatype for ${id}`);
2035
- }
2036
- cb && cb(null, id);
2037
- });
2038
- } else {
2039
- returnClientToPool(client);
2040
-
2041
- sqlDPs[id].type = rows[0].type;
2042
-
2043
- cb && cb(null, id);
2044
- }
2045
- }
2046
- });
2047
- });
2048
- }
2049
-
2050
- // my be it is required to cache all the data in memory
2051
- function getFrom(_from, cb) {
2052
- // const sources = (adapter.config.dbtype !== 'postgresql' ? (adapter.config.dbname + '.') : '') + 'sources';
2053
- let query = SQLFuncs.getFromSelect(adapter.config.dbname, _from);
2054
- adapter.log.debug(query);
2055
-
2056
- borrowClientFromPool((err, client) => {
2057
- if (err) {
2058
- returnClientToPool(client);
2059
- return cb && cb(err, _from);
2060
- }
2061
- client.execute(query, (err, rows /* , fields */) => {
2062
- if (rows && rows.rows) rows = rows.rows;
2063
- if (err) {
2064
- returnClientToPool(client);
2065
- adapter.log.error(`Cannot select ${query}: ${err}`);
2066
- return cb && cb(err, _from);
2067
- }
2068
- if (!rows.length) {
2069
- // insert
2070
- query = SQLFuncs.getFromInsert(adapter.config.dbname, _from);
2071
- adapter.log.debug(query);
2072
- client.execute(query, (err /* , rows, fields */) => {
2073
- if (err) {
2074
- returnClientToPool(client);
2075
- adapter.log.error(`Cannot insert ${query}: ${err}`);
2076
- return cb && cb(err, _from);
2077
- }
2078
-
2079
- query = SQLFuncs.getFromSelect(adapter.config.dbname, _from);
2080
- adapter.log.debug(query);
2081
- client.execute(query, (err, rows /* , fields */) => {
2082
- returnClientToPool(client);
2083
-
2084
- if (rows && rows.rows) rows = rows.rows;
2085
- if (err) {
2086
- adapter.log.error(`Cannot select ${query}: ${err}`);
2087
- return cb && cb(err, _from);
2088
- }
2089
- from[_from] = rows[0].id;
2090
-
2091
- cb && cb(null, _from);
2092
- });
2093
- });
2094
- } else {
2095
- returnClientToPool(client);
2096
-
2097
- from[_from] = rows[0].id;
2098
-
2099
- cb && cb(null, _from);
2100
- }
2101
- });
2102
- });
2103
- }
2104
-
2105
- function sortByTs(a, b) {
2106
- const aTs = a.ts;
2107
- const bTs = b.ts;
2108
- return aTs < bTs ? -1 : (aTs > bTs ? 1 : 0);
2109
- }
2110
-
2111
-
2112
- function getOneCachedData(id, options, cache, addId) {
2113
- addId = addId || options.addId;
2114
-
2115
- if (sqlDPs[id]) {
2116
- let res = [];
2117
- for (let inFlightId in sqlDPs[id].inFlight) {
2118
- adapter.log.debug(`getOneCachedData: add ${sqlDPs[id].inFlight[inFlightId].length} inFlight datapoints for ${options.index || options.id}`);
2119
- res = res.concat(sqlDPs[id].inFlight[inFlightId]);
2120
- }
2121
- res = res.concat(sqlDPs[id].list);
2122
- // todo can be optimized
2123
- if (res) {
2124
- let iProblemCount = 0;
2125
- let vLast = null;
2126
- for (let i = res.length - 1; i >= 0 ; i--) {
2127
- if (!res[i] || !res[i].state) {
2128
- iProblemCount++;
2129
- continue;
2130
- }
2131
- if (options.start && res[i].state.ts < options.start) {
2132
- // add one before start
2133
- cache.unshift(Object.assign({}, res[i].state));
2134
- break;
2135
- } else if (res[i].state.ts > options.end) {
2136
- // add one after end
2137
- vLast = res[i].state;
2138
- continue;
2139
- }
2140
-
2141
- if (vLast) {
2142
- cache.unshift(Object.assign({}, vLast));
2143
- vLast = null;
2144
- }
2145
-
2146
- cache.unshift(Object.assign({}, res[i].state));
2147
-
2148
- if ((options.returnNewestEntries && options.count && cache.length >= options.count) && (options.aggregate === 'onchange' || options.aggregate === '' || options.aggregate === 'none')) {
2149
- break;
2150
- }
2151
- }
2152
-
2153
- iProblemCount && adapter.log.warn(`getOneCachedData: got null states ${iProblemCount} times for ${options.index || options.id}`);
2154
-
2155
- adapter.log.debug(`getOneCachedData: got ${res.length} datapoints for ${options.index || options.id}`);
2156
- } else {
2157
- adapter.log.debug(`getOneCachedData: datapoints for ${options.index || options.id} do not yet exist`);
2158
- }
2159
- }
2160
- }
2161
-
2162
- function getCachedData(options, callback) {
2163
- const cache = [];
2164
-
2165
- if (options.index || options.id) {
2166
- getOneCachedData(options.index || options.id, options, cache);
2167
- } else {
2168
- for (const id in sqlDPs) {
2169
- if (sqlDPs.hasOwnProperty(id)) {
2170
- getOneCachedData(id, options, cache, true);
2171
- }
2172
- }
2173
- }
2174
-
2175
- let earliestTs = null;
2176
- for (let c = 0; c < cache.length; c++) {
2177
- if (typeof cache[c].ts === 'string') {
2178
- cache[c].ts = parseInt(cache[c].ts, 10);
2179
- }
2180
-
2181
- if (adapter.common.loglevel === 'debug') {
2182
- cache[c].date = new Date(parseInt(cache[c].ts, 10));
2183
- }
2184
- if (options.ack) {
2185
- cache[c].ack = !!cache[c].ack;
2186
- }
2187
- if (typeof cache[c].val === 'number' && isFinite(cache[c].val) && options.round) {
2188
- cache[c].val = Math.round(cache[c].val * options.round) / options.round;
2189
- }
2190
- if (sqlDPs[options.index || options.id] && sqlDPs[options.index || options.id].type === 2) { // 2 === boolean
2191
- cache[c].val = !!cache[c].val;
2192
- }
2193
- if (options.addId && !cache[c].id && options.id) {
2194
- cache[c].id = options.index || options.id;
2195
- }
2196
- if (cache[c].ts < earliestTs || earliestTs === null) {
2197
- earliestTs = cache[c].ts;
2198
- }
2199
- }
2200
-
2201
- options.length = cache.length;
2202
- callback(cache, options.returnNewestEntries && options.count && cache.length >= options.count, !!(sqlDPs[options.index || options.id] && sqlDPs[options.index || options.id].inFlight && Object.keys(sqlDPs[options.index || options.id].inFlight).length), earliestTs);
2203
- }
2204
-
2205
-
2206
- function _getDataFromDB(query, options, callback) {
2207
- adapter.log.debug(query);
2208
-
2209
- borrowClientFromPool((err, client) => {
2210
- if (err) {
2211
- returnClientToPool(client);
2212
- return callback && callback(err);
2213
- }
2214
- client.execute(query, (err, rows /* , fields */) => {
2215
- returnClientToPool(client);
2216
-
2217
- if (!err && rows && rows.rows) rows = rows.rows;
2218
-
2219
- if (!err && rows) {
2220
- for (let c = 0; c < rows.length; c++) {
2221
- if (typeof rows[c].ts === 'string') {
2222
- rows[c].ts = parseInt(rows[c].ts, 10);
2223
- }
2224
-
2225
- if (adapter.common.loglevel === 'debug') {
2226
- rows[c].date = new Date(parseInt(rows[c].ts, 10));
2227
- }
2228
- if (options.ack) {
2229
- rows[c].ack = !!rows[c].ack;
2230
- }
2231
- if (typeof rows[c].val === 'number' && isFinite(rows[c].val) && options.round) {
2232
- rows[c].val = Math.round(rows[c].val * options.round) / options.round;
2233
- }
2234
- if (sqlDPs[options.index || options.id] && sqlDPs[options.index || options.id].type === 2) { // 2 === boolean
2235
- rows[c].val = !!rows[c].val;
2236
- }
2237
- if (options.addId && !rows[c].id && options.id) {
2238
- rows[c].id = options.index || options.id;
2239
- }
2240
- }
2241
- }
2242
- callback && callback(err, rows);
2243
- });
2244
- });
2245
- }
2246
-
2247
- function getDataFromDB(db, options, callback) {
2248
- const query = SQLFuncs.getHistory(adapter.config.dbname, db, options);
2249
- adapter.log.debug(query);
2250
- if (!multiRequests) {
2251
- if (tasks.length > MAXTASKS) {
2252
- adapter.log.error(`Cannot queue new requests, because more than ${MAXTASKS}`);
2253
- callback && callback(`Cannot queue new requests, because more than ${MAXTASKS}`);
2254
- } else {
2255
- tasks.push({operation: 'select', query, options, callback});
2256
- tasks.length === 1 && processTasks();
2257
- }
2258
- } else {
2259
- _getDataFromDB(query, options, callback);
2260
- }
2261
- }
2262
-
2263
- function getCounterDataFromDB(options, callback) {
2264
- const query = SQLFuncs.getCounterDiff(adapter.config.dbname, options);
2265
-
2266
- adapter.log.debug(query);
2267
-
2268
- if (!multiRequests) {
2269
- if (tasks.length > MAXTASKS) {
2270
- const error = `Cannot queue new requests, because more than ${MAXTASKS}`;
2271
- adapter.log.error(error);
2272
- callback && callback(error);
2273
- } else {
2274
- tasks.push({operation: 'select', query, options, callback});
2275
- tasks.length === 1 && processTasks();
2276
- }
2277
- } else {
2278
- _getDataFromDB(query, options, callback);
2279
- }
2280
- }
2281
-
2282
- function getCounterDiff(msg) {
2283
- const startTime = Date.now();
2284
- const id = msg.message.id;
2285
- const start = msg.message.options.start || 0;
2286
- const end = msg.message.options.end || (Date.now() + 5000000);
2287
-
2288
-
2289
- if (!sqlDPs[id]) {
2290
- adapter.sendTo(msg.from, msg.command, {result: [], step: null, error: 'Not enabled'}, msg.callback);
2291
- } else {
2292
- if (!SQLFuncs.getCounterDiff) {
2293
- adapter.sendTo(msg.from, msg.command, {result: [], step: null, error: 'Counter option is not enabled for this type of SQL'}, msg.callback);
2294
- } else {
2295
- const options = {id: sqlDPs[id].index, start, end, index: id};
2296
- getCounterDataFromDB(options, (err, data) =>
2297
- commons.sendResponseCounter(adapter, msg, options, (err ? err.toString() : null) || data, startTime));
2298
- }
2299
- }
2300
- }
2301
-
2302
- function getHistory(msg) {
2303
- const startTime = Date.now();
2304
-
2305
- if (!msg.message || !msg.message.options) {
2306
- return adapter.sendTo(msg.from, msg.command, {
2307
- error: 'Invalid call. No options for getHistory provided'
2308
- }, msg.callback);
2309
- }
2310
-
2311
- const options = {
2312
- id: msg.message.id === '*' ? null : msg.message.id,
2313
- start: msg.message.options.start,
2314
- end: msg.message.options.end || (Date.now() + 5000000),
2315
- step: parseInt(msg.message.options.step, 10) || null,
2316
- count: parseInt(msg.message.options.count, 10),
2317
- ignoreNull: msg.message.options.ignoreNull,
2318
- aggregate: msg.message.options.aggregate || 'average', // One of: max, min, average, total, none, on-change
2319
- limit: parseInt(msg.message.options.limit, 10) || parseInt(msg.message.options.count, 10) || adapter.config.limit || 2000,
2320
- from: msg.message.options.from || false,
2321
- q: msg.message.options.q || false,
2322
- ack: msg.message.options.ack || false,
2323
- ms: msg.message.options.ms || false,
2324
- addId: msg.message.options.addId || false,
2325
- sessionId: msg.message.options.sessionId,
2326
- returnNewestEntries: msg.message.options.returnNewestEntries || false,
2327
- percentile: msg.message.options.aggregate === 'percentile' ? parseInt(msg.message.options.percentile, 10) || 50 : null,
2328
- quantile: msg.message.options.aggregate === 'quantile' ? parseFloat(msg.message.options.quantile) || 0.5 : null,
2329
- integralUnit: msg.message.options.aggregate === 'integral' ? parseInt(msg.message.options.integralUnit, 10) || 60 : null,
2330
- integralInterpolation: msg.message.options.aggregate === 'integral' ? msg.message.options.integralInterpolation || 'none' : null,
2331
- removeBorderValues: msg.message.options.removeBorderValues || false,
2332
- logId: (msg.message.id ? msg.message.id : 'all') + Date.now() + Math.random()
2333
- };
2334
-
2335
- adapter.log.debug(`${options.logId} getHistory message: ${JSON.stringify(msg.message)}`);
2336
-
2337
- if (!options.count || isNaN(options.count)) {
2338
- if (options.aggregate === 'none' || options.aggregate === 'onchange') {
2339
- options.count = options.limit;
2340
- } else {
2341
- options.count = 500;
2342
- }
2343
- }
2344
-
2345
- try {
2346
- if (options.start && typeof options.start !== 'number') {
2347
- options.start = new Date(options.start).getTime();
2348
- }
2349
- } catch (err) {
2350
- return adapter.sendTo(msg.from, msg.command, {
2351
- error: `Invalid call. Start date ${JSON.stringify(options.start)} is not a valid date`
2352
- }, msg.callback);
2353
- }
2354
-
2355
- try {
2356
- if (options.end && typeof options.end !== 'number') {
2357
- options.end = new Date(options.end).getTime();
2358
- }
2359
- } catch (err) {
2360
- return adapter.sendTo(msg.from, msg.command, {
2361
- error: `Invalid call. End date ${JSON.stringify(options.end)} is not a valid date`
2362
- }, msg.callback);
2363
- }
2364
-
2365
- if (!options.start && options.count) {
2366
- options.returnNewestEntries = true;
2367
- }
2368
-
2369
- if (msg.message.options.round !== null && msg.message.options.round !== undefined && msg.message.options.round !== '') {
2370
- msg.message.options.round = parseInt(msg.message.options.round, 10);
2371
- if (!isFinite(msg.message.options.round) || msg.message.options.round < 0) {
2372
- options.round = adapter.config.round;
2373
- } else {
2374
- options.round = Math.pow(10, parseInt(msg.message.options.round, 10));
2375
- }
2376
- } else {
2377
- options.round = adapter.config.round;
2378
- }
2379
-
2380
- if (options.id && aliasMap[options.id]) {
2381
- options.id = aliasMap[options.id];
2382
- }
2383
-
2384
- if (options.aggregate === 'percentile' && options.percentile < 0 || options.percentile > 100) {
2385
- adapter.log.error(`Invalid percentile value: ${options.percentile}, use 50 as default`);
2386
- options.percentile = 50;
2387
- }
2388
-
2389
- if (options.aggregate === 'quantile' && options.quantile < 0 || options.quantile > 1) {
2390
- adapter.log.error(`Invalid quantile value: ${options.quantile}, use 0.5 as default`);
2391
- options.quantile = 0.5;
2392
- }
2393
-
2394
- if (options.aggregate === 'integral' && (typeof options.integralUnit !== 'number' || options.integralUnit <= 0)) {
2395
- adapter.log.error(`Invalid integralUnit value: ${options.integralUnit}, use 60s as default`);
2396
- options.integralUnit = 60;
2397
- }
2398
-
2399
- sqlDPs[options.id] = sqlDPs[options.id] || {};
2400
- const debugLog = options.debugLog = !!((sqlDPs[options.id] && sqlDPs[options.id][adapter.namespace] && sqlDPs[options.id][adapter.namespace].enableDebugLogs) || adapter.config.enableDebugLogs);
2401
-
2402
- if (options.ignoreNull === 'true') options.ignoreNull = true; // include nulls and replace them with last value
2403
- if (options.ignoreNull === 'false') options.ignoreNull = false; // include nulls
2404
- if (options.ignoreNull === '0') options.ignoreNull = 0; // include nulls and replace them with 0
2405
- if (options.ignoreNull !== true && options.ignoreNull !== false && options.ignoreNull !== 0) {
2406
- options.ignoreNull = false;
2407
- }
2408
-
2409
- if (options.start > options.end) {
2410
- const _end = options.end;
2411
- options.end = options.start;
2412
- options.start =_end;
2413
- }
2414
-
2415
- if (!options.start && !options.count) {
2416
- options.start = Date.now() - 86400000; // - 1 day
2417
- }
2418
-
2419
- debugLog && adapter.log.debug(`${options.logId} getHistory options final: ${JSON.stringify(options)}`);
2420
-
2421
- if (sqlDPs[options.id].type === undefined && sqlDPs[options.id].dbtype !== undefined) {
2422
- if (sqlDPs[options.id][adapter.namespace] && sqlDPs[options.id][adapter.namespace].storageType) {
2423
- if (storageTypes.indexOf(sqlDPs[options.id][adapter.namespace].storageType) === sqlDPs[options.id].dbtype) {
2424
- debugLog && adapter.log.debug(`${options.logId} For getHistory for id ${options.id}: Type empty, use storageType dbtype ${sqlDPs[options.id].dbtype}`);
2425
- sqlDPs[options.id].type = sqlDPs[options.id].dbtype;
2426
- }
2427
- }
2428
- else {
2429
- debugLog && adapter.log.debug(`${options.logId} For getHistory for id ${options.id}: Type empty, use dbtype ${sqlDPs[options.id].dbtype}`);
2430
- sqlDPs[options.id].type = sqlDPs[options.id].dbtype;
2431
- }
2432
- }
2433
- if (options.id && sqlDPs[options.id].index === undefined) {
2434
- // read or create in DB
2435
- return getId(options.id, null, err => {
2436
- if (err) {
2437
- adapter.log.warn(`Cannot get index of "${options.id}": ${err}`);
2438
- commons.sendResponse(adapter, msg, options, [], startTime);
2439
- } else {
2440
- getHistory(msg);
2441
- }
2442
- });
2443
- }
2444
- if (options.id && sqlDPs[options.id].type === undefined) {
2445
- adapter.log.warn(`For getHistory for id "${options.id}": Type empty. Need to write data first. Index = ${sqlDPs[options.id].index}`);
2446
- commons.sendResponse(adapter, msg, options, 'Please wait till next data record is logged and reload.', startTime);
2447
- return;
2448
- }
2449
-
2450
- const type = sqlDPs[options.id].type;
2451
- if (options.id) {
2452
- options.index = options.id;
2453
- options.id = sqlDPs[options.id].index;
2454
- }
2455
-
2456
- if (options.debugLog) {
2457
- options.log = adapter.log.debug;
2458
- }
2459
-
2460
- // if specific id requested
2461
- if (options.id) {
2462
- getCachedData(options, (cacheData, isFull, includesInFlightData, earliestTs) => {
2463
- debugLog && adapter.log.debug(`${options.logId} after getCachedData: length = ${cacheData.length}, isFull=${isFull}`);
2464
-
2465
- // if all data read
2466
- if ((isFull && cacheData.length) && (options.aggregate === 'onchange' || options.aggregate === '' || options.aggregate === 'none')) {
2467
- cacheData = cacheData.sort(sortByTs);
2468
- if (options.count && cacheData.length > options.count && options.aggregate === 'none') {
2469
- cacheData.splice(0, cacheData.length - options.count);
2470
- debugLog && adapter.log.debug(`${options.logId} cut cacheData to ${options.count} values`);
2471
- }
2472
- adapter.log.debug(`${options.logId} Send: ${cacheData.length} values in: ${Date.now() - startTime}ms`);
2473
-
2474
- adapter.sendTo(msg.from, msg.command, {
2475
- result: cacheData,
2476
- step: null,
2477
- error: null
2478
- }, msg.callback);
2479
- } else {
2480
- const origEnd = options.end;
2481
- if (includesInFlightData) {
2482
- options.end = earliestTs;
2483
- }
2484
- // if not all data read
2485
- getDataFromDB(dbNames[type], options, (err, data) => {
2486
- if (!err && data) {
2487
- options.end = origEnd;
2488
- if (options.aggregate === 'none' && options.count && options.returnNewestEntries) {
2489
- cacheData = cacheData.reverse()
2490
- data = cacheData.concat(data);
2491
- } else {
2492
- data = data.concat(cacheData);
2493
- }
2494
- debugLog && adapter.log.debug(`${options.logId} after getDataFromDB: length = ${data.length}`);
2495
- if (options.count && data.length > options.count && options.aggregate === 'none' && !options.returnNewestEntries) {
2496
- if (options.start) {
2497
- for (let i = 0; i < data.length; i++) {
2498
- if (data[i].ts < options.start) {
2499
- data.splice(i, 1);
2500
- i--;
2501
- } else {
2502
- break;
2503
- }
2504
- }
2505
- }
2506
- data.splice(options.count);
2507
- options.debugLog && adapter.log.debug(`${options.logId} pre-cut data to ${options.count} oldest values`);
2508
- }
2509
-
2510
- data.sort(sortByTs);
2511
- }
2512
- try {
2513
- commons.sendResponse(adapter, msg, options, (err ? err.toString() : null) || data, startTime)
2514
- } catch (e) {
2515
- commons.sendResponse(adapter, msg, options, e.toString(), startTime);
2516
- }
2517
- });
2518
- }
2519
- });
2520
- } else {
2521
- // if all IDs requested
2522
- let rows = [];
2523
- let count = 0;
2524
- getCachedData(options, (cacheData, isFull, includesInFlightData, earliestTs) => {
2525
- if (isFull && cacheData.length) {
2526
- cacheData.sort(sortByTs);
2527
- commons.sendResponse(adapter, msg, options, cacheData, startTime);
2528
- } else {
2529
- if (includesInFlightData) {
2530
- options.end = earliestTs;
2531
- }
2532
- for (let db = 0; db < dbNames.length; db++) {
2533
- count++;
2534
- getDataFromDB(dbNames[db], options, (err, data) => {
2535
- if (data) {
2536
- rows = rows.concat(data);
2537
- }
2538
- if (!--count) {
2539
- rows.sort(sortByTs);
2540
- try {
2541
- commons.sendResponse(adapter, msg, options, rows, startTime);
2542
- } catch (e) {
2543
- commons.sendResponse(adapter, msg, options, e.toString(), startTime);
2544
- }
2545
- }
2546
- });
2547
- }
2548
- }
2549
- });
2550
- }
2551
- }
2552
-
2553
- function update(id, state, cb) {
2554
- // first try to find the value in not yet saved data
2555
- let found = false;
2556
- if (sqlDPs[id]) {
2557
- const res = sqlDPs[id].list;
2558
- if (res) {
2559
- for (let i = res.length - 1; i >= 0; i--) {
2560
- if (res[i].state.ts === state.ts) {
2561
- if (state.val !== undefined) {
2562
- res[i].state.val = state.val;
2563
- }
2564
- if (state.q !== undefined && res[i].q !== undefined) {
2565
- res[i].state.q = state.q;
2566
- }
2567
- if (state.from !== undefined && res[i].from !== undefined) {
2568
- res[i].state.from = state.from;
2569
- }
2570
- if (state.ack !== undefined) {
2571
- res[i].state.ack = state.ack;
2572
- }
2573
- found = true;
2574
- break;
2575
- }
2576
- }
2577
- }
2578
- }
2579
-
2580
- if (!found) {
2581
- prepareTaskCheckTypeAndDbId(id, state, false, err => {
2582
- if (err) {
2583
- return cb && cb(err);
2584
- }
2585
-
2586
- const type = sqlDPs[id].type;
2587
-
2588
- const query = SQLFuncs.update(adapter.config.dbname, sqlDPs[id].index, state, from[state.from], dbNames[type]);
2589
-
2590
- if (!multiRequests) {
2591
- if (tasks.length > MAXTASKS) {
2592
- const error = `Cannot queue new requests, because more than ${MAXTASKS}`;
2593
- adapter.log.error(error);
2594
- cb && cb(error);
2595
- } else {
2596
- tasks.push({operation: 'query', query, id, callback: cb});
2597
- tasks.length === 1 && processTasks();
2598
- }
2599
- } else {
2600
- _executeQuery(query, id, cb);
2601
- }
2602
- });
2603
- } else {
2604
- cb && cb();
2605
- }
2606
- }
2607
-
2608
- function _delete(id, state, cb) {
2609
- // first try to find the value in not yet saved data
2610
- let found = false;
2611
- if (sqlDPs[id]) {
2612
- const res = sqlDPs[id].list;
2613
- if (res) {
2614
- if (!state.ts && !state.start && !state.end) {
2615
- sqlDPs[id].list = [];
2616
- } else {
2617
- for (let i = res.length - 1; i >= 0; i--) {
2618
- if (state.start && state.end) {
2619
- if (res[i].state.ts >= state.start && res[i].state.ts <= state.end) {
2620
- res.splice(i, 1);
2621
- }
2622
- } else if (state.start) {
2623
- if (res[i].state.ts >= state.start) {
2624
- res.splice(i, 1);
2625
- }
2626
- } else if (state.end) {
2627
- if (res[i].state.ts <= state.end) {
2628
- res.splice(i, 1);
2629
- }
2630
- } else
2631
- if (res[i].state.ts === state.ts) {
2632
- res.splice(i, 1);
2633
- found = true;
2634
- break;
2635
- }
2636
- }
2637
- }
2638
- }
2639
- }
2640
-
2641
- if (!found) {
2642
- prepareTaskCheckTypeAndDbId(id, state, false, err => {
2643
- if (err) {
2644
- return cb && cb(err);
2645
- }
2646
-
2647
- const type = sqlDPs[id].type;
2648
-
2649
- let query;
2650
- if (state.start && state.end) {
2651
- query = SQLFuncs.delete(adapter.config.dbname, dbNames[type], sqlDPs[id].index, state.start, state.end);
2652
- } else if (state.ts) {
2653
- query = SQLFuncs.delete(adapter.config.dbname, dbNames[type], sqlDPs[id].index, state.ts);
2654
- } else {
2655
- query = SQLFuncs.delete(adapter.config.dbname, dbNames[type], sqlDPs[id].index);
2656
- }
2657
-
2658
- if (!multiRequests) {
2659
- if (tasks.length > MAXTASKS) {
2660
- const error = `Cannot queue new requests, because more than ${MAXTASKS}`;
2661
- adapter.log.error(error);
2662
- cb && cb(error);
2663
- } else {
2664
- tasks.push({operation: 'query', query, id, callback: cb});
2665
- tasks.length === 1 && processTasks();
2666
- }
2667
- } else {
2668
- _executeQuery(query, id, cb);
2669
- }
2670
- });
2671
- } else {
2672
- cb && cb();
2673
- }
2674
- }
2675
-
2676
- function updateState(msg) {
2677
- if (!msg.message) {
2678
- adapter.log.error('updateState called with invalid data');
2679
- return adapter.sendTo(msg.from, msg.command, {
2680
- error: `Invalid call: ${JSON.stringify(msg)}`
2681
- }, msg.callback);
2682
- }
2683
- let id;
2684
- if (Array.isArray(msg.message)) {
2685
- adapter.log.debug(`updateState ${msg.message.length} items`);
2686
- for (let i = 0; i < msg.message.length; i++) {
2687
- id = aliasMap[msg.message[i].id] ? aliasMap[msg.message[i].id] : msg.message[i].id;
2688
-
2689
- if (msg.message[i].state && typeof msg.message[i].state === 'object') {
2690
- update(id, msg.message[i].state);
2691
- } else {
2692
- adapter.log.warn(`Invalid state for ${JSON.stringify(msg.message[i])}`);
2693
- }
2694
- }
2695
- } else if (msg.message.state && Array.isArray(msg.message.state)) {
2696
- adapter.log.debug(`updateState ${msg.message.state.length} items`);
2697
- id = aliasMap[msg.message.id] ? aliasMap[msg.message.id] : msg.message.id;
2698
- for (let j = 0; j < msg.message.state.length; j++) {
2699
- if (msg.message.state[j] && typeof msg.message.state[j] === 'object') {
2700
- update(id, msg.message.state[j]);
2701
- } else {
2702
- adapter.log.warn(`Invalid state for ${JSON.stringify(msg.message.state[j])}`);
2703
- }
2704
- }
2705
- } else if (msg.message.id && msg.message.state && typeof msg.message.state === 'object') {
2706
- adapter.log.debug('updateState 1 item');
2707
- id = aliasMap[msg.message.id] ? aliasMap[msg.message.id] : msg.message.id;
2708
- return update(id, msg.message.state, () => adapter.sendTo(msg.from, msg.command, {
2709
- success: true,
2710
- connected: !!clientPool
2711
- }, msg.callback));
2712
- } else {
2713
- adapter.log.error('updateState called with invalid data');
2714
- return adapter.sendTo(msg.from, msg.command, {
2715
- error: `Invalid call: ${JSON.stringify(msg)}`
2716
- }, msg.callback);
2717
- }
2718
-
2719
- adapter.sendTo(msg.from, msg.command, {
2720
- success: true,
2721
- connected: !!clientPool
2722
- }, msg.callback);
2723
- }
2724
-
2725
- function deleteState(msg) {
2726
- if (!msg.message) {
2727
- adapter.log.error('deleteState called with invalid data');
2728
- return adapter.sendTo(msg.from, msg.command, {
2729
- error: `Invalid call: ${JSON.stringify(msg)}`
2730
- }, msg.callback);
2731
- }
2732
- let id;
2733
- if (Array.isArray(msg.message)) {
2734
- adapter.log.debug(`deleteState ${msg.message.length} items`);
2735
- for (let i = 0; i < msg.message.length; i++) {
2736
- id = aliasMap[msg.message[i].id] ? aliasMap[msg.message[i].id] : msg.message[i].id;
2737
-
2738
- // {id: 'blabla', ts: 892}
2739
- if (msg.message[i].ts) {
2740
- _delete(id, {ts: msg.message[i].ts});
2741
- } else
2742
- if (msg.message[i].start) {
2743
- if (typeof msg.message[i].start === 'string') {
2744
- msg.message[i].start = new Date(msg.message[i].start).getTime();
2745
- }
2746
- if (typeof msg.message[i].end === 'string') {
2747
- msg.message[i].end = new Date(msg.message[i].end).getTime();
2748
- }
2749
- _delete(id, {start: msg.message[i].start, end: msg.message[i].end || Date.now()});
2750
- } else
2751
- if (typeof msg.message[i].state === 'object' && msg.message[i].state && msg.message[i].state.ts) {
2752
- _delete(id, {ts: msg.message[i].state.ts});
2753
- } else
2754
- if (typeof msg.message[i].state === 'object' && msg.message[i].state && msg.message[i].state.start) {
2755
- if (typeof msg.message[i].state.start === 'string') {
2756
- msg.message[i].state.start = new Date(msg.message[i].state.start).getTime();
2757
- }
2758
- if (typeof msg.message[i].state.end === 'string') {
2759
- msg.message[i].state.end = new Date(msg.message[i].state.end).getTime();
2760
- }
2761
- _delete(id, {start: msg.message[i].state.start, end: msg.message[i].state.end || Date.now()});
2762
- } else {
2763
- adapter.log.warn(`Invalid state for ${JSON.stringify(msg.message[i])}`);
2764
- }
2765
- }
2766
- } else if (msg.message.state && Array.isArray(msg.message.state)) {
2767
- adapter.log.debug(`deleteState ${msg.message.state.length} items`);
2768
- id = aliasMap[msg.message.id] ? aliasMap[msg.message.id] : msg.message.id;
2769
-
2770
- for (let j = 0; j < msg.message.state.length; j++) {
2771
- if (msg.message.state[j] && typeof msg.message.state[j] === 'object') {
2772
- if (msg.message.state[j].ts) {
2773
- _delete(id, {ts: msg.message.state[j].ts});
2774
- } else if (msg.message.state[j].start) {
2775
- if (typeof msg.message.state[j].start === 'string') {
2776
- msg.message.state[j].start = new Date(msg.message.state[j].start).getTime();
2777
- }
2778
- if (typeof msg.message.state[j].end === 'string') {
2779
- msg.message.state[j].end = new Date(msg.message.state[j].end).getTime();
2780
- }
2781
- _delete(id, {start: msg.message.state[j].start, end: msg.message.state[j].end || Date.now()});
2782
- }
2783
- } else if (msg.message.state[j] && typeof msg.message.state[j] === 'number') {
2784
- _delete(id, {ts: msg.message.state[j]});
2785
- } else {
2786
- adapter.log.warn(`Invalid state for ${JSON.stringify(msg.message.state[j])}`);
2787
- }
2788
- }
2789
- } else if (msg.message.ts && Array.isArray(msg.message.ts)) {
2790
- adapter.log.debug(`deleteState ${msg.message.ts.length} items`);
2791
- id = aliasMap[msg.message.id] ? aliasMap[msg.message.id] : msg.message.id;
2792
- for (let j = 0; j < msg.message.ts.length; j++) {
2793
- if (msg.message.ts[j] && typeof msg.message.ts[j] === 'number') {
2794
- _delete(id, {ts: msg.message.ts[j]});
2795
- } else {
2796
- adapter.log.warn(`Invalid state for ${JSON.stringify(msg.message.ts[j])}`);
2797
- }
2798
- }
2799
- } else if (msg.message.id && msg.message.state && typeof msg.message.state === 'object') {
2800
- adapter.log.debug('deleteState 1 item');
2801
- id = aliasMap[msg.message.id] ? aliasMap[msg.message.id] : msg.message.id;
2802
- return _delete(id, {ts: msg.message.state.ts}, () => adapter.sendTo(msg.from, msg.command, {
2803
- success: true,
2804
- connected: !!clientPool
2805
- }, msg.callback));
2806
- } else if (msg.message.id && msg.message.ts && typeof msg.message.ts === 'number') {
2807
- adapter.log.debug('deleteState 1 item');
2808
- id = aliasMap[msg.message.id] ? aliasMap[msg.message.id] : msg.message.id;
2809
- return _delete(id, {ts: msg.message.ts}, () => adapter.sendTo(msg.from, msg.command, {
2810
- success: true,
2811
- connected: !!clientPool
2812
- }, msg.callback));
2813
- } else {
2814
- adapter.log.error('deleteState called with invalid data');
2815
- return adapter.sendTo(msg.from, msg.command, {error: `Invalid call: ${JSON.stringify(msg)}`}, msg.callback);
2816
- }
2817
-
2818
- adapter.sendTo(msg.from, msg.command, {
2819
- success: true,
2820
- connected: !!clientPool
2821
- }, msg.callback);
2822
- }
2823
-
2824
- function deleteStateAll(msg) {
2825
- if (!msg.message) {
2826
- adapter.log.error('deleteState called with invalid data');
2827
- return adapter.sendTo(msg.from, msg.command, {
2828
- error: `Invalid call: ${JSON.stringify(msg)}`
2829
- }, msg.callback);
2830
- }
2831
- let id;
2832
- if (Array.isArray(msg.message)) {
2833
- adapter.log.debug(`deleteStateAll ${msg.message.length} items`);
2834
- for (let i = 0; i < msg.message.length; i++) {
2835
- id = aliasMap[msg.message[i].id] ? aliasMap[msg.message[i].id] : msg.message[i].id;
2836
- _delete(id, {});
2837
- }
2838
- } else if (msg.message.id) {
2839
- adapter.log.debug('deleteStateAll 1 item');
2840
- id = aliasMap[msg.message.id] ? aliasMap[msg.message.id] : msg.message.id;
2841
- return _delete(id, {}, () => adapter.sendTo(msg.from, msg.command, {
2842
- success: true,
2843
- connected: !!clientPool
2844
- }, msg.callback));
2845
- } else {
2846
- adapter.log.error('deleteStateAll called with invalid data');
2847
- return adapter.sendTo(msg.from, msg.command, {error: `Invalid call: ${JSON.stringify(msg)}`}, msg.callback);
2848
- }
2849
-
2850
- adapter.sendTo(msg.from, msg.command, {
2851
- success: true,
2852
- connected: !!clientPool
2853
- }, msg.callback);
2854
- }
2855
-
2856
- function storeStatePushData(id, state, applyRules) {
2857
- if (!state || typeof state !== 'object') {
2858
- throw new Error(`State ${JSON.stringify(state)} for ${id} is not valid`);
2859
- }
2860
-
2861
- let pushFunc = applyRules ? pushHistory : pushHelper;
2862
- if (!sqlDPs[id] || !sqlDPs[id][adapter.namespace]) {
2863
- if (applyRules) {
2864
- throw new Error(`sql not enabled for ${id}, so can not apply the rules as requested`);
2865
- }
2866
- sqlDPs[id] = sqlDPs[id] || {};
2867
- sqlDPs[id].realId = id;
2868
- }
2869
- return new Promise((resolve, reject) => {
2870
- pushFunc(id, state , err => {
2871
- if (err) {
2872
- reject(new Error(`Error writing state for ${id}: ${err.message}, Data: ${JSON.stringify(state)}`));
2873
- } else {
2874
- resolve(true);
2875
- }
2876
- });
2877
- });
2878
- }
2879
-
2880
- async function storeState(msg) {
2881
- if (!msg.message) {
2882
- adapter.log.error('storeState called with invalid data');
2883
- return adapter.sendTo(msg.from, msg.command, {
2884
- error: `Invalid call: ${JSON.stringify(msg)}`
2885
- }, msg.callback);
2886
- }
2887
-
2888
- let errors = [];
2889
- let successCount = 0;
2890
- if (Array.isArray(msg.message)) {
2891
- adapter.log.debug(`storeState ${msg.message.length} items`);
2892
- for (let i = 0; i < msg.message.length; i++) {
2893
- const id = aliasMap[msg.message[i].id] ? aliasMap[msg.message[i].id] : msg.message[i].id;
2894
- try {
2895
- await storeStatePushData(id, msg.message[i].state, msg.message.rules);
2896
- successCount++;
2897
- } catch (err) {
2898
- errors.push(err.message);
2899
- }
2900
- }
2901
- } else if (msg.message.id && Array.isArray(msg.message.state)) {
2902
- adapter.log.debug(`storeState ${msg.message.state.length} items`);
2903
- const id = aliasMap[msg.message.id] ? aliasMap[msg.message.id] : msg.message.id;
2904
- for (let j = 0; j < msg.message.state.length; j++) {
2905
- try {
2906
- await storeStatePushData(id, msg.message.state[j], msg.message.rules);
2907
- successCount++;
2908
- } catch (err) {
2909
- errors.push(err.message);
2910
- }
2911
- }
2912
- } else if (msg.message.id && msg.message.state) {
2913
- adapter.log.debug('storeState 1 item');
2914
- const id = aliasMap[msg.message.id] ? aliasMap[msg.message.id] : msg.message.id;
2915
- try {
2916
- await storeStatePushData(id, msg.message.state, msg.message.rules);
2917
- successCount++;
2918
- } catch (err) {
2919
- errors.push(err.message);
2920
- }
2921
- } else {
2922
- adapter.log.error('storeState called with invalid data');
2923
- return adapter.sendTo(msg.from, msg.command, {
2924
- error: `Invalid call: ${JSON.stringify(msg)}`
2925
- }, msg.callback);
2926
- }
2927
- if (errors.length) {
2928
- adapter.log.warn(`storeState executed with ${errors.length} errors: ${errors.join(', ')}`);
2929
- return adapter.sendTo(msg.from, msg.command, {
2930
- error: `${errors.length} errors happened while storing data`,
2931
- errors: errors,
2932
- successCount
2933
- }, msg.callback);
2934
- }
2935
-
2936
- adapter.log.debug(`storeState executed with ${successCount} states successfully`);
2937
-
2938
- adapter.sendTo(msg.from, msg.command, {
2939
- success: true,
2940
- successCount,
2941
- connected: !!clientPool
2942
- }, msg.callback);
2943
- }
2944
-
2945
- function getDpOverview(msg) {
2946
- const result = {};
2947
- const query = SQLFuncs.getIdSelect(adapter.config.dbname);
2948
- adapter.log.info(query);
2949
-
2950
- borrowClientFromPool((err, client) => {
2951
- if (err) {
2952
- returnClientToPool(client);
2953
- return adapter.sendTo(msg.from, msg.command, {
2954
- error: `Cannot select ${query}: ${err}`
2955
- }, msg.callback);
2956
- }
2957
- client.execute(query, (err, rows /* , fields */) => {
2958
- if (rows && rows.rows) {
2959
- rows = rows.rows;
2960
- }
2961
- if (err) {
2962
- returnClientToPool(client);
2963
-
2964
- adapter.log.error(`Cannot select ${query}: ${err}`);
2965
-
2966
- adapter.sendTo(msg.from, msg.command, {
2967
- error: `Cannot select ${query}: ${err}`
2968
- }, msg.callback);
2969
- return;
2970
- }
2971
-
2972
- adapter.log.info(`Query result ${JSON.stringify(rows)}`);
2973
-
2974
- if (rows.length) {
2975
- for (let r = 0; r < rows.length; r++) {
2976
- if (!result[rows[r].type]) {
2977
- result[rows[r].type] = {};
2978
- }
2979
-
2980
- result[rows[r].type][rows[r].id] = {};
2981
-
2982
- result[rows[r].type][rows[r].id].name = rows[r].name;
2983
-
2984
- switch (dbNames[rows[r].type]) {
2985
- case 'ts_number':
2986
- result[rows[r].type][rows[r].id].type = 'number';
2987
- break;
2988
-
2989
- case 'ts_string':
2990
- result[rows[r].type][rows[r].id].type = 'string';
2991
- break;
2992
-
2993
- case 'ts_bool':
2994
- result[rows[r].type][rows[r].id].type = 'boolean';
2995
- break;
2996
- }
2997
- }
2998
-
2999
- adapter.log.info(`initialisation result: ${JSON.stringify(result)}`);
3000
- getFirstTsForIds(client, 0, result, msg);
3001
- }
3002
- });
3003
- });
3004
- }
3005
-
3006
- function getFirstTsForIds(dbClient, typeId, resultData, msg) {
3007
- if (typeId < dbNames.length) {
3008
- if (!resultData[typeId]) {
3009
- getFirstTsForIds(dbClient, typeId + 1, resultData, msg);
3010
- } else {
3011
- const query = SQLFuncs.getFirstTs(adapter.config.dbname, dbNames[typeId]);
3012
- adapter.log.info(query);
3013
-
3014
- dbClient.execute(query, (err, rows /* , fields */) => {
3015
- if (rows && rows.rows) {
3016
- rows = rows.rows;
3017
- }
3018
-
3019
- if (err) {
3020
- returnClientToPool(dbClient);
3021
-
3022
- adapter.log.error(`Cannot select ${query}: ${err}`);
3023
- adapter.sendTo(msg.from, msg.command, {
3024
- error: `Cannot select ${query}: ${err}`
3025
- }, msg.callback);
3026
- return;
3027
- }
3028
-
3029
- adapter.log.info(`Query result ${JSON.stringify(rows)}`);
3030
-
3031
- if (rows.length) {
3032
- for (let r = 0; r < rows.length; r++) {
3033
- if (resultData[typeId][rows[r].id]) {
3034
- resultData[typeId][rows[r].id].ts = rows[r].ts;
3035
- }
3036
- }
3037
- }
3038
-
3039
- adapter.log.info(`enhanced result (${typeId}): ${JSON.stringify(resultData)}`);
3040
- dpOverviewTimeout = setTimeout((dbClient, typeId, resultData, msg) => {
3041
- dpOverviewTimeout = null;
3042
- getFirstTsForIds(dbClient, typeId, resultData, msg);
3043
- }, 5000, dbClient, typeId + 1, resultData, msg);
3044
- });
3045
- }
3046
- } else {
3047
- returnClientToPool(dbClient);
3048
-
3049
- adapter.log.info('consolidate data ...');
3050
- const result = {};
3051
- for (let ti = 0; ti < dbNames.length; ti++ ) {
3052
- if (resultData[ti]) {
3053
- for (let index in resultData[ti]) {
3054
- if (!resultData[ti].hasOwnProperty(index)) {
3055
- continue;
3056
- }
3057
-
3058
- const id = resultData[ti][index].name;
3059
- if (!result[id]) {
3060
- result[id] = {};
3061
- result[id].type = resultData[ti][index].type;
3062
- result[id].ts = resultData[ti][index].ts;
3063
- } else {
3064
- result[id].type = 'undefined';
3065
- if (resultData[ti][index].ts < result[id].ts) {
3066
- result[id].ts = resultData[ti][index].ts;
3067
- }
3068
- }
3069
- }
3070
- }
3071
- }
3072
- adapter.log.info(`Result: ${JSON.stringify(result)}`);
3073
- adapter.sendTo(msg.from, msg.command, {
3074
- success: true,
3075
- result: result
3076
- }, msg.callback);
3077
- }
3078
- }
3079
-
3080
- function enableHistory(msg) {
3081
- if (!msg.message || !msg.message.id) {
3082
- adapter.log.error('enableHistory called with invalid data');
3083
- adapter.sendTo(msg.from, msg.command, {
3084
- error: 'Invalid call'
3085
- }, msg.callback);
3086
- return;
3087
- }
3088
-
3089
- const obj = {};
3090
- obj.common = {};
3091
- obj.common.custom = {};
3092
-
3093
- if (msg.message.options) {
3094
- obj.common.custom[adapter.namespace] = msg.message.options;
3095
- } else {
3096
- obj.common.custom[adapter.namespace] = {};
3097
- }
3098
-
3099
- obj.common.custom[adapter.namespace].enabled = true;
3100
-
3101
- adapter.extendForeignObject(msg.message.id, obj, err => {
3102
- if (err) {
3103
- adapter.log.error(`enableHistory: ${err}`);
3104
- adapter.sendTo(msg.from, msg.command, {
3105
- error: err
3106
- }, msg.callback);
3107
- } else {
3108
- adapter.log.info(JSON.stringify(obj));
3109
- adapter.sendTo(msg.from, msg.command, {
3110
- success: true
3111
- }, msg.callback);
3112
- }
3113
- });
3114
- }
3115
-
3116
- function disableHistory(msg) {
3117
- if (!msg.message || !msg.message.id) {
3118
- adapter.log.error('disableHistory called with invalid data');
3119
- return adapter.sendTo(msg.from, msg.command, {
3120
- error: 'Invalid call'
3121
- }, msg.callback);
3122
- }
3123
-
3124
- const obj = {};
3125
- obj.common = {};
3126
- obj.common.custom = {};
3127
- obj.common.custom[adapter.namespace] = {};
3128
- obj.common.custom[adapter.namespace].enabled = false;
3129
-
3130
- adapter.extendForeignObject(msg.message.id, obj, err => {
3131
- if (err) {
3132
- adapter.log.error(`disableHistory: ${err}`);
3133
- adapter.sendTo(msg.from, msg.command, {
3134
- error: err
3135
- }, msg.callback);
3136
- } else {
3137
- adapter.log.info(JSON.stringify(obj));
3138
- adapter.sendTo(msg.from, msg.command, {
3139
- success: true
3140
- }, msg.callback);
3141
- }
3142
- });
3143
- }
3144
-
3145
- function getEnabledDPs(msg) {
3146
- const data = {};
3147
- for (const id in sqlDPs) {
3148
- if (sqlDPs.hasOwnProperty(id) && sqlDPs[id] && sqlDPs[id][adapter.namespace] && sqlDPs[id][adapter.namespace].enabled) {
3149
- data[sqlDPs[id].realId] = sqlDPs[id][adapter.namespace];
3150
- }
3151
- }
3152
-
3153
- adapter.sendTo(msg.from, msg.command, data, msg.callback);
3154
- }
3155
-
3156
- function main() {
3157
- setConnected(false);
3158
-
3159
- // set default history if not yet set
3160
- adapter.getForeignObject('system.config', (err, obj) => {
3161
- if (obj && obj.common && !obj.common.defaultHistory) {
3162
- obj.common.defaultHistory = adapter.namespace;
3163
- adapter.setForeignObject('system.config', obj, err => {
3164
- if (err) {
3165
- adapter.log.error(`Cannot set default history instance: ${err}`);
3166
- } else {
3167
- adapter.log.info(`Set default history instance to "${adapter.namespace}"`);
3168
- }
3169
- });
3170
- }
3171
- });
3172
-
3173
- adapter.config.dbname = adapter.config.dbname || 'iobroker';
3174
-
3175
- if (adapter.config.writeNulls === undefined) {
3176
- adapter.config.writeNulls = true;
3177
- }
3178
-
3179
- adapter.config.retention = parseInt(adapter.config.retention, 10) || 0;
3180
- if (adapter.config.retention === -1 ) { // Custom timeframe
3181
- adapter.config.retention = (parseInt(adapter.config.customRetentionDuration, 10) || 0) * 24 * 60 * 60;
3182
- }
3183
- adapter.config.debounce = parseInt(adapter.config.debounce, 10) || 0;
3184
- adapter.config.requestInterval = (adapter.config.requestInterval === undefined || adapter.config.requestInterval === null || adapter.config.requestInterval === '') ? 0 : parseInt(adapter.config.requestInterval, 10) || 0;
3185
-
3186
- if (adapter.config.changesRelogInterval !== null && adapter.config.changesRelogInterval !== undefined) {
3187
- adapter.config.changesRelogInterval = parseInt(adapter.config.changesRelogInterval, 10);
3188
- } else {
3189
- adapter.config.changesRelogInterval = 0;
3190
- }
3191
-
3192
- if (!clients[adapter.config.dbtype]) {
3193
- adapter.log.error(`Unknown DB type: ${adapter.config.dbtype}`);
3194
- adapter.stop();
3195
- }
3196
- if (adapter.config.multiRequests !== undefined && adapter.config.dbtype !== 'SQLite3Client' && adapter.config.dbtype !== 'sqlite') {
3197
- clients[adapter.config.dbtype].multiRequests = adapter.config.multiRequests;
3198
- }
3199
- if (adapter.config.maxConnections !== undefined && adapter.config.dbtype !== 'SQLite3Client' && adapter.config.dbtype !== 'sqlite') {
3200
- adapter.config.maxConnections = parseInt(adapter.config.maxConnections, 10);
3201
- if (adapter.config.maxConnections !== 0 && !adapter.config.maxConnections) {
3202
- adapter.config.maxConnections = 100;
3203
- }
3204
- } else {
3205
- adapter.config.maxConnections = 1; // SQLite does not support multiple connections
3206
- }
3207
-
3208
- if (adapter.config.changesMinDelta !== null && adapter.config.changesMinDelta !== undefined) {
3209
- adapter.config.changesMinDelta = parseFloat(adapter.config.changesMinDelta.toString().replace(/,/g, '.'));
3210
- } else {
3211
- adapter.config.changesMinDelta = 0;
3212
- }
3213
-
3214
- if (adapter.config.blockTime !== null && adapter.config.blockTime !== undefined) {
3215
- adapter.config.blockTime = parseInt(adapter.config.blockTime, 10) || 0;
3216
- } else {
3217
- if (adapter.config.debounce !== null && adapter.config.debounce !== undefined) {
3218
- adapter.config.debounce = parseInt(adapter.config.debounce, 10) || 0;
3219
- } else {
3220
- adapter.config.blockTime = 0;
3221
- }
3222
- }
3223
-
3224
- if (adapter.config.debounceTime !== null && adapter.config.debounceTime !== undefined) {
3225
- adapter.config.debounceTime = parseInt(adapter.config.debounceTime, 10) || 0;
3226
- } else {
3227
- adapter.config.debounceTime = 0;
3228
- }
3229
-
3230
- multiRequests = clients[adapter.config.dbtype].multiRequests;
3231
- if (!multiRequests) {
3232
- adapter.config.writeNulls = false;
3233
- }
3234
-
3235
- adapter.config.port = parseInt(adapter.config.port, 10) || 0;
3236
-
3237
- if (adapter.config.round !== null && adapter.config.round !== undefined && adapter.config.round !== '') {
3238
- adapter.config.round = parseInt(adapter.config.round, 10);
3239
- if (!isFinite(adapter.config.round) || adapter.config.round < 0) {
3240
- adapter.config.round = null;
3241
- adapter.log.info(`Invalid round value: ${adapter.config.round} - ignore, do not round values`);
3242
- } else {
3243
- adapter.config.round = Math.pow(10, parseInt(adapter.config.round, 10));
3244
- }
3245
- } else {
3246
- adapter.config.round = null;
3247
- }
3248
-
3249
- if (adapter.config.dbtype === 'postgresql' && !SQL.PostgreSQLClient) {
3250
- const postgres = require(`${__dirname}/lib/postgresql-client`);
3251
- for (const attr in postgres) {
3252
- if (postgres.hasOwnProperty(attr) && !SQL[attr]) {
3253
- SQL[attr] = postgres[attr];
3254
- }
3255
- }
3256
- } else if (adapter.config.dbtype === 'mssql' && !SQL.MSSQLClient) {
3257
- const mssql = require(`${__dirname}/lib/mssql-client`);
3258
- for (const attr_ in mssql) {
3259
- if (mssql.hasOwnProperty(attr_) && !SQL[attr_]) {
3260
- SQL[attr_] = mssql[attr_];
3261
- }
3262
- }
3263
- } else if (adapter.config.dbtype === 'mysql' && !SQL.MySQL2Client) {
3264
- const mysql = require(`${__dirname}/lib/mysql-client`);
3265
- for (const attr_ in mysql) {
3266
- if (mysql.hasOwnProperty(attr_) && !SQL[attr_]) {
3267
- SQL[attr_] = mysql[attr_];
3268
- }
3269
- }
3270
- }
3271
- SQLFuncs = require(`${__dirname}/lib/${adapter.config.dbtype}`);
3272
-
3273
- if (adapter.config.dbtype === 'sqlite' || adapter.config.host) {
3274
- connect(() => {
3275
- // read all custom settings
3276
- adapter.getObjectView('system', 'custom' , {}, (err, doc) => {
3277
- let count = 0;
3278
- if (doc && doc.rows) {
3279
- for (let i = 0, l = doc.rows.length; i < l; i++) {
3280
- if (doc.rows[i].value) {
3281
- let id = doc.rows[i].id;
3282
- const realId = id;
3283
- if (doc.rows[i].value[adapter.namespace] && doc.rows[i].value[adapter.namespace].aliasId) {
3284
- aliasMap[id] = doc.rows[i].value[adapter.namespace].aliasId;
3285
- adapter.log.debug(`Found Alias: ${id} --> ${aliasMap[id]}`);
3286
- id = aliasMap[id];
3287
- }
3288
-
3289
- let storedIndex = null;
3290
- let storedType = null;
3291
- if (sqlDPs[id] && sqlDPs[id].index !== undefined) {
3292
- storedIndex = sqlDPs[id].index;
3293
- }
3294
- if (sqlDPs[id] && sqlDPs[id].dbtype !== undefined) {
3295
- storedType = sqlDPs[id].dbtype;
3296
- }
3297
-
3298
- sqlDPs[id] = doc.rows[i].value;
3299
- if (storedIndex !== null) {
3300
- sqlDPs[id].index = storedIndex;
3301
- }
3302
- if (storedType !== null) {
3303
- sqlDPs[id].dbtype = storedType;
3304
- }
3305
-
3306
- if (!sqlDPs[id][adapter.namespace] || typeof sqlDPs[id][adapter.namespace] !== 'object' || sqlDPs[id][adapter.namespace].enabled === false) {
3307
- delete sqlDPs[id];
3308
- } else {
3309
- count++;
3310
- adapter.log.info(`enabled logging of ${id}, Alias=${id !== realId}, ${count} points now activated`);
3311
-
3312
- // maxLength
3313
- if (!sqlDPs[id][adapter.namespace].maxLength && sqlDPs[id][adapter.namespace].maxLength !== '0' && sqlDPs[id][adapter.namespace].maxLength !== 0) {
3314
- sqlDPs[id][adapter.namespace].maxLength = parseInt(adapter.config.maxLength, 10) || 0;
3315
- } else {
3316
- sqlDPs[id][adapter.namespace].maxLength = parseInt(sqlDPs[id][adapter.namespace].maxLength, 10);
3317
- }
3318
-
3319
- // retention
3320
- if (sqlDPs[id][adapter.namespace].retention !== undefined && sqlDPs[id][adapter.namespace].retention !== null && sqlDPs[id][adapter.namespace].retention !== '') {
3321
- sqlDPs[id][adapter.namespace].retention = parseInt(sqlDPs[id][adapter.namespace].retention, 10) || 0;
3322
- } else {
3323
- sqlDPs[id][adapter.namespace].retention = adapter.config.retention;
3324
- }
3325
- if (sqlDPs[id][adapter.namespace].retention === -1) {
3326
- // customRetentionDuration
3327
- if (sqlDPs[id][adapter.namespace].customRetentionDuration !== undefined && sqlDPs[id][adapter.namespace].customRetentionDuration !== null && sqlDPs[id][adapter.namespace].customRetentionDuration !== '') {
3328
- sqlDPs[id][adapter.namespace].customRetentionDuration = parseInt(sqlDPs[id][adapter.namespace].customRetentionDuration, 10) || 0;
3329
- } else {
3330
- sqlDPs[id][adapter.namespace].customRetentionDuration = adapter.config.customRetentionDuration;
3331
- }
3332
- sqlDPs[id][adapter.namespace].retention = sqlDPs[id][adapter.namespace].customRetentionDuration * 24 * 60 * 60
3333
- }
3334
-
3335
- // debounceTime and debounce compatibility handling
3336
- if (!sqlDPs[id][adapter.namespace].blockTime && sqlDPs[id][adapter.namespace].blockTime !== '0' && sqlDPs[id][adapter.namespace].blockTime !== 0) {
3337
- if (!sqlDPs[id][adapter.namespace].debounce && sqlDPs[id][adapter.namespace].debounce !== '0' && sqlDPs[id][adapter.namespace].debounce !== 0) {
3338
- sqlDPs[id][adapter.namespace].blockTime = parseInt(adapter.config.blockTime, 10) || 0;
3339
- } else {
3340
- sqlDPs[id][adapter.namespace].blockTime = parseInt(sqlDPs[id][adapter.namespace].debounce, 10) || 0;
3341
- }
3342
- } else {
3343
- sqlDPs[id][adapter.namespace].blockTime = parseInt(sqlDPs[id][adapter.namespace].blockTime, 10) || 0;
3344
- }
3345
- if (!sqlDPs[id][adapter.namespace].debounceTime && sqlDPs[id][adapter.namespace].debounceTime !== '0' && sqlDPs[id][adapter.namespace].debounceTime !== 0) {
3346
- sqlDPs[id][adapter.namespace].debounceTime = parseInt(adapter.config.debounceTime, 10) || 0;
3347
- } else {
3348
- sqlDPs[id][adapter.namespace].debounceTime = parseInt(sqlDPs[id][adapter.namespace].debounceTime, 10) || 0;
3349
- }
3350
-
3351
- // changesOnly
3352
- sqlDPs[id][adapter.namespace].changesOnly = sqlDPs[id][adapter.namespace].changesOnly === 'true' || sqlDPs[id][adapter.namespace].changesOnly === true;
3353
-
3354
- // ignoreZero
3355
- sqlDPs[id][adapter.namespace].ignoreZero = sqlDPs[id][adapter.namespace].ignoreZero === 'true' || sqlDPs[id][adapter.namespace].ignoreZero === true;
3356
-
3357
- // round
3358
- if (sqlDPs[id][adapter.namespace].round !== null && sqlDPs[id][adapter.namespace].round !== undefined && sqlDPs[id][adapter.namespace] !== '') {
3359
- sqlDPs[id][adapter.namespace].round = parseInt(sqlDPs[id][adapter.namespace], 10);
3360
- if (!isFinite(sqlDPs[id][adapter.namespace].round) || sqlDPs[id][adapter.namespace].round < 0) {
3361
- sqlDPs[id][adapter.namespace].round = adapter.config.round;
3362
- } else {
3363
- sqlDPs[id][adapter.namespace].round = Math.pow(10, parseInt(sqlDPs[id][adapter.namespace].round, 10));
3364
- }
3365
- } else {
3366
- sqlDPs[id][adapter.namespace].round = adapter.config.round;
3367
- }
3368
-
3369
- // ignoreAboveNumber
3370
- if (sqlDPs[id][adapter.namespace].ignoreAboveNumber !== undefined && sqlDPs[id][adapter.namespace].ignoreAboveNumber !== null && sqlDPs[id][adapter.namespace].ignoreAboveNumber !== '') {
3371
- sqlDPs[id][adapter.namespace].ignoreAboveNumber = parseFloat(sqlDPs[id][adapter.namespace].ignoreAboveNumber) || null;
3372
- }
3373
-
3374
- // ignoreBelowNumber and ignoreBelowZero compatibility handling
3375
- if (sqlDPs[id][adapter.namespace].ignoreBelowNumber !== undefined && sqlDPs[id][adapter.namespace].ignoreBelowNumber !== null && sqlDPs[id][adapter.namespace].ignoreBelowNumber !== '') {
3376
- sqlDPs[id][adapter.namespace].ignoreBelowNumber = parseFloat(sqlDPs[id][adapter.namespace].ignoreBelowNumber) || null;
3377
- } else if (sqlDPs[id][adapter.namespace].ignoreBelowZero === 'true' || sqlDPs[id][adapter.namespace].ignoreBelowZero === true) {
3378
- sqlDPs[id][adapter.namespace].ignoreBelowNumber = 0;
3379
- }
3380
-
3381
- // disableSkippedValueLogging
3382
- if (sqlDPs[id][adapter.namespace].disableSkippedValueLogging !== undefined && sqlDPs[id][adapter.namespace].disableSkippedValueLogging !== null && sqlDPs[id][adapter.namespace].disableSkippedValueLogging !== '') {
3383
- sqlDPs[id][adapter.namespace].disableSkippedValueLogging = sqlDPs[id][adapter.namespace].disableSkippedValueLogging === 'true' || sqlDPs[id][adapter.namespace].disableSkippedValueLogging === true;
3384
- } else {
3385
- sqlDPs[id][adapter.namespace].disableSkippedValueLogging = adapter.config.disableSkippedValueLogging;
3386
- }
3387
-
3388
- // enableDebugLogs
3389
- if (sqlDPs[id][adapter.namespace].enableDebugLogs !== undefined && sqlDPs[id][adapter.namespace].enableDebugLogs !== null && sqlDPs[id][adapter.namespace].enableDebugLogs !== '') {
3390
- sqlDPs[id][adapter.namespace].enableDebugLogs = sqlDPs[id][adapter.namespace].enableDebugLogs === 'true' || sqlDPs[id][adapter.namespace].enableDebugLogs === true;
3391
- } else {
3392
- sqlDPs[id][adapter.namespace].enableDebugLogs = adapter.config.enableDebugLogs;
3393
- }
3394
-
3395
- // changesRelogInterval
3396
- if (sqlDPs[id][adapter.namespace].changesRelogInterval !== undefined && sqlDPs[id][adapter.namespace].changesRelogInterval !== null && sqlDPs[id][adapter.namespace].changesRelogInterval !== '') {
3397
- sqlDPs[id][adapter.namespace].changesRelogInterval = parseInt(sqlDPs[id][adapter.namespace].changesRelogInterval, 10) || 0;
3398
- } else {
3399
- sqlDPs[id][adapter.namespace].changesRelogInterval = adapter.config.changesRelogInterval;
3400
- }
3401
-
3402
- // changesMinDelta
3403
- if (sqlDPs[id][adapter.namespace].changesMinDelta !== undefined && sqlDPs[id][adapter.namespace].changesMinDelta !== null && sqlDPs[id][adapter.namespace].changesMinDelta !== '') {
3404
- sqlDPs[id][adapter.namespace].changesMinDelta = parseFloat(sqlDPs[id][adapter.namespace].changesMinDelta.toString().replace(/,/g, '.')) || 0;
3405
- } else {
3406
- sqlDPs[id][adapter.namespace].changesMinDelta = adapter.config.changesMinDelta;
3407
- }
3408
-
3409
- // storageType
3410
- if (!sqlDPs[id][adapter.namespace].storageType) {
3411
- sqlDPs[id][adapter.namespace].storageType = false;
3412
- }
3413
-
3414
- // add one day if retention is too small
3415
- if (sqlDPs[id][adapter.namespace].retention && sqlDPs[id][adapter.namespace].retention <= 604800) {
3416
- sqlDPs[id][adapter.namespace].retention += 86400;
3417
- }
3418
-
3419
- // relogTimeout
3420
- if (sqlDPs[id][adapter.namespace] && sqlDPs[id][adapter.namespace].changesOnly && sqlDPs[id][adapter.namespace].changesRelogInterval > 0) {
3421
- sqlDPs[id].relogTimeout && clearTimeout(sqlDPs[id].relogTimeout);
3422
- sqlDPs[id].relogTimeout = setTimeout(reLogHelper, (sqlDPs[id][adapter.namespace].changesRelogInterval * 500 * Math.random()) + sqlDPs[id][adapter.namespace].changesRelogInterval * 500, id);
3423
- }
3424
-
3425
- sqlDPs[id].realId = realId;
3426
- sqlDPs[id].list = sqlDPs[id].list || [];
3427
- sqlDPs[id].inFlight = sqlDPs[id].inFlight || {};
3428
-
3429
- // randomize lastCheck to avoid all datapoints to be checked at same timepoint
3430
- sqlDPs[id].lastCheck = Date.now() - Math.floor(Math.random() * 21600000/* 6 hours */);
3431
- }
3432
- }
3433
- }
3434
- }
3435
-
3436
- adapter.config.writeNulls && writeNulls();
3437
-
3438
- if (count < 200) {
3439
- Object.keys(sqlDPs).forEach(id =>
3440
- sqlDPs[id] && sqlDPs[id][adapter.namespace] && !sqlDPs[id].realId && adapter.log.warn(`No realID found for ${id}`));
3441
-
3442
- // BF (2020.05.20) change it later to
3443
- // adapter.subscribeForeignStates(Object.keys(sqlDPs).forEach(id => sqlDPs[id] && sqlDPs[id][adapter.namespace] && sqlDPs[id].realId).filter(id => id));
3444
-
3445
- Object.keys(sqlDPs).forEach(id =>
3446
- sqlDPs[id] && sqlDPs[id][adapter.namespace] && sqlDPs[id].realId && adapter.subscribeForeignStates(sqlDPs[id].realId));
3447
- } else {
3448
- subscribeAll = true;
3449
- adapter.subscribeForeignStates('*');
3450
- }
3451
- adapter.subscribeForeignObjects('*');
3452
- adapter.log.debug('Initialization done');
3453
- setConnected(true);
3454
- processStartValues();
3455
-
3456
- // store all buffered data every 10 minutes to not lost the data
3457
- bufferChecker = setInterval(() => storeCached(), 10 * 60000);
3458
- });
3459
- });
3460
- }
3461
- }
3462
-
3463
- // If started as allInOne/compact mode => return function to create instance
3464
- if (module.parent) {
3465
- module.exports = startAdapter;
3466
- } else {
3467
- // or start the instance directly
3468
- startAdapter();
3469
- }