iobroker.sql 1.16.2 → 2.0.2

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.
package/main.js CHANGED
@@ -12,7 +12,7 @@ let SQLFuncs = null;
12
12
 
13
13
  const clients = {
14
14
  postgresql: {name: 'PostgreSQLClient', multiRequests: true},
15
- mysql: {name: 'MySQLClient', multiRequests: true},
15
+ mysql: {name: 'MySQL2Client', multiRequests: true},
16
16
  sqlite: {name: 'SQLite3Client', multiRequests: false},
17
17
  mssql: {name: 'MSSQLClient', multiRequests: true}
18
18
  };
@@ -52,6 +52,8 @@ let subscribeAll = false;
52
52
  let clientPool;
53
53
  let reconnectTimeout = null;
54
54
  let testConnectTimeout = null;
55
+ let dpOverviewTimeout = null;
56
+ let bufferChecker = null;
55
57
 
56
58
  function isEqual(a, b) {
57
59
  //console.log('Compare ' + JSON.stringify(a) + ' with ' + JSON.stringify(b));
@@ -109,7 +111,7 @@ function startAdapter(options) {
109
111
  const now = Date.now();
110
112
  const formerAliasId = aliasMap[id] ? aliasMap[id] : id;
111
113
 
112
- 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) {
114
+ 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) {
113
115
  const realId = id;
114
116
  let checkForRemove = true;
115
117
 
@@ -141,22 +143,10 @@ function startAdapter(options) {
141
143
  adapter.subscribeForeignStates('*');
142
144
  }
143
145
 
144
- let storedIndex = null;
145
- let storedType = null;
146
- if (sqlDPs[id] && sqlDPs[id].index !== undefined) {
147
- storedIndex = sqlDPs[id].index;
148
- }
149
-
150
- if (sqlDPs[id] && sqlDPs[id].dbtype !== undefined) {
151
- storedType = sqlDPs[id].dbtype;
152
- } else if (sqlDPs[formerAliasId] && sqlDPs[formerAliasId].dbtype !== undefined) {
153
- storedType = sqlDPs[formerAliasId].dbtype;
154
- }
155
-
156
- if (storedIndex === undefined) {
157
- getId(id, sqlDPs[id].dbtype, () => reInit(id, realId, formerAliasId, storedIndex, storedType, obj));
146
+ if (sqlDPs[id] && sqlDPs[id].index === undefined) {
147
+ getId(id, sqlDPs[id].dbtype, () => reInit(id, realId, formerAliasId, obj));
158
148
  } else {
159
- reInit(id, realId, formerAliasId, storedIndex, storedType, obj);
149
+ reInit(id, realId, formerAliasId, obj);
160
150
  }
161
151
  } else {
162
152
  if (aliasMap[id]) {
@@ -166,42 +156,59 @@ function startAdapter(options) {
166
156
 
167
157
  id = formerAliasId;
168
158
 
169
- if (sqlDPs[id]) {
170
- adapter.log.info('disabled logging of ' + id);
171
- sqlDPs[id].relogTimeout && clearTimeout(sqlDPs[id].relogTimeout);
172
- sqlDPs[id].timeout && clearTimeout(sqlDPs[id].timeout);
159
+ if (sqlDPs[id] && sqlDPs[id][adapter.namespace]) {
160
+ adapter.log.info(`disabled logging of ${id}`);
161
+ if (sqlDPs[id].relogTimeout) {
162
+ clearTimeout(sqlDPs[id].relogTimeout);
163
+ sqlDPs[id].relogTimeout = null;
164
+ }
165
+ if (sqlDPs[id].timeout) {
166
+ clearTimeout(sqlDPs[id].timeout);
167
+ sqlDPs[id].timeout = null;
168
+ }
173
169
 
174
170
  tmpState = Object.assign({}, sqlDPs[id].state);
175
171
  const state = sqlDPs[id].state ? tmpState : null;
176
172
 
177
- if (sqlDPs[id].skipped) {
178
- pushValueIntoDB(id, sqlDPs[id].skipped);
179
- sqlDPs[id].skipped = null;
180
- }
173
+ if (sqlDPs[id][adapter.namespace]) {
174
+ sqlDPs[id][adapter.namespace].enabled = false;
175
+ if (sqlDPs[id].skipped && !sqlDPs[id][adapter.namespace].disableSkippedValueLogging) {
176
+ pushValueIntoDB(id, sqlDPs[id].skipped, false, true);
177
+ sqlDPs[id].skipped = null;
178
+ }
181
179
 
182
- const nullValue = {val: null, ts: now, lc: now, q: 0x40, from: 'system.adapter.' + adapter.namespace};
183
-
184
- if (sqlDPs[id][adapter.namespace] && adapter.config.writeNulls) {
185
- if (sqlDPs[id][adapter.namespace].changesOnly && state && state.val !== null) {
186
- (function (_id, _state, _nullValue) {
187
- _state.ts = now;
188
- _state.from = 'system.adapter.' + adapter.namespace;
189
- nullValue.ts += 4;
190
- nullValue.lc += 4; // because of MS SQL
191
- adapter.log.debug(`Write 1/2 "${_state.val}" _id: ${_id}`);
192
- pushValueIntoDB(_id, _state, () => {
193
- // terminate values with null to indicate adapter stop. timestamp + 1#
194
- adapter.log.debug(`Write 2/2 "null" _id: ${_id}`);
195
- pushValueIntoDB(_id, _nullValue, () => delete sqlDPs[id][adapter.namespace]);
196
- });
197
- })(id, state, nullValue);
180
+ if (adapter.config.writeNulls) {
181
+ const nullValue = {
182
+ val: null,
183
+ ts: now,
184
+ lc: now,
185
+ q: 0x40,
186
+ from: `system.adapter.${adapter.namespace}`
187
+ };
188
+
189
+ if (sqlDPs[id][adapter.namespace].changesOnly && state && state.val !== null) {
190
+ (function (_id, _state, _nullValue) {
191
+ _state.ts = now;
192
+ _state.from = `system.adapter.${adapter.namespace}`;
193
+ nullValue.ts += 4;
194
+ nullValue.lc += 4; // because of MS SQL
195
+ adapter.log.debug(`Write 1/2 "${_state.val}" _id: ${_id}`);
196
+ pushValueIntoDB(_id, _state, false, true, () => {
197
+ // terminate values with null to indicate adapter stop. timestamp + 1
198
+ adapter.log.debug(`Write 2/2 "null" _id: ${_id}`);
199
+ pushValueIntoDB(_id, _nullValue, () => delete sqlDPs[id]);
200
+ });
201
+ })(id, state, nullValue);
202
+ } else {
203
+ // terminate values with null to indicate adapter stop. timestamp + 1
204
+ adapter.log.debug(`Write 0 NULL _id: ${id}`);
205
+ pushValueIntoDB(id, nullValue, () => delete sqlDPs[id]);
206
+ }
198
207
  } else {
199
- // terminate values with null to indicate adapter stop. timestamp + 1
200
- adapter.log.debug('Write 0 NULL _id: ' + id);
201
- pushValueIntoDB(id, nullValue, () => delete sqlDPs[id][adapter.namespace]);
208
+ storeCached(id, () => delete sqlDPs[id]);
202
209
  }
203
210
  } else {
204
- delete sqlDPs[id][adapter.namespace];
211
+ delete sqlDPs[id];
205
212
  }
206
213
  }
207
214
  }
@@ -237,7 +244,7 @@ function borrowClientFromPool(callback) {
237
244
  // make sure we always have at least one error listener to prevent crashes
238
245
  if (client.on && client.listenerCount && client.listenerCount('error') === 0) {
239
246
  client.on('error', err =>
240
- adapter.log.warn('SQL client error: ' + err));
247
+ adapter.log.warn(`SQL client error: ${err}`));
241
248
  }
242
249
  }
243
250
 
@@ -249,8 +256,14 @@ function returnClientToPool(client) {
249
256
  return clientPool && clientPool.return(client);
250
257
  }
251
258
 
252
- function reInit(id, realId, formerAliasId, storedIndex, storedType, obj) {
253
- adapter.log.debug(`remembered Index/Type ${storedIndex} / ${storedType}`);
259
+ function reInit(id, realId, formerAliasId, obj) {
260
+
261
+ // maxLength
262
+ if (!obj.common.custom[adapter.namespace].maxLength && obj.common.custom[adapter.namespace].maxLength !== '0' && obj.common.custom[adapter.namespace].maxLength !== 0) {
263
+ obj.common.custom[adapter.namespace].maxLength = parseInt(adapter.config.maxLength, 10) || 960;
264
+ } else {
265
+ obj.common.custom[adapter.namespace].maxLength = parseInt(obj.common.custom[adapter.namespace].maxLength, 10);
266
+ }
254
267
 
255
268
  // retention
256
269
  if (obj.common.custom[adapter.namespace].retention || obj.common.custom[adapter.namespace].retention === 0) {
@@ -258,20 +271,77 @@ function reInit(id, realId, formerAliasId, storedIndex, storedType, obj) {
258
271
  } else {
259
272
  obj.common.custom[adapter.namespace].retention = adapter.config.retention;
260
273
  }
274
+ if (obj.common.custom[adapter.namespace].retention === -1) {
275
+ // customRetentionDuration
276
+ if (obj.common.custom[adapter.namespace].customRetentionDuration !== undefined && obj.common.custom[adapter.namespace].customRetentionDuration !== null && obj.common.custom[adapter.namespace].customRetentionDuration !== '') {
277
+ obj.common.custom[adapter.namespace].customRetentionDuration = parseInt(obj.common.custom[adapter.namespace].customRetentionDuration, 10) || 0;
278
+ } else {
279
+ obj.common.custom[adapter.namespace].customRetentionDuration = adapter.config.customRetentionDuration;
280
+ }
281
+ obj.common.custom[adapter.namespace].retention = obj.common.custom[adapter.namespace].customRetentionDuration * 24 * 60 * 60
282
+ }
261
283
 
262
- // debounce
263
- if (obj.common.custom[adapter.namespace].debounce || obj.common.custom[adapter.namespace].debounce === 0) {
264
- obj.common.custom[adapter.namespace].debounce = parseInt(obj.common.custom[adapter.namespace].debounce, 10) || 0;
284
+ // debounceTime and debounce compatibility handling
285
+ if (!obj.common.custom[adapter.namespace].blockTime && obj.common.custom[adapter.namespace].blockTime !== '0' && obj.common.custom[adapter.namespace].blockTime !== 0) {
286
+ if (!obj.common.custom[adapter.namespace].debounce && obj.common.custom[adapter.namespace].debounce !== '0' && obj.common.custom[adapter.namespace].debounce !== 0) {
287
+ obj.common.custom[adapter.namespace].blockTime = parseInt(adapter.config.blockTime, 10) || 0;
288
+ } else {
289
+ obj.common.custom[adapter.namespace].blockTime = parseInt(obj.common.custom[adapter.namespace].debounce, 10) || 0;
290
+ }
291
+ } else {
292
+ obj.common.custom[adapter.namespace].blockTime = parseInt(obj.common.custom[adapter.namespace].blockTime, 10) || 0;
293
+ }
294
+ if (!obj.common.custom[adapter.namespace].debounceTime && obj.common.custom[adapter.namespace].debounceTime !== '0' && obj.common.custom[adapter.namespace].debounceTime !== 0) {
295
+ obj.common.custom[adapter.namespace].debounceTime = parseInt(adapter.config.debounceTime, 10) || 0;
265
296
  } else {
266
- obj.common.custom[adapter.namespace].debounce = adapter.config.debounce;
297
+ obj.common.custom[adapter.namespace].debounceTime = parseInt(obj.common.custom[adapter.namespace].debounceTime, 10) || 0;
267
298
  }
268
299
 
269
300
  // changesOnly
270
301
  obj.common.custom[adapter.namespace].changesOnly = obj.common.custom[adapter.namespace].changesOnly === 'true' || obj.common.custom[adapter.namespace].changesOnly === true;
271
302
 
303
+ // ignoreZero
272
304
  obj.common.custom[adapter.namespace].ignoreZero = obj.common.custom[adapter.namespace].ignoreZero === 'true' || obj.common.custom[adapter.namespace].ignoreZero === true;
273
- obj.common.custom[adapter.namespace].ignoreBelowZero = obj.common.custom[adapter.namespace].ignoreBelowZero === 'true' || obj.common.custom[adapter.namespace].ignoreBelowZero === true;
274
305
 
306
+ // round
307
+ if (obj.common.custom[adapter.namespace].round !== null && obj.common.custom[adapter.namespace].round !== undefined && obj.common.custom[adapter.namespace] !== '') {
308
+ obj.common.custom[adapter.namespace].round = parseInt(obj.common.custom[adapter.namespace], 10);
309
+ if (!isFinite(obj.common.custom[adapter.namespace].round) || obj.common.custom[adapter.namespace].round < 0) {
310
+ obj.common.custom[adapter.namespace].round = adapter.config.round;
311
+ } else {
312
+ obj.common.custom[adapter.namespace].round = Math.pow(10, parseInt(obj.common.custom[adapter.namespace].round, 10));
313
+ }
314
+ } else {
315
+ obj.common.custom[adapter.namespace].round = adapter.config.round;
316
+ }
317
+
318
+ // ignoreAboveNumber
319
+ if (obj.common.custom[adapter.namespace].ignoreAboveNumber !== undefined && obj.common.custom[adapter.namespace].ignoreAboveNumber !== null && obj.common.custom[adapter.namespace].ignoreAboveNumber !== '') {
320
+ obj.common.custom[adapter.namespace].ignoreAboveNumber = parseFloat(obj.common.custom[adapter.namespace].ignoreAboveNumber) || null;
321
+ }
322
+
323
+ // ignoreBelowNumber incl. ignoreBelowZero compatibility handling
324
+ if (obj.common.custom[adapter.namespace].ignoreBelowNumber !== undefined && obj.common.custom[adapter.namespace].ignoreBelowNumber !== null && obj.common.custom[adapter.namespace].ignoreBelowNumber !== '') {
325
+ obj.common.custom[adapter.namespace].ignoreBelowNumber = parseFloat(obj.common.custom[adapter.namespace].ignoreBelowNumber) || null;
326
+ } else if (obj.common.custom[adapter.namespace].ignoreBelowZero === 'true' || obj.common.custom[adapter.namespace].ignoreBelowZero === true) {
327
+ obj.common.custom[adapter.namespace].ignoreBelowNumber = 0;
328
+ }
329
+
330
+ // disableSkippedValueLogging
331
+ if (obj.common.custom[adapter.namespace].disableSkippedValueLogging !== undefined && obj.common.custom[adapter.namespace].disableSkippedValueLogging !== null && obj.common.custom[adapter.namespace].disableSkippedValueLogging !== '') {
332
+ obj.common.custom[adapter.namespace].disableSkippedValueLogging = obj.common.custom[adapter.namespace].disableSkippedValueLogging === 'true' || obj.common.custom[adapter.namespace].disableSkippedValueLogging === true;
333
+ } else {
334
+ obj.common.custom[adapter.namespace].disableSkippedValueLogging = adapter.config.disableSkippedValueLogging;
335
+ }
336
+
337
+ // enableDebugLogs
338
+ if (obj.common.custom[adapter.namespace].enableDebugLogs !== undefined && obj.common.custom[adapter.namespace].enableDebugLogs !== null && obj.common.custom[adapter.namespace].enableDebugLogs !== '') {
339
+ obj.common.custom[adapter.namespace].enableDebugLogs = obj.common.custom[adapter.namespace].enableDebugLogs === 'true' || obj.common.custom[adapter.namespace].enableDebugLogs === true;
340
+ } else {
341
+ obj.common.custom[adapter.namespace].enableDebugLogs = adapter.config.enableDebugLogs;
342
+ }
343
+
344
+ // changesRelogInterval
275
345
  if (obj.common.custom[adapter.namespace].changesRelogInterval || obj.common.custom[adapter.namespace].changesRelogInterval === 0) {
276
346
  obj.common.custom[adapter.namespace].changesRelogInterval = parseInt(obj.common.custom[adapter.namespace].changesRelogInterval, 10) || 0;
277
347
  } else {
@@ -298,29 +368,40 @@ function reInit(id, realId, formerAliasId, storedIndex, storedType, obj) {
298
368
  if (sqlDPs[formerAliasId] &&
299
369
  sqlDPs[formerAliasId][adapter.namespace] &&
300
370
  isEqual(obj.common.custom[adapter.namespace], sqlDPs[formerAliasId][adapter.namespace])) {
301
- return adapter.log.debug(`Object ${id} unchanged. Ignore`);
371
+ return obj.common.custom[adapter.namespace].enableDebugLogs && adapter.log.debug(`Object ${id} unchanged. Ignore`);
302
372
  }
303
373
 
304
374
  // relogTimeout
305
375
  if (sqlDPs[formerAliasId] && sqlDPs[formerAliasId].relogTimeout) {
306
376
  clearTimeout(sqlDPs[formerAliasId].relogTimeout);
377
+ sqlDPs[formerAliasId].relogTimeout = null;
307
378
  }
308
379
 
309
- sqlDPs[id] = obj.common.custom;
310
- sqlDPs[id].realId = realId;
380
+ const writeNull = !(sqlDPs[id] && sqlDPs[id][adapter.namespace]);
381
+ const state = sqlDPs[id] ? sqlDPs[id].state : null;
382
+ const list = sqlDPs[id] ? sqlDPs[id].list : null;
383
+ const inFlight = sqlDPs[id] ? sqlDPs[id].inFlight: null;
384
+ const timeout = sqlDPs[id] ? sqlDPs[id].timeout : null;
385
+ const ts = sqlDPs[id] ? sqlDPs[id].ts : null;
386
+
387
+ sqlDPs[id] = obj.common.custom;
388
+ sqlDPs[id].state = state;
389
+ sqlDPs[id].list = list || [];
390
+ sqlDPs[id].inFlight = inFlight || {};
391
+ sqlDPs[id].timeout = timeout;
392
+ sqlDPs[id].ts = ts;
393
+ sqlDPs[id].realId = realId;
311
394
 
312
395
  // changesRelogInterval
313
396
  if (sqlDPs[id][adapter.namespace].changesRelogInterval > 0) {
314
- sqlDPs[id].relogTimeout && clearTimeout(sqlDPs[id].relogTimeout);
315
397
  sqlDPs[id].relogTimeout = setTimeout(reLogHelper, (sqlDPs[id][adapter.namespace].changesRelogInterval * 500 * Math.random()) + sqlDPs[id][adapter.namespace].changesRelogInterval * 500, id);
316
398
  }
317
399
 
318
- const writeNull = !(sqlDPs[id] && sqlDPs[id][adapter.namespace]);
319
400
  if (writeNull && adapter.config.writeNulls) {
320
401
  writeNulls(id);
321
402
  }
322
403
 
323
- adapter.log.info(`enabled logging of ${id}, Alias=${id !== realId}`);
404
+ adapter.log.info(`enabled logging of ${id}, Alias=${id !== realId}, WriteNulls=${writeNull}`);
324
405
  }
325
406
 
326
407
  function setConnected(isConnected) {
@@ -368,14 +449,26 @@ function connect(callback) {
368
449
  return adapter.log.error(`SQL package "${clients[adapter.config.dbtype].name}" is not installed.`);
369
450
  }
370
451
 
371
- if (adapter.config.dbtype !== 'postgresql') {
372
- params.options = {
373
- encrypt: !!adapter.config.encrypt
374
- };
375
- }
376
-
377
452
  if (adapter.config.dbtype === 'postgresql') {
378
453
  params.database = 'postgres';
454
+ if (adapter.config.encrypt) {
455
+ params.ssl = {
456
+ rejectUnauthorized: !!adapter.config.rejectUnauthorized
457
+ };
458
+ }
459
+ } else if (adapter.config.dbtype === 'mssql') {
460
+ params.options = {
461
+ encrypt: !!adapter.config.encrypt,
462
+ };
463
+ if (adapter.config.encrypt) {
464
+ params.options.trustServerCertificate = !adapter.config.rejectUnauthorized
465
+ }
466
+ } else if (adapter.config.dbtype === 'mysql') {
467
+ if (adapter.config.encrypt) {
468
+ params.ssl = {
469
+ rejectUnauthorized: !!adapter.config.rejectUnauthorized
470
+ };
471
+ }
379
472
  }
380
473
 
381
474
  if (adapter.config.dbtype === 'sqlite') {
@@ -384,10 +477,10 @@ function connect(callback) {
384
477
  // special solution for postgres. Connect first to Db "postgres", create new DB "iobroker" and then connect to "iobroker" DB.
385
478
  if (adapter.config.dbtype === 'postgresql' && !postgresDbCreated) {
386
479
  // connect first to DB postgres and create iobroker DB
387
- adapter.log.info('Postgres connection options: ' + JSON.stringify(params));
480
+ adapter.log.info(`Postgres connection options: ${JSON.stringify(params).replace(params.password, '****')}`);
388
481
  const _client = new SQL[clients[adapter.config.dbtype].name](params);
389
482
  _client.on && _client.on('error', err =>
390
- adapter.log.warn('SQL client error: ' + err));
483
+ adapter.log.warn(`SQL client error: ${err}`));
391
484
 
392
485
  return _client.connect(err => {
393
486
  if (err) {
@@ -403,7 +496,7 @@ function connect(callback) {
403
496
  reconnectTimeout && clearTimeout(reconnectTimeout);
404
497
  reconnectTimeout = setTimeout(() => connect(callback), 100);
405
498
  } else {
406
- _client.execute('CREATE DATABASE ' + adapter.config.dbname + ';', (err /* , rows, fields */) => {
499
+ _client.execute(`CREATE DATABASE ${adapter.config.dbname};`, (err /* , rows, fields */) => {
407
500
  _client.disconnect();
408
501
  if (err && err.code !== '42P04') { // if error not about yet exists
409
502
  postgresDbCreated = false;
@@ -427,10 +520,10 @@ function connect(callback) {
427
520
  try {
428
521
  if (!clients[adapter.config.dbtype].name) {
429
522
  adapter.log.error(`Unknown SQL type selected: "${adapter.config.dbtype}"`);
430
- } else if (!SQL[clients[adapter.config.dbtype].name + 'Pool']) {
523
+ } else if (!SQL[`${clients[adapter.config.dbtype].name}Pool`]) {
431
524
  adapter.log.error(`Selected SQL DB was not installed properly: "${adapter.config.dbtype}". SQLite requires build tools on system. See README.md`);
432
525
  } else {
433
- clientPool = new SQL[clients[adapter.config.dbtype].name + 'Pool'](params);
526
+ clientPool = new SQL[`${clients[adapter.config.dbtype].name}Pool`](params);
434
527
 
435
528
  return clientPool.open(err => {
436
529
  if (err) {
@@ -466,7 +559,7 @@ function connect(callback) {
466
559
  reconnectTimeout && clearTimeout(reconnectTimeout);
467
560
  reconnectTimeout = setTimeout(() => connect(callback), 30000);
468
561
  } else {
469
- adapter.log.info('Connected to ' + adapter.config.dbtype);
562
+ adapter.log.info(`Connected to ${adapter.config.dbtype}`);
470
563
  // read all DB IDs and all FROM ids
471
564
  getAllIds(() =>
472
565
  getAllFroms(callback));
@@ -483,18 +576,18 @@ function getSqlLiteDir(fileName) {
483
576
  } else {
484
577
  // normally /opt/iobroker/node_modules/iobroker.js-controller
485
578
  // but can be /example/ioBroker.js-controller
486
- const tools = require(utils.controllerDir + '/lib/tools');
579
+ const tools = require(`${utils.controllerDir}/lib/tools`);
487
580
  let config = tools.getConfigFileName().replace(/\\/g, '/');
488
581
  const parts = config.split('/');
489
582
  parts.pop();
490
- config = parts.join('/') + '/sqlite';
583
+ config = `${parts.join('/')}/sqlite`;
491
584
 
492
585
  // create sqlite directory
493
586
  if (!fs.existsSync(config)) {
494
587
  fs.mkdirSync(config);
495
588
  }
496
589
 
497
- return config + '/' + fileName;
590
+ return `${config}/${fileName}`;
498
591
  }
499
592
  }
500
593
 
@@ -520,12 +613,16 @@ function testConnection(msg) {
520
613
  Object.keys(postgres)
521
614
  .filter(attr => !SQL[attr])
522
615
  .forEach(attr => SQL[attr] = postgres[attr]);
523
- } else
524
- if (msg.message.config.dbtype === 'mssql' && !SQL.MSSQLClient) {
616
+ } else if (msg.message.config.dbtype === 'mssql' && !SQL.MSSQLClient) {
525
617
  const mssql = require('./lib/mssql-client');
526
618
  Object.keys(mssql)
527
619
  .filter(attr => !SQL[attr])
528
620
  .forEach(attr => SQL[attr] = mssql[attr]);
621
+ } else if (msg.message.config.dbtype === 'mysql' && !SQL.MySQL2Client) {
622
+ const mysql = require('./lib/mysql-client');
623
+ Object.keys(mysql)
624
+ .filter(attr => !SQL[attr])
625
+ .forEach(attr => SQL[attr] = mysql[attr]);
529
626
  }
530
627
 
531
628
  if (msg.message.config.dbtype === 'postgresql') {
@@ -534,10 +631,31 @@ function testConnection(msg) {
534
631
  params = getSqlLiteDir(msg.message.config.fileName);
535
632
  }
536
633
 
634
+ if (msg.message.config.dbtype === 'postgresql') {
635
+ if (msg.message.config.encrypt) {
636
+ params.ssl = {
637
+ rejectUnauthorized: !!msg.message.config.rejectUnauthorized
638
+ };
639
+ }
640
+ } else if (msg.message.config.dbtype === 'mssql') {
641
+ params.options = {
642
+ encrypt: !!msg.message.config.encrypt,
643
+ };
644
+ if (msg.message.config.encrypt) {
645
+ params.options. trustServerCertificate= !msg.message.config.rejectUnauthorized
646
+ }
647
+ } else if (msg.message.config.dbtype === 'mysql') {
648
+ if (msg.message.config.encrypt) {
649
+ params.ssl = {
650
+ rejectUnauthorized: !!msg.message.config.rejectUnauthorized
651
+ };
652
+ }
653
+ }
654
+
537
655
  try {
538
656
  const client = new SQL[clients[msg.message.config.dbtype].name](params);
539
657
  client.on && client.on('error', err =>
540
- adapter.log.warn('SQL client error: ' + err));
658
+ adapter.log.warn(`SQL client error: ${err}`));
541
659
 
542
660
  testConnectTimeout = setTimeout(() => {
543
661
  testConnectTimeout = null;
@@ -586,7 +704,7 @@ function destroyDB(msg) {
586
704
  adapter.sendTo(msg.from, msg.command, {error: null, result: 'deleted'}, msg.callback);
587
705
  // restart adapter
588
706
  setTimeout(() =>
589
- adapter.getForeignObject('system.adapter.' + adapter.namespace, (err, obj) => {
707
+ adapter.getForeignObject(`system.adapter.${adapter.namespace}`, (err, obj) => {
590
708
  if (!err) {
591
709
  adapter.setForeignObject(obj._id, obj);
592
710
  } else {
@@ -616,6 +734,12 @@ function _userQuery(msg, callback) {
616
734
  client.execute(msg.message, (err, rows /* , fields */) => {
617
735
  if (rows && rows.rows) rows = rows.rows;
618
736
  returnClientToPool(client);
737
+ //convert ts for postgresql and ms sqlserver
738
+ if (!err && rows && rows[0] && typeof rows[0].ts === 'string') {
739
+ for (let i = 0; i < rows.length; i++) {
740
+ rows[i].ts = parseInt(rows[i].ts, 10);
741
+ }
742
+ }
619
743
  adapter.sendTo(msg.from, msg.command, {error: err ? err.toString() : null, result: rows}, msg.callback);
620
744
  callback && callback();
621
745
  });
@@ -631,7 +755,7 @@ function _userQuery(msg, callback) {
631
755
  function query(msg) {
632
756
  if (!multiRequests) {
633
757
  if (tasks.length > MAXTASKS) {
634
- const error = 'Cannot queue new requests, because more than '+MAXTASKS;
758
+ const error = `Cannot queue new requests, because more than ${MAXTASKS}`;
635
759
  adapter.log.error(error);
636
760
  adapter.sendTo(msg.from, msg.command, {error}, msg.callback);
637
761
  } else {
@@ -658,7 +782,7 @@ function oneScript(script, cb) {
658
782
  adapter.log.debug(script);
659
783
 
660
784
  client.execute(script, (err /* , rows, fields */) => {
661
- adapter.log.debug('Response: ' + JSON.stringify(err));
785
+ adapter.log.debug(`Response: ${JSON.stringify(err)}`);
662
786
  if (err) {
663
787
  // Database 'iobroker' already exists. Choose a different database name.
664
788
  if (err.number === 1801 ||
@@ -732,6 +856,22 @@ function allScripts(scripts, index, cb) {
732
856
 
733
857
  function finish(callback) {
734
858
 
859
+ function allFinished() {
860
+ if (clientPool) {
861
+ clientPool.close();
862
+ clientPool = null;
863
+ setConnected(false);
864
+ }
865
+ if (typeof finished === 'object') {
866
+ setTimeout(cb => {
867
+ for (let f = 0; f < cb.length; f++) {
868
+ typeof cb[f] === 'function' && cb[f]();
869
+ }
870
+ }, 500, finished);
871
+ finished = true;
872
+ }
873
+ }
874
+
735
875
  function finishId(id) {
736
876
  if (!sqlDPs[id]) {
737
877
  return;
@@ -747,57 +887,37 @@ function finish(callback) {
747
887
  let tmpState = Object.assign({}, sqlDPs[id].state);
748
888
  const state = sqlDPs[id].state ? tmpState : null;
749
889
 
750
- if (sqlDPs[id].skipped) {
890
+ if (sqlDPs[id].skipped && !(sqlDPs[id][adapter.namespace] && sqlDPs[id][adapter.namespace].disableSkippedValueLogging)) {
751
891
  count++;
752
- pushValueIntoDB(id, sqlDPs[id].skipped, () => {
892
+ pushValueIntoDB(id, sqlDPs[id].skipped, false, true,() => {
753
893
  if (!--count) {
754
- if (clientPool) {
755
- clientPool.close();
756
- clientPool = null;
757
- setConnected(false);
758
- }
759
- if (typeof finished === 'object') {
760
- setTimeout(cb => {
761
- for (let f = 0; f < cb.length; f++) {
762
- typeof cb[f] === 'function' && cb[f]();
763
- }
764
- }, 500, finished);
765
- finished = true;
766
- }
894
+ pushValuesIntoDB(id, sqlDPs[id].list, () => {
895
+ allFinished();
896
+ });
767
897
  }
768
898
  });
769
899
  sqlDPs[id].skipped = null;
770
900
  }
771
901
 
772
- const nullValue = {val: null, ts: now, lc: now, q: 0x40, from: 'system.adapter.' + adapter.namespace};
902
+ const nullValue = {val: null, ts: now, lc: now, q: 0x40, from: `system.adapter.${adapter.namespace}`};
773
903
 
774
904
  if (sqlDPs[id][adapter.namespace] && adapter.config.writeNulls) {
775
905
  if (sqlDPs[id][adapter.namespace].changesOnly && state && state.val !== null) {
776
906
  count++;
777
907
  (function (_id, _state, _nullValue) {
778
908
  _state.ts = now;
779
- _state.from = 'system.adapter.' + adapter.namespace;
909
+ _state.from = `system.adapter.${adapter.namespace}`;
780
910
  nullValue.ts += 4;
781
911
  nullValue.lc += 4; // because of MS SQL
782
912
  adapter.log.debug(`Write 1/2 "${_state.val}" _id: ${_id}`);
783
- pushValueIntoDB(_id, _state, () => {
784
- // terminate values with null to indicate adapter stop. timestamp + 1#
913
+ pushValueIntoDB(_id, _state, false, true,() => {
914
+ // terminate values with null to indicate adapter stop. timestamp + 1
785
915
  adapter.log.debug(`Write 2/2 "null" _id: ${_id}`);
786
- pushValueIntoDB(_id, _nullValue, () => {
916
+ pushValueIntoDB(_id, _nullValue, false, true,() => {
787
917
  if (!--count) {
788
- if (clientPool) {
789
- clientPool.close();
790
- clientPool = null;
791
- setConnected(false);
792
- }
793
- if (typeof finished === 'object') {
794
- setTimeout(cb => {
795
- for (let f = 0; f < cb.length; f++) {
796
- typeof cb[f] === 'function' && cb[f]();
797
- }
798
- }, 500, finished);
799
- finished = true;
800
- }
918
+ pushValuesIntoDB(id, sqlDPs[id].list, () => {
919
+ allFinished();
920
+ });
801
921
  }
802
922
  });
803
923
  });
@@ -805,24 +925,12 @@ function finish(callback) {
805
925
  } else {
806
926
  // terminate values with null to indicate adapter stop. timestamp + 1
807
927
  count++;
808
- adapter.log.debug('Write 0 NULL _id: ' + id);
809
- pushValueIntoDB(id, nullValue, () => {
928
+ adapter.log.debug(`Write 0 NULL _id: ${id}`);
929
+ pushValueIntoDB(id, nullValue, false, true,() => {
810
930
  if (!--count) {
811
- setTimeout(() => {
812
- if (clientPool) {
813
- clientPool.close();
814
- clientPool = null;
815
- setConnected(false);
816
- }
817
- if (typeof finished === 'object') {
818
- setTimeout(cb => {
819
- for (let f = 0; f < cb.length; f++) {
820
- typeof cb[f] === 'function' && cb[f]();
821
- }
822
- }, 500, finished);
823
- finished = true;
824
- }
825
- }, 5000);
931
+ pushValuesIntoDB(id, sqlDPs[id].list, () => {
932
+ allFinished();
933
+ });
826
934
  }
827
935
  });
828
936
  }
@@ -837,7 +945,7 @@ function finish(callback) {
837
945
  }
838
946
  } else {
839
947
  subscribeAll = false;
840
- adapter.subscribeForeignStates('*');
948
+ adapter.unsubscribeForeignStates('*');
841
949
  }
842
950
 
843
951
  if (reconnectTimeout) {
@@ -848,6 +956,14 @@ function finish(callback) {
848
956
  clearTimeout(testConnectTimeout);
849
957
  testConnectTimeout = null;
850
958
  }
959
+ if (dpOverviewTimeout) {
960
+ clearTimeout(dpOverviewTimeout);
961
+ dpOverviewTimeout = null;
962
+ }
963
+ if (bufferChecker) {
964
+ clearInterval(bufferChecker);
965
+ bufferChecker = null;
966
+ }
851
967
 
852
968
  let count = 0;
853
969
  if (finished) {
@@ -865,7 +981,9 @@ function finish(callback) {
865
981
  let dpcount = 0;
866
982
  let delay = 0;
867
983
  for (const id in sqlDPs) {
868
- if (!sqlDPs.hasOwnProperty(id)) continue;
984
+ if (!sqlDPs.hasOwnProperty(id)) {
985
+ continue;
986
+ }
869
987
  dpcount++;
870
988
  delay += (dpcount%50 === 0) ? 1000: 0;
871
989
  setTimeout(finishId, delay, id);
@@ -930,7 +1048,7 @@ function processMessage(msg) {
930
1048
  finish(() => {
931
1049
  if (msg.callback) {
932
1050
  adapter.sendTo(msg.from, msg.command, 'stopped', msg.callback);
933
- setTimeout(() => process.exit(0), 200);
1051
+ setTimeout(() => adapter.stop(), 200);
934
1052
  }
935
1053
  });
936
1054
  }
@@ -948,13 +1066,13 @@ function processStartValues(callback) {
948
1066
  lc: state ? now - 4 : now, // 4 is because of MS SQL
949
1067
  ack: true,
950
1068
  q: 0x40,
951
- from: 'system.adapter.' + adapter.namespace
1069
+ from: `system.adapter.${adapter.namespace}`
952
1070
  });
953
1071
 
954
1072
  if (state) {
955
1073
  state.ts = now;
956
1074
  state.lc = now;
957
- state.from = 'system.adapter.' + adapter.namespace;
1075
+ state.from = `system.adapter.${adapter.namespace}`;
958
1076
  pushHistory(task.id, state);
959
1077
  }
960
1078
 
@@ -968,7 +1086,7 @@ function processStartValues(callback) {
968
1086
  lc: task.now || Date.now(),
969
1087
  ack: true,
970
1088
  q: 0x40,
971
- from: 'system.adapter.' + adapter.namespace
1089
+ from: `system.adapter.${adapter.namespace}`
972
1090
  });
973
1091
 
974
1092
  setImmediate(processStartValues);
@@ -1017,52 +1135,97 @@ function pushHistory(id, state, timerRelog) {
1017
1135
  return adapter.log.warn(`state value undefined received for ${id} which is not allowed. Ignoring.`);
1018
1136
  }
1019
1137
 
1020
- adapter.log.debug(`new value received for ${id}, new-value=${state.val}, ts=${state.ts}, relog=${timerRelog}`);
1021
-
1022
- if (state.val !== null && typeof state.val === 'string' && settings.storageType !== 'String') {
1023
- const f = parseFloat(state.val);
1024
- // do not use here === or find a better way to validate if string is a valid float
1025
- if (f == state.val) {
1026
- state.val = f;
1138
+ if (typeof state.val === 'string' && settings.storageType !== 'String') {
1139
+ if (isFinite(state.val)) {
1140
+ state.val = parseFloat(state.val);
1027
1141
  }
1028
1142
  }
1029
1143
 
1030
- if (settings.counter && sqlDPs[id].state) {
1031
- if (sqlDPs[id].type !== types.number) {
1032
- adapter.log.error('Counter cannot have type not "number"!');
1144
+ settings.enableDebugLogs && adapter.log.debug(`new value received for ${id} (storageType ${settings.storageType}), new-value=${state.val}, ts=${state.ts}, relog=${timerRelog}`);
1145
+
1146
+ let ignoreDebonce = false;
1147
+
1148
+ if (!timerRelog) {
1149
+ const valueUnstable = !!sqlDPs[id].timeout;
1150
+ // When a debounce timer runs and the value is the same as the last one, ignore it
1151
+ if (sqlDPs[id].timeout && state.ts !== state.lc) {
1152
+ settings.enableDebugLogs && adapter.log.debug(`value not changed debounce ${id}, value=${state.val}, ts=${state.ts}, debounce timer keeps running`);
1153
+ return;
1154
+ } else if (sqlDPs[id].timeout) { // if value changed, clear timer
1155
+ settings.enableDebugLogs && adapter.log.debug(`value changed during debounce time ${id}, value=${state.val}, ts=${state.ts}, debounce timer restarted`);
1156
+ clearTimeout(sqlDPs[id].timeout);
1157
+ sqlDPs[id].timeout = null;
1158
+ }
1159
+
1160
+ if (!valueUnstable && settings.blockTime && sqlDPs[id].state && (sqlDPs[id].state.ts + settings.blockTime) > state.ts) {
1161
+ settings.enableDebugLogs && adapter.log.debug(`value ignored blockTime ${id}, value=${state.val}, ts=${state.ts}, lastState.ts=${sqlDPs[id].state.ts}, blockTime=${settings.blockTime}`);
1162
+ return;
1163
+ }
1164
+
1165
+ if (settings.ignoreZero && (state.val === undefined || state.val === null || state.val === 0)) {
1166
+ settings.enableDebugLogs && adapter.log.debug(`value ignore because zero or null ${id}, new-value=${state.val}, ts=${state.ts}`);
1167
+ return;
1033
1168
  } else
1034
- // if actual value is less then last seen counter
1035
- if (state.val < sqlDPs[id].state.val) {
1036
- // store both values
1037
- pushValueIntoDB(id, sqlDPs[id].state, true);
1038
- pushValueIntoDB(id, state, true);
1169
+ if (typeof settings.ignoreBelowNumber === 'number' && typeof state.val === 'number' && state.val < settings.ignoreBelowNumber) {
1170
+ settings.enableDebugLogs && adapter.log.debug(`value ignored because below ${settings.ignoreBelowNumber} for ${id}, new-value=${state.val}, ts=${state.ts}`);
1171
+ return;
1172
+ }
1173
+ if (typeof settings.ignoreAboveNumber === 'number' && typeof state.val === 'number' && state.val > settings.ignoreAboveNumber) {
1174
+ settings.enableDebugLogs && adapter.log.debug(`value ignored because above ${settings.ignoreAboveNumber} for ${id}, new-value=${state.val}, ts=${state.ts}`);
1175
+ return;
1039
1176
  }
1040
- }
1041
1177
 
1042
- if (sqlDPs[id].state && settings.changesOnly && !timerRelog) {
1043
- if (settings.changesRelogInterval === 0) {
1044
- if (state.ts !== state.lc) {
1045
- sqlDPs[id].skipped = state; // remember new timestamp
1046
- return adapter.log.debug(`value not changed ${id}, last-value=${sqlDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
1047
- }
1048
- } else if (sqlDPs[id].lastLogTime) {
1049
- if ((state.ts !== state.lc) && (Math.abs(sqlDPs[id].lastLogTime - state.ts) < settings.changesRelogInterval * 1000)) {
1050
- sqlDPs[id].skipped = state; // remember new timestamp
1051
- return adapter.log.debug(`value not changed relog ${id}, last-value=${sqlDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
1178
+ if (sqlDPs[id].state && settings.changesOnly) {
1179
+ if (settings.changesRelogInterval === 0) {
1180
+ if ((sqlDPs[id].state.val !== null || state.val === null) && state.ts !== state.lc) {
1181
+ // remember new timestamp
1182
+ if (!valueUnstable && !settings.disableSkippedValueLogging) {
1183
+ sqlDPs[id].skipped = state;
1184
+ }
1185
+ settings.enableDebugLogs && adapter.log.debug(`value not changed ${id}, last-value=${sqlDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
1186
+ return;
1187
+ }
1188
+ } else if (sqlDPs[id].lastLogTime) {
1189
+ if ((sqlDPs[id].state.val !== null || state.val === null) && (state.ts !== state.lc) && (Math.abs(sqlDPs[id].lastLogTime - state.ts) < settings.changesRelogInterval * 1000)) {
1190
+ // remember new timestamp
1191
+ if (!valueUnstable && !settings.disableSkippedValueLogging) {
1192
+ sqlDPs[id].skipped = state;
1193
+ }
1194
+ settings.enableDebugLogs && adapter.log.debug(`value not changed ${id}, last-value=${sqlDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
1195
+ return;
1196
+ }
1197
+ if (state.ts !== state.lc) {
1198
+ settings.enableDebugLogs && adapter.log.debug(`value-not-changed-relog ${id}, value=${state.val}, lastLogTime=${sqlDPs[id].lastLogTime}, ts=${state.ts}`);
1199
+ ignoreDebonce = true;
1200
+ }
1052
1201
  }
1053
- if (state.ts !== state.lc) {
1054
- adapter.log.debug(`value-changed-relog ${id}, value=${state.val}, lastLogTime=${sqlDPs[id].lastLogTime}, ts=${state.ts}`);
1202
+ if (typeof state.val === 'number') {
1203
+ if (
1204
+ sqlDPs[id].state.val !== null &&
1205
+ settings.changesMinDelta !== 0 &&
1206
+ Math.abs(sqlDPs[id].state.val - state.val) < settings.changesMinDelta
1207
+ ) {
1208
+ if (!valueUnstable && !settings.disableSkippedValueLogging) {
1209
+ sqlDPs[id].skipped = state;
1210
+ }
1211
+ settings.enableDebugLogs && adapter.log.debug(`Min-Delta not reached ${id}, last-value=${sqlDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
1212
+ return;
1213
+ } else if (settings.changesMinDelta !== 0) {
1214
+ settings.enableDebugLogs && adapter.log.debug(`Min-Delta reached ${id}, last-value=${sqlDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
1215
+ }
1216
+ } else {
1217
+ 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}`);
1055
1218
  }
1056
1219
  }
1220
+ }
1057
1221
 
1058
- if (sqlDPs[id].state.val !== null && settings.changesMinDelta !== 0 && typeof state.val === 'number' && Math.abs(sqlDPs[id].state.val - state.val) < settings.changesMinDelta) {
1059
- adapter.log.debug(`Min-Delta not reached ${id}, last-value=${sqlDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
1060
- sqlDPs[id].skipped = state; // remember new timestamp
1061
- return;
1062
- } else if (typeof state.val === 'number') {
1063
- adapter.log.debug(`Min-Delta reached ${id}, last-value=${sqlDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
1064
- } else {
1065
- adapter.log.debug(`Min-Delta ignored because no number ${id}, last-value=${sqlDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
1222
+ if (settings.counter && sqlDPs[id].state) {
1223
+ if (sqlDPs[id].type !== types.number) {
1224
+ adapter.log.error('Counter must have type "number"!');
1225
+ } else if (state.val < sqlDPs[id].state.val) {
1226
+ // if actual value is less then last seen counter, store both values
1227
+ pushValueIntoDB(id, sqlDPs[id].state, true);
1228
+ pushValueIntoDB(id, state, true);
1066
1229
  }
1067
1230
  }
1068
1231
 
@@ -1071,54 +1234,61 @@ function pushHistory(id, state, timerRelog) {
1071
1234
  sqlDPs[id].relogTimeout = null;
1072
1235
  }
1073
1236
 
1074
- if (settings.changesRelogInterval > 0) {
1075
- sqlDPs[id].relogTimeout = setTimeout(reLogHelper, settings.changesRelogInterval * 1000, id);
1076
- }
1077
-
1078
- let ignoreDebonce = false;
1079
1237
  if (timerRelog) {
1238
+ state = Object.assign({}, state);
1080
1239
  state.ts = Date.now();
1081
- state.from = 'system.adapter.' + adapter.namespace;
1082
- adapter.log.debug(`timed-relog ${id}, value=${state.val}, lastLogTime=${sqlDPs[id].lastLogTime}, ts=${state.ts}`);
1240
+ state.from = `system.adapter.${adapter.namespace}`;
1241
+ settings.enableDebugLogs && adapter.log.debug(`timed-relog ${id}, value=${state.val}, lastLogTime=${sqlDPs[id].lastLogTime}, ts=${state.ts}`);
1083
1242
  ignoreDebonce = true;
1084
1243
  } else {
1085
1244
  if (settings.changesOnly && sqlDPs[id].skipped) {
1086
- sqlDPs[id].state = sqlDPs[id].skipped;
1087
- pushHelper(id);
1245
+ settings.enableDebugLogs && adapter.log.debug(`Skipped value logged ${id}, value=${sqlDPs[id].skipped.val}, ts=${sqlDPs[id].skipped.ts}`);
1246
+ pushHelper(id, sqlDPs[id].skipped);
1247
+ sqlDPs[id].skipped = null;
1088
1248
  }
1089
-
1090
1249
  if (sqlDPs[id].state && ((sqlDPs[id].state.val === null && state.val !== null) || (sqlDPs[id].state.val !== null && state.val === null))) {
1091
1250
  ignoreDebonce = true;
1092
1251
  } else if (!sqlDPs[id].state && state.val === null) {
1093
1252
  ignoreDebonce = true;
1094
1253
  }
1095
-
1096
- // only store state if really changed
1097
- sqlDPs[id].state = state;
1098
1254
  }
1099
1255
 
1100
- sqlDPs[id].lastLogTime = state.ts;
1101
- sqlDPs[id].skipped = null;
1102
-
1103
- if (settings.debounce && !ignoreDebonce) {
1104
- // Discard changes in debounce time to store last stable value
1256
+ if (settings.debounceTime && !ignoreDebonce && !timerRelog) {
1257
+ // Discard changes in de-bounce time to store last stable value
1105
1258
  sqlDPs[id].timeout && clearTimeout(sqlDPs[id].timeout);
1106
- sqlDPs[id].timeout = setTimeout(pushHelper, settings.debounce, id, true);
1259
+ sqlDPs[id].timeout = setTimeout((id, state) => {
1260
+ sqlDPs[id].timeout = null;
1261
+ sqlDPs[id].state = state;
1262
+ sqlDPs[id].lastLogTime = state.ts;
1263
+ settings.enableDebugLogs && adapter.log.debug(`Value logged ${id}, value=${sqlDPs[id].state.val}, ts=${sqlDPs[id].state.ts}`);
1264
+ pushHelper(id);
1265
+ if (settings.changesRelogInterval > 0) {
1266
+ sqlDPs[id].relogTimeout = setTimeout(reLogHelper, settings.changesRelogInterval * 1000, id);
1267
+ }
1268
+ }, settings.debounceTime, id, state);
1107
1269
  } else {
1108
- pushHelper(id);
1270
+ if (!timerRelog) {
1271
+ sqlDPs[id].state = state;
1272
+ }
1273
+ sqlDPs[id].lastLogTime = state.ts;
1274
+
1275
+ settings.enableDebugLogs && adapter.log.debug(`Value logged ${id}, value=${sqlDPs[id].state.val}, ts=${sqlDPs[id].state.ts}`);
1276
+ pushHelper(id, state);
1277
+ if (settings.changesRelogInterval > 0) {
1278
+ sqlDPs[id].relogTimeout = setTimeout(reLogHelper, settings.changesRelogInterval * 1000, id);
1279
+ }
1109
1280
  }
1110
1281
  }
1111
1282
  }
1112
1283
 
1113
1284
  function reLogHelper(_id) {
1114
1285
  if (!sqlDPs[_id]) {
1115
- adapter.log.info('non-existing id ' + _id);
1286
+ adapter.log.info(`non-existing id ${_id}`);
1116
1287
  } else {
1117
1288
  sqlDPs[_id].relogTimeout = null;
1118
1289
  if (sqlDPs[_id].skipped) {
1119
- sqlDPs[_id].state = sqlDPs[_id].skipped;
1120
- sqlDPs[_id].state.from = 'system.adapter.' + adapter.namespace;
1121
- sqlDPs[_id].skipped = null;
1290
+ pushHistory(_id, sqlDPs[_id].skipped, true);
1291
+ } else if (sqlDPs[_id].state) {
1122
1292
  pushHistory(_id, sqlDPs[_id].state, true);
1123
1293
  } else {
1124
1294
  adapter.getForeignState(sqlDPs[_id].realId, (err, state) => {
@@ -1136,56 +1306,52 @@ function reLogHelper(_id) {
1136
1306
  }
1137
1307
  }
1138
1308
 
1139
- function pushHelper(_id, timeoutTriggered) {
1140
- if (!sqlDPs[_id] || !sqlDPs[_id].state) {
1309
+ function pushHelper(_id, state) {
1310
+ if (!sqlDPs[_id] || (!sqlDPs[_id].state && !state)) {
1141
1311
  return;
1142
1312
  }
1313
+ if (!state) {
1314
+ state = sqlDPs[_id].state;
1315
+ }
1143
1316
 
1144
1317
  const _settings = sqlDPs[_id][adapter.namespace];
1145
1318
 
1146
1319
  // if it was not deleted in this time
1147
1320
  if (_settings) {
1148
- if (timeoutTriggered) {
1149
- sqlDPs[_id].timeout = null;
1150
- }
1151
-
1152
- if (sqlDPs[_id].state.val !== null && (typeof sqlDPs[_id].state.val === 'object' || typeof sqlDPs[_id].state.val === 'undefined')) {
1153
- sqlDPs[_id].state.val = JSON.stringify(sqlDPs[_id].state.val);
1321
+ if (state.val !== null && (typeof state.val === 'object' || typeof state.val === 'undefined')) {
1322
+ state.val = JSON.stringify(state.val);
1154
1323
  }
1155
1324
 
1156
- if (sqlDPs[_id].state.val !== null && sqlDPs[_id].state.val !== undefined) {
1157
- adapter.log.debug(`Datatype ${_id}: Currently: ${typeof sqlDPs[_id].state.val}, StorageType: ${_settings.storageType}`);
1158
-
1159
- if (typeof sqlDPs[_id].state.val === 'string' && _settings.storageType !== 'String') {
1160
- adapter.log.debug('Do Automatic Datatype conversion for ' + _id);
1161
- const f = parseFloat(sqlDPs[_id].state.val);
1325
+ if (state.val !== null && state.val !== undefined) {
1326
+ _settings.enableDebugLogs && adapter.log.debug(`Datatype ${_id}: Currently: ${typeof state.val}, StorageType: ${_settings.storageType}`);
1162
1327
 
1163
- // do not use here === or find a better way to validate if string is valid float
1164
- if (f == sqlDPs[_id].state.val) {
1165
- sqlDPs[_id].state.val = f;
1166
- } else if (sqlDPs[_id].state.val === 'true') {
1167
- sqlDPs[_id].state.val = true;
1168
- } else if (sqlDPs[_id].state.val === 'false') {
1169
- sqlDPs[_id].state.val = false;
1328
+ if (typeof state.val === 'string' && _settings.storageType !== 'String') {
1329
+ _settings.enableDebugLogs && adapter.log.debug(`Do Automatic Datatype conversion for ${_id}`);
1330
+ if (isFinite(state.val)) {
1331
+ state.val = parseFloat(state.val);
1332
+ } else if (state.val === 'true') {
1333
+ state.val = true;
1334
+ } else if (state.val === 'false') {
1335
+ state.val = false;
1170
1336
  }
1171
1337
  }
1172
1338
 
1173
- if (_settings.storageType === 'String' && typeof sqlDPs[_id].state.val !== 'string') {
1174
- sqlDPs[_id].state.val = sqlDPs[_id].state.val.toString();
1175
- } else if (_settings.storageType === 'Number' && typeof sqlDPs[_id].state.val !== 'number') {
1176
- if (typeof sqlDPs[_id].state.val === 'boolean') {
1177
- sqlDPs[_id].state.val = sqlDPs[_id].state.val ? 1 : 0;
1339
+ if (_settings.storageType === 'String' && typeof state.val !== 'string') {
1340
+ state.val = state.val.toString();
1341
+ } else if (_settings.storageType === 'Number' && typeof state.val !== 'number') {
1342
+ if (typeof state.val === 'boolean') {
1343
+ state.val = state.val ? 1 : 0;
1178
1344
  } else {
1179
- return adapter.log.info('Do not store value "' + sqlDPs[_id].state.val + '" for ' + _id + ' because no number');
1345
+ return adapter.log.info(`Do not store value "${state.val}" for ${_id} because no number`);
1180
1346
  }
1181
- } else if (_settings.storageType === 'Boolean' && typeof sqlDPs[_id].state.val !== 'boolean') {
1182
- sqlDPs[_id].state.val = !!sqlDPs[_id].state.val;
1347
+ } else if (_settings.storageType === 'Boolean' && typeof state.val !== 'boolean') {
1348
+ state.val = !!state.val;
1183
1349
  }
1184
1350
  } else {
1185
- adapter.log.debug('Datatype ' + _id + ': Currently: null');
1351
+ _settings.enableDebugLogs && adapter.log.debug(`Datatype ${_id}: Currently: null`);
1186
1352
  }
1187
1353
 
1188
- pushValueIntoDB(_id, sqlDPs[_id].state);
1354
+ pushValueIntoDB(_id, state);
1189
1355
  }
1190
1356
  }
1191
1357
 
@@ -1202,7 +1368,7 @@ function getAllIds(cb) {
1202
1368
  returnClientToPool(client);
1203
1369
  if (rows && rows.rows) rows = rows.rows;
1204
1370
  if (err) {
1205
- adapter.log.error('Cannot select ' + query + ': ' + err);
1371
+ adapter.log.error(`Cannot select ${query}: ${err}`);
1206
1372
  return cb && cb(err);
1207
1373
  }
1208
1374
 
@@ -1233,7 +1399,7 @@ function getAllFroms(cb) {
1233
1399
  returnClientToPool(client);
1234
1400
  if (rows && rows.rows) rows = rows.rows;
1235
1401
  if (err) {
1236
- adapter.log.error('Cannot select ' + query + ': ' + err);
1402
+ adapter.log.error(`Cannot select ${query}: ${err}`);
1237
1403
  return cb && cb(err);
1238
1404
  }
1239
1405
 
@@ -1258,7 +1424,7 @@ function _checkRetention(query, cb) {
1258
1424
  } else {
1259
1425
  client.execute(query, (err /* , rows, fields */ ) => {
1260
1426
  returnClientToPool(client);
1261
- err && adapter.log.warn('Retention: Cannot delete ' + query + ': ' + err);
1427
+ err && adapter.log.warn(`Retention: Cannot delete ${query}: ${err}`);
1262
1428
  cb && cb();
1263
1429
  });
1264
1430
  }
@@ -1280,7 +1446,7 @@ function checkRetention(id) {
1280
1446
 
1281
1447
  if (!multiRequests) {
1282
1448
  if (tasks.length > MAXTASKS) {
1283
- return adapter.log.error('Cannot queue new requests, because more than '+MAXTASKS);
1449
+ return adapter.log.error(`Cannot queue new requests, because more than ${MAXTASKS}`);
1284
1450
  }
1285
1451
 
1286
1452
  let start = tasks.length === 1;
@@ -1350,64 +1516,70 @@ function processReadTypes() {
1350
1516
  const task = tasksReadType[0];
1351
1517
 
1352
1518
  if (!sqlDPs[task.id] || !sqlDPs[task.id][adapter.namespace]) {
1353
- adapter.log.warn('Ignore type lookup for ' + task.id + ' because not enabled anymore');
1354
- task.cb && task.cb('Ignore type lookup for ' + task.id + ' because not enabled anymore')
1519
+ adapter.log.warn(`Ignore type lookup for ${task.id} because not enabled anymore`);
1520
+ task.cb && task.cb(`Ignore type lookup for ${task.id} because not enabled anymore`)
1355
1521
  task.cb = null;
1356
- tasksReadType.shift();
1357
- return setImmediate(processReadTypes);
1522
+ return setImmediate(() => {
1523
+ tasksReadType.shift();
1524
+ processReadTypes();
1525
+ });
1358
1526
  }
1359
1527
 
1360
- adapter.log.debug('Type set in Def for ' + task.id + ': ' + sqlDPs[task.id][adapter.namespace].storageType);
1528
+ adapter.log.debug(`Type set in Def for ${task.id}: ${sqlDPs[task.id][adapter.namespace].storageType}`);
1361
1529
 
1362
1530
  if (sqlDPs[task.id][adapter.namespace].storageType) {
1363
1531
  sqlDPs[task.id].type = types[sqlDPs[task.id][adapter.namespace].storageType.toLowerCase()];
1364
- adapter.log.debug('Type (from Def) for ' + task.id + ': ' + sqlDPs[task.id].type);
1532
+ adapter.log.debug(`Type (from Def) for ${task.id}: ${sqlDPs[task.id].type}`);
1365
1533
  processVerifyTypes(task);
1366
1534
  } else if (sqlDPs[task.id].dbtype !== undefined) {
1367
1535
  sqlDPs[task.id].type = sqlDPs[task.id].dbtype;
1368
1536
  sqlDPs[task.id][adapter.namespace].storageType = storageTypes[sqlDPs[task.id].type];
1369
- adapter.log.debug('Type (from DB-Type) for ' + task.id + ': ' + sqlDPs[task.id].type);
1537
+ adapter.log.debug(`Type (from DB-Type) for ${task.id}: ${sqlDPs[task.id].type}`);
1370
1538
  processVerifyTypes(task);
1371
1539
  } else {
1372
1540
  adapter.getForeignObject(sqlDPs[task.id].realId, (err, obj) => {
1373
- err && adapter.log.warn('Error while get Object for Def: ' + err);
1541
+ err && adapter.log.warn(`Error while get Object for Def: ${err}`);
1374
1542
 
1375
1543
  if (!sqlDPs[task.id] || !sqlDPs[task.id][adapter.namespace]) {
1376
- adapter.log.warn('Ignore type lookup for ' + task.id + ' because not enabled anymore');
1377
- task.cb && task.cb('Ignore type lookup for ' + task.id + ' because not enabled anymore')
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`)
1378
1546
  task.cb = null;
1379
- tasksReadType.shift();
1380
- return setImmediate(processReadTypes);
1547
+ return setImmediate(() => {
1548
+ tasksReadType.shift();
1549
+ processReadTypes();
1550
+ });
1381
1551
  } else
1382
1552
  // read type from object
1383
1553
  if (obj && obj.common && obj.common.type && types[obj.common.type.toLowerCase()] !== undefined) {
1384
- adapter.log.debug(obj.common.type.toLowerCase() + ' / ' + types[obj.common.type.toLowerCase()] + ' / ' + JSON.stringify(obj.common));
1554
+ adapter.log.debug(`${obj.common.type.toLowerCase()} / ${types[obj.common.type.toLowerCase()]} / ${JSON.stringify(obj.common)}`);
1385
1555
  sqlDPs[task.id].type = types[obj.common.type.toLowerCase()];
1386
1556
  sqlDPs[task.id][adapter.namespace].storageType = storageTypes[sqlDPs[task.id].type];
1387
- adapter.log.debug('Type (from Obj) for ' + task.id + ': ' + sqlDPs[task.id].type);
1557
+ adapter.log.debug(`Type (from Obj) for ${task.id}: ${sqlDPs[task.id].type}`);
1388
1558
  processVerifyTypes(task);
1389
1559
  } else if (sqlDPs[task.id].type === undefined) {
1390
1560
  adapter.getForeignState(sqlDPs[task.id].realId, (err, state) => {
1391
1561
  if (!sqlDPs[task.id] || !sqlDPs[task.id][adapter.namespace]) {
1392
- adapter.log.warn('Ignore type lookup for ' + task.id + ' because not enabled anymore');
1393
- task.cb && task.cb('Ignore type lookup for ' + task.id + ' because not enabled anymore')
1562
+ adapter.log.warn(`Ignore type lookup for ${task.id} because not enabled anymore`);
1563
+ task.cb && task.cb(`Ignore type lookup for ${task.id} because not enabled anymore`)
1394
1564
  task.cb = null;
1395
- tasksReadType.shift();
1396
- return setImmediate(processReadTypes);
1565
+ return setImmediate(() => {
1566
+ tasksReadType.shift();
1567
+ processReadTypes();
1568
+ });
1397
1569
  }
1398
1570
 
1399
1571
  if (err) {
1400
- adapter.log.warn('Store data for ' + task.id + ' as string because no other valid type found');
1572
+ adapter.log.warn(`Store data for ${task.id} as string because no other valid type found`);
1401
1573
  sqlDPs[task.id].type = 1; // string
1402
1574
  } else if (state && state.val !== null && state.val !== undefined && types[typeof state.val] !== undefined) {
1403
1575
  sqlDPs[task.id].type = types[typeof state.val];
1404
1576
  sqlDPs[task.id][adapter.namespace].storageType = storageTypes[sqlDPs[task.id].type];
1405
1577
  } else {
1406
- adapter.log.warn('Store data for ' + task.id + ' as string because no other valid type found (' + (state?(typeof state.val):'state not existing') + ')');
1578
+ adapter.log.warn(`Store data for ${task.id} as string because no other valid type found (${state ? (typeof state.val) : 'state not existing'})`);
1407
1579
  sqlDPs[task.id].type = 1; // string
1408
1580
  }
1409
1581
 
1410
- adapter.log.debug('Type (from State) for ' + task.id + ': ' + sqlDPs[task.id].type);
1582
+ adapter.log.debug(`Type (from State) for ${task.id}: ${sqlDPs[task.id].type}`);
1411
1583
  processVerifyTypes(task);
1412
1584
  });
1413
1585
  } else {
@@ -1439,7 +1611,7 @@ function processVerifyTypes(task) {
1439
1611
  if (err) {
1440
1612
  adapter.log.error(`error updating history config for ${task.id} to pin datatype: ${query}: ${err}`);
1441
1613
  } else {
1442
- adapter.log.info('changed history configuration to pin detected datatype for ' + task.id);
1614
+ adapter.log.info(`changed history configuration to pin detected datatype for ${task.id}`);
1443
1615
  }
1444
1616
  processVerifyTypes(task);
1445
1617
  });
@@ -1447,9 +1619,12 @@ function processVerifyTypes(task) {
1447
1619
  }
1448
1620
 
1449
1621
  task.cb && task.cb();
1622
+ task.cb = null;
1450
1623
 
1451
- tasksReadType.shift();
1452
- setTimeout(processReadTypes, 50);
1624
+ setTimeout(() => {
1625
+ tasksReadType.shift();
1626
+ processReadTypes();
1627
+ }, 50);
1453
1628
  }
1454
1629
 
1455
1630
  function prepareTaskReadDbId(id, state, isCounter, cb) {
@@ -1479,7 +1654,7 @@ function prepareTaskReadDbId(id, state, isCounter, cb) {
1479
1654
  if (sqlDPs[id].isRunning.length === 1) {
1480
1655
  // read or create in DB
1481
1656
  return getId(id, type, (err, _id) => {
1482
- adapter.log.debug('prepareTaskCheckTypeAndDbId getId Result - isRunning length = ' + (sqlDPs[_id].isRunning ? sqlDPs[_id].isRunning.length : 'none'));
1657
+ adapter.log.debug(`prepareTaskCheckTypeAndDbId getId Result - isRunning length = ${sqlDPs[_id].isRunning ? sqlDPs[_id].isRunning.length : 'none'}`);
1483
1658
  if (err) {
1484
1659
  adapter.log.warn(`Cannot get index of "${_id}": ${err}`);
1485
1660
  sqlDPs[_id].isRunning &&
@@ -1506,9 +1681,9 @@ function prepareTaskReadDbId(id, state, isCounter, cb) {
1506
1681
  if (isFromRunning[state.from].length === 1) {
1507
1682
  // read or create in DB
1508
1683
  return getFrom(state.from, (err, from) => {
1509
- adapter.log.debug('prepareTaskCheckTypeAndDbId getFrom ' + from + ' Result - isRunning length = ' + (isFromRunning[from] ? isFromRunning[from].length : 'none'))
1684
+ adapter.log.debug(`prepareTaskCheckTypeAndDbId getFrom ${from} Result - isRunning length = ${isFromRunning[from] ? isFromRunning[from].length : 'none'}`)
1510
1685
  if (err) {
1511
- adapter.log.warn('Cannot get "from" for "' + from + '": ' + err);
1686
+ adapter.log.warn(`Cannot get "from" for "${from}": ${err}`);
1512
1687
  isFromRunning[from] &&
1513
1688
  isFromRunning[from].forEach(f => f.cb && f.cb(`Cannot get "from" for "${from}": ${err}`));
1514
1689
  } else {
@@ -1522,12 +1697,7 @@ function prepareTaskReadDbId(id, state, isCounter, cb) {
1522
1697
  }
1523
1698
  }
1524
1699
 
1525
- // if greater than 2000.01.01 00:00:00
1526
- if (state.ts > 946681200000) {
1527
- state.ts = parseInt(state.ts, 10);
1528
- } else {
1529
- state.ts = parseInt(state.ts, 10) * 1000 + (parseInt(state.ms, 10) || 0);
1530
- }
1700
+ state.ts = parseInt(state.ts, 10);
1531
1701
 
1532
1702
  try {
1533
1703
  if (state.val !== null && (typeof state.val === 'object' || typeof state.val === 'undefined')) {
@@ -1545,7 +1715,7 @@ function prepareTaskReadDbId(id, state, isCounter, cb) {
1545
1715
  function prepareTaskCheckTypeAndDbId(id, state, isCounter, cb) {
1546
1716
  // check if we know about this ID
1547
1717
  if (!sqlDPs[id]) {
1548
- return cb && setImmediate(cb, 'Unknown ID: ' + id);
1718
+ return cb && setImmediate(cb, `Unknown ID: ${id}`);
1549
1719
  }
1550
1720
 
1551
1721
  // Check sql connection
@@ -1553,7 +1723,7 @@ function prepareTaskCheckTypeAndDbId(id, state, isCounter, cb) {
1553
1723
  adapter.log.warn('No Connection to database');
1554
1724
  return cb && setImmediate(cb, 'No Connection to database');
1555
1725
  }
1556
- adapter.log.debug('prepareTaskCheckTypeAndDbId CALLED for ' + id);
1726
+ adapter.log.debug(`prepareTaskCheckTypeAndDbId CALLED for ${id}`);
1557
1727
 
1558
1728
  // read type of value
1559
1729
  if (sqlDPs[id].type !== undefined) {
@@ -1566,25 +1736,25 @@ function prepareTaskCheckTypeAndDbId(id, state, isCounter, cb) {
1566
1736
  }
1567
1737
  }
1568
1738
 
1569
- function pushValueIntoDB(id, state, isCounter, cb) {
1739
+ function pushValueIntoDB(id, state, isCounter, storeInCacheOnly, cb) {
1740
+ if (typeof storeInCacheOnly === 'function') {
1741
+ cb = storeInCacheOnly;
1742
+ storeInCacheOnly = false;
1743
+ }
1744
+
1570
1745
  if (typeof isCounter === 'function') {
1571
1746
  cb = isCounter;
1572
1747
  isCounter = false;
1573
1748
  }
1574
1749
 
1575
- if (sqlDPs[id] && sqlDPs[id][adapter.namespace] && sqlDPs[id][adapter.namespace].ignoreZero && (!state || state.val === undefined || state.val === null || state.val === 0)) {
1576
- adapter.log.debug(`pushValueIntoDB called for ${id} (type: ${sqlDPs[id].type}, ID: ${sqlDPs[id].index}) and state: ${JSON.stringify(state)} and it was ignored because the value zero or null`);
1577
- return cb && cb();
1578
- } else
1579
- if (state && sqlDPs[id] && sqlDPs[id][adapter.namespace] && sqlDPs[id][adapter.namespace].ignoreBelowZero && typeof state.val === 'number' && state.val < 0) {
1580
- adapter.log.debug(`pushValueIntoDB called for ${id} (type: ${sqlDPs[id].type}, ID: ${sqlDPs[id].index}) and state: ${JSON.stringify(state)} and it was ignored because the value is below 0`);
1581
- return cb && cb();
1750
+ if (!sqlDPs[id] || !state) {
1751
+ return cb && cb()
1582
1752
  }
1583
1753
 
1584
1754
  adapter.log.debug(`pushValueIntoDB called for ${id} (type: ${sqlDPs[id].type}, ID: ${sqlDPs[id].index}) and state: ${JSON.stringify(state)}`);
1585
1755
 
1586
1756
  prepareTaskCheckTypeAndDbId(id, state, isCounter, err => {
1587
- adapter.log.debug(`pushValueIntoDB-prepareTaskCheckTypeAndDbId RESULT for ${id} (type: ${sqlDPs[id].type}, ID: ${sqlDPs[id].index}) and state: ${JSON.stringify(state)}`);
1757
+ adapter.log.debug(`pushValueIntoDB-prepareTaskCheckTypeAndDbId RESULT for ${id} (type: ${sqlDPs[id].type}, ID: ${sqlDPs[id].index}) and state: ${JSON.stringify(state)}: ${err}`);
1588
1758
  if (err) {
1589
1759
  return cb && cb(err);
1590
1760
  }
@@ -1599,21 +1769,71 @@ function pushValueIntoDB(id, state, isCounter, cb) {
1599
1769
  // remember last timestamp
1600
1770
  sqlDPs[id].ts = state.ts;
1601
1771
 
1602
- const query = SQLFuncs.insert(adapter.config.dbname, sqlDPs[id].index, state, from[state.from] || 0, isCounter ? 'ts_counter' : dbNames[type]);
1772
+ // if it was not deleted in this time
1773
+ sqlDPs[id].list = sqlDPs[id].list || [];
1603
1774
 
1604
- if (!multiRequests) {
1605
- if (tasks.length > MAXTASKS) {
1606
- const error = 'Cannot queue new requests, because more than ' + MAXTASKS;
1607
- adapter.log.error(error);
1608
- cb && cb(error);
1609
- } else {
1610
- tasks.push({operation: 'insert', query, id, callback: cb});
1611
- tasks.length === 1 && processTasks();
1775
+ sqlDPs[id].list.push({state, from: from[state.from] || 0, db: isCounter ? 'ts_counter' : dbNames[type]});
1776
+
1777
+ const _settings = sqlDPs[id][adapter.namespace];
1778
+ if ((cb || _settings && sqlDPs[id].list.length > _settings.maxLength) && !storeInCacheOnly) {
1779
+ storeCached(id, cb);
1780
+ } else if (cb && storeInCacheOnly) {
1781
+ setImmediate(cb);
1782
+ }
1783
+ });
1784
+ }
1785
+
1786
+ function storeCached(onlyId, cb) {
1787
+ let count = 0;
1788
+ for (const id in sqlDPs) {
1789
+ if (!sqlDPs.hasOwnProperty(id) || (onlyId !== undefined && onlyId !== id)) {
1790
+ continue;
1791
+ }
1792
+
1793
+ const _settings = sqlDPs[id][adapter.namespace];
1794
+ if (_settings && sqlDPs[id].list && sqlDPs[id].list.length) {
1795
+ _settings.enableDebugLogs && adapter.log.debug(`inserting ${sqlDPs[id].list.length} entries from ${id} to DB`);
1796
+ const inFlightId = `${id}_${Date.now()}_${Math.random()}`;
1797
+ sqlDPs[id].inFlight = sqlDPs[id].inFlight || {};
1798
+ sqlDPs[id].inFlight[inFlightId] = sqlDPs[id].list;
1799
+ sqlDPs[id].list = [];
1800
+ count++;
1801
+ pushValuesIntoDB(id, sqlDPs[id].inFlight[inFlightId], err => {
1802
+ delete sqlDPs[id].inFlight[inFlightId];
1803
+ if (!--count && cb) {
1804
+ cb(err);
1805
+ cb = null;
1806
+ }
1807
+ });
1808
+ if (onlyId !== undefined) {
1809
+ break;
1612
1810
  }
1811
+ }
1812
+ }
1813
+ if (!count && cb) {
1814
+ cb();
1815
+ }
1816
+ }
1817
+
1818
+ function pushValuesIntoDB(id, list, cb) {
1819
+ if (!list.length) {
1820
+ return cb && setImmediate(cb);
1821
+ }
1822
+
1823
+ if (!multiRequests) {
1824
+ if (tasks.length > MAXTASKS) {
1825
+ const error = `Cannot queue new requests, because more than ${MAXTASKS}`;
1826
+ adapter.log.error(error);
1827
+ cb && cb(error);
1613
1828
  } else {
1614
- _insertValueIntoDB(query, id, cb);
1829
+ tasks.push({operation: 'insert', index: sqlDPs[id].index, list, id, callback: cb});
1830
+ tasks.length === 1 && processTasks();
1615
1831
  }
1616
- });
1832
+ } else {
1833
+ const query = SQLFuncs.insert(adapter.config.dbname, sqlDPs[id].index, list);
1834
+ _insertValueIntoDB(query, id, cb);
1835
+ }
1836
+
1617
1837
  }
1618
1838
 
1619
1839
  let lockTasks = false;
@@ -1633,8 +1853,23 @@ function processTasks() {
1633
1853
  tasks.length && setTimeout(processTasks, adapter.config.requestInterval);
1634
1854
  });
1635
1855
  } else if (tasks[0].operation === 'insert') {
1636
- _insertValueIntoDB(tasks[0].query, tasks[0].id, () => {
1637
- tasks[0].callback && tasks[0].callback();
1856
+ const callbacks = [];
1857
+ if (tasks[0].callback) {
1858
+ callbacks.push(tasks[0].callback);
1859
+ }
1860
+ for (let i = 1; i < tasks.length; i++) {
1861
+ if (tasks[i].operation === 'insert' && tasks[0].index === tasks[i].index) {
1862
+ tasks[0].list = tasks[0].list.concat(tasks[i].list);
1863
+ if (tasks[i].callback) {
1864
+ callbacks.push(tasks[i].callback);
1865
+ }
1866
+ tasks.splice(i, 1);
1867
+ i--;
1868
+ }
1869
+ }
1870
+ const query = SQLFuncs.insert(adapter.config.dbname, tasks[0].index, tasks[0].list);
1871
+ _insertValueIntoDB(query, tasks[0].id, () => {
1872
+ callbacks.forEach(cb => cb());
1638
1873
  tasks.shift();
1639
1874
  lockTasks = false;
1640
1875
  tasks.length && setTimeout(processTasks, adapter.config.requestInterval);
@@ -1661,7 +1896,7 @@ function processTasks() {
1661
1896
  tasks.length && setTimeout(processTasks, adapter.config.requestInterval);
1662
1897
  });
1663
1898
  } else {
1664
- adapter.log.error('unknown task: ' + tasks[0].operation);
1899
+ adapter.log.error(`unknown task: ${tasks[0].operation}`);
1665
1900
  tasks[0].callback && tasks[0].callback();
1666
1901
  tasks.shift();
1667
1902
  lockTasks = false;
@@ -1687,7 +1922,7 @@ function getId(id, type, cb) {
1687
1922
 
1688
1923
  if (err) {
1689
1924
  returnClientToPool(client);
1690
- adapter.log.error('Cannot select ' + query + ': ' + err);
1925
+ adapter.log.error(`Cannot select ${query}: ${err}`);
1691
1926
  return cb && cb(err, id);
1692
1927
  } else if (!rows.length) {
1693
1928
  if (type !== null && type !== undefined) {
@@ -1699,7 +1934,7 @@ function getId(id, type, cb) {
1699
1934
  client.execute(query, (err /* , rows, fields */) => {
1700
1935
  if (err) {
1701
1936
  returnClientToPool(client);
1702
- adapter.log.error('Cannot insert ' + query + ': ' + err);
1937
+ adapter.log.error(`Cannot insert ${query}: ${err}`);
1703
1938
  cb && cb(err, id);
1704
1939
  } else {
1705
1940
  query = SQLFuncs.getIdSelect(adapter.config.dbname,id);
@@ -1713,7 +1948,7 @@ function getId(id, type, cb) {
1713
1948
  }
1714
1949
 
1715
1950
  if (err) {
1716
- adapter.log.error('Cannot select ' + query + ': ' + err);
1951
+ adapter.log.error(`Cannot select ${query}: ${err}`);
1717
1952
  cb && cb(err, id);
1718
1953
  } else if (rows[0]) {
1719
1954
  sqlDPs[id].index = rows[0].id;
@@ -1721,8 +1956,8 @@ function getId(id, type, cb) {
1721
1956
 
1722
1957
  cb && cb(null, id);
1723
1958
  } else {
1724
- adapter.log.error('No result for select ' + query + ': after insert');
1725
- cb && cb(new Error('No result for select ' + query + ': after insert'), id);
1959
+ adapter.log.error(`No result for select ${query}: after insert`);
1960
+ cb && cb(new Error(`No result for select ${query}: after insert`), id);
1726
1961
  }
1727
1962
  });
1728
1963
  }
@@ -1745,7 +1980,7 @@ function getId(id, type, cb) {
1745
1980
  if (err) {
1746
1981
  adapter.log.error(`error updating history config for ${id} to pin datatype: ${query}: ${err}`);
1747
1982
  } else {
1748
- adapter.log.info('changed history configuration to pin detected datatype for ' + id);
1983
+ adapter.log.info(`changed history configuration to pin detected datatype for ${id}`);
1749
1984
  }
1750
1985
  cb && cb(null, id);
1751
1986
  });
@@ -1775,7 +2010,7 @@ function getFrom(_from, cb) {
1775
2010
  if (rows && rows.rows) rows = rows.rows;
1776
2011
  if (err) {
1777
2012
  returnClientToPool(client);
1778
- adapter.log.error('Cannot select ' + query + ': ' + err);
2013
+ adapter.log.error(`Cannot select ${query}: ${err}`);
1779
2014
  return cb && cb(err, _from);
1780
2015
  }
1781
2016
  if (!rows.length) {
@@ -1785,7 +2020,7 @@ function getFrom(_from, cb) {
1785
2020
  client.execute(query, (err /* , rows, fields */) => {
1786
2021
  if (err) {
1787
2022
  returnClientToPool(client);
1788
- adapter.log.error('Cannot insert ' + query + ': ' + err);
2023
+ adapter.log.error(`Cannot insert ${query}: ${err}`);
1789
2024
  return cb && cb(err, _from);
1790
2025
  }
1791
2026
 
@@ -1796,7 +2031,7 @@ function getFrom(_from, cb) {
1796
2031
 
1797
2032
  if (rows && rows.rows) rows = rows.rows;
1798
2033
  if (err) {
1799
- adapter.log.error('Cannot select ' + query + ': ' + err);
2034
+ adapter.log.error(`Cannot select ${query}: ${err}`);
1800
2035
  return cb && cb(err, _from);
1801
2036
  }
1802
2037
  from[_from] = rows[0].id;
@@ -1821,6 +2056,101 @@ function sortByTs(a, b) {
1821
2056
  return aTs < bTs ? -1 : (aTs > bTs ? 1 : 0);
1822
2057
  }
1823
2058
 
2059
+
2060
+ function getOneCachedData(id, options, cache, addId) {
2061
+ addId = addId || options.addId;
2062
+
2063
+ if (sqlDPs[id]) {
2064
+ let res = [];
2065
+ for (let inFlightId in sqlDPs[id].inFlight) {
2066
+ adapter.log.debug(`getOneCachedData: add ${sqlDPs[id].inFlight[inFlightId].length} inFlight datapoints for ${options.index || options.id}`);
2067
+ res = res.concat(sqlDPs[id].inFlight[inFlightId]);
2068
+ }
2069
+ res = res.concat(sqlDPs[id].list);
2070
+ // todo can be optimized
2071
+ if (res) {
2072
+ let iProblemCount = 0;
2073
+ let vLast = null;
2074
+ for (let i = res.length - 1; i >= 0 ; i--) {
2075
+ if (!res[i] || !res[i].state) {
2076
+ iProblemCount++;
2077
+ continue;
2078
+ }
2079
+ if (options.start && res[i].state.ts < options.start) {
2080
+ // add one before start
2081
+ cache.unshift(Object.assign({}, res[i].state));
2082
+ break;
2083
+ } else if (res[i].state.ts > options.end) {
2084
+ // add one after end
2085
+ vLast = res[i].state;
2086
+ continue;
2087
+ }
2088
+
2089
+ if (vLast) {
2090
+ cache.unshift(Object.assign({}, vLast));
2091
+ vLast = null;
2092
+ }
2093
+
2094
+ cache.unshift(Object.assign({}, res[i].state));
2095
+
2096
+ if ((options.returnNewestEntries && options.count && cache.length >= options.count) && (options.aggregate === 'onchange' || options.aggregate === '' || options.aggregate === 'none')) {
2097
+ break;
2098
+ }
2099
+ }
2100
+
2101
+ iProblemCount && adapter.log.warn(`getOneCachedData: got null states ${iProblemCount} times for ${options.index || options.id}`);
2102
+
2103
+ adapter.log.debug(`getOneCachedData: got ${res.length} datapoints for ${options.index || options.id}`);
2104
+ } else {
2105
+ adapter.log.debug(`getOneCachedData: datapoints for ${options.index || options.id} do not yet exist`);
2106
+ }
2107
+ }
2108
+ }
2109
+
2110
+ function getCachedData(options, callback) {
2111
+ const cache = [];
2112
+
2113
+ if (options.index || options.id) {
2114
+ getOneCachedData(options.index || options.id, options, cache);
2115
+ } else {
2116
+ for (const id in sqlDPs) {
2117
+ if (sqlDPs.hasOwnProperty(id)) {
2118
+ getOneCachedData(id, options, cache, true);
2119
+ }
2120
+ }
2121
+ }
2122
+
2123
+ let earliestTs = null;
2124
+ for (let c = 0; c < cache.length; c++) {
2125
+ if (typeof cache[c].ts === 'string') {
2126
+ cache[c].ts = parseInt(cache[c].ts, 10);
2127
+ }
2128
+
2129
+ if (adapter.common.loglevel === 'debug') {
2130
+ cache[c].date = new Date(parseInt(cache[c].ts, 10));
2131
+ }
2132
+ if (options.ack) {
2133
+ cache[c].ack = !!cache[c].ack;
2134
+ }
2135
+ if (cache[c].val !== null && isFinite(cache[c].val) && options.round) {
2136
+ cache[c].val = Math.round(cache[c].val * options.round) / options.round;
2137
+ }
2138
+ if (sqlDPs[options.index].type === 2) {
2139
+ cache[c].val = !!cache[c].val;
2140
+ }
2141
+ if (options.addId && !cache[c].id && options.id) {
2142
+ cache[c].id = options.index || options.id;
2143
+ }
2144
+ if (cache[c].ts < earliestTs || earliestTs === null) {
2145
+ earliestTs = cache[c].ts;
2146
+ }
2147
+ }
2148
+
2149
+ options.length = cache.length;
2150
+ callback(cache, options.returnNewestEntries && options.count && cache.length >= options.count, !!Object.keys(sqlDPs[options.index || options.id].inFlight).length, earliestTs);
2151
+ }
2152
+
2153
+
1824
2154
  function _getDataFromDB(query, options, callback) {
1825
2155
  adapter.log.debug(query);
1826
2156
 
@@ -1831,42 +2161,31 @@ function _getDataFromDB(query, options, callback) {
1831
2161
  client.execute(query, (err, rows /* , fields */) => {
1832
2162
  returnClientToPool(client);
1833
2163
 
1834
- if (rows && rows.rows) rows = rows.rows;
1835
- // because descending
1836
- if (!err && rows && !options.start && options.count) {
1837
- rows.sort(sortByTs);
1838
- }
2164
+ if (!err && rows && rows.rows) rows = rows.rows;
1839
2165
 
1840
- if (rows) {
1841
- let isNumber = null;
2166
+ if (!err && rows) {
1842
2167
  for (let c = 0; c < rows.length; c++) {
1843
- if (isNumber === null && rows[c].val !== null) {
1844
- isNumber = parseFloat(rows[c].val) == rows[c].val;
1845
- }
1846
2168
  if (typeof rows[c].ts === 'string') {
1847
2169
  rows[c].ts = parseInt(rows[c].ts, 10);
1848
2170
  }
1849
2171
 
1850
- // if less than 2000.01.01 00:00:00
1851
- if (rows[c].ts < 946681200000) {
1852
- rows[c].ts *= 1000;
1853
- }
1854
-
1855
2172
  if (adapter.common.loglevel === 'debug') {
1856
2173
  rows[c].date = new Date(parseInt(rows[c].ts, 10));
1857
2174
  }
1858
2175
  if (options.ack) {
1859
2176
  rows[c].ack = !!rows[c].ack;
1860
2177
  }
1861
- if (isNumber && adapter.config.round && rows[c].val !== null) {
1862
- rows[c].val = Math.round(rows[c].val * adapter.config.round) / adapter.config.round;
2178
+ if (rows[c].val !== null && isFinite(rows[c].val) && options.round) {
2179
+ rows[c].val = Math.round(rows[c].val * options.round) / options.round;
1863
2180
  }
1864
2181
  if (sqlDPs[options.index].type === 2) {
1865
2182
  rows[c].val = !!rows[c].val;
1866
2183
  }
2184
+ if (options.addId && !rows[c].id && options.id) {
2185
+ rows[c].id = options.index || options.id;
2186
+ }
1867
2187
  }
1868
2188
  }
1869
-
1870
2189
  callback && callback(err, rows);
1871
2190
  });
1872
2191
  });
@@ -1877,8 +2196,8 @@ function getDataFromDB(db, options, callback) {
1877
2196
  adapter.log.debug(query);
1878
2197
  if (!multiRequests) {
1879
2198
  if (tasks.length > MAXTASKS) {
1880
- adapter.log.error('Cannot queue new requests, because more than '+MAXTASKS);
1881
- callback && callback('Cannot queue new requests, because more than '+MAXTASKS);
2199
+ adapter.log.error(`Cannot queue new requests, because more than ${MAXTASKS}`);
2200
+ callback && callback(`Cannot queue new requests, because more than ${MAXTASKS}`);
1882
2201
  } else {
1883
2202
  tasks.push({operation: 'select', query, options, callback});
1884
2203
  tasks.length === 1 && processTasks();
@@ -1895,7 +2214,7 @@ function getCounterDataFromDB(options, callback) {
1895
2214
 
1896
2215
  if (!multiRequests) {
1897
2216
  if (tasks.length > MAXTASKS) {
1898
- const error = 'Cannot queue new requests, because more than '+MAXTASKS;
2217
+ const error = `Cannot queue new requests, because more than ${MAXTASKS}`;
1899
2218
  adapter.log.error(error);
1900
2219
  callback && callback(error);
1901
2220
  } else {
@@ -1930,6 +2249,12 @@ function getCounterDiff(msg) {
1930
2249
  function getHistory(msg) {
1931
2250
  const startTime = Date.now();
1932
2251
 
2252
+ if (!msg.message || !msg.message.options) {
2253
+ return adapter.sendTo(msg.from, msg.command, {
2254
+ error: 'Invalid call. No options for getHistory provided'
2255
+ }, msg.callback);
2256
+ }
2257
+
1933
2258
  const options = {
1934
2259
  id: msg.message.id === '*' ? null : msg.message.id,
1935
2260
  start: msg.message.options.start,
@@ -1937,19 +2262,61 @@ function getHistory(msg) {
1937
2262
  step: parseInt(msg.message.options.step, 10) || null,
1938
2263
  count: parseInt(msg.message.options.count, 10) || 500,
1939
2264
  ignoreNull: msg.message.options.ignoreNull,
1940
- aggregate: msg.message.options.aggregate || 'average', // One of: max, min, average, total
1941
- limit: msg.message.options.limit || adapter.config.limit || 2000,
2265
+ aggregate: msg.message.options.aggregate || 'average', // One of: max, min, average, total, none, on-change
2266
+ limit: parseInt(msg.message.options.limit, 10) || parseInt(msg.message.options.count, 10) || adapter.config.limit || 2000,
1942
2267
  from: msg.message.options.from || false,
1943
2268
  q: msg.message.options.q || false,
1944
2269
  ack: msg.message.options.ack || false,
1945
2270
  ms: msg.message.options.ms || false,
1946
2271
  addId: msg.message.options.addId || false,
1947
- sessionId: msg.message.options.sessionId
2272
+ sessionId: msg.message.options.sessionId,
2273
+ returnNewestEntries: msg.message.options.returnNewestEntries || false,
2274
+ percentile: msg.message.options.aggregate === 'percentile' ? parseInt(msg.message.options.percentile, 10) || 50 : null,
2275
+ quantile: msg.message.options.aggregate === 'quantile' ? parseFloat(msg.message.options.quantile) || 0.5 : null,
2276
+ integralUnit: msg.message.options.aggregate === 'integral' ? parseInt(msg.message.options.integralUnit, 10) || 60 : null,
2277
+ integralInterpolation: msg.message.options.aggregate === 'integral' ? msg.message.options.integralInterpolation || 'none' : null,
2278
+ removeBorderValues: msg.message.options.removeBorderValues || false,
2279
+ logId: (msg.message.id ? msg.message.id : 'all') + Date.now() + Math.random()
1948
2280
  };
2281
+
2282
+ if (!options.start && options.count) {
2283
+ options.returnNewestEntries = true;
2284
+ }
2285
+
2286
+ if (msg.message.options.round !== null && msg.message.options.round !== undefined && msg.message.options.round !== '') {
2287
+ msg.message.options.round = parseInt(msg.message.options.round, 10);
2288
+ if (!isFinite(msg.message.options.round) || msg.message.options.round < 0) {
2289
+ options.round = adapter.config.round;
2290
+ } else {
2291
+ options.round = Math.pow(10, parseInt(msg.message.options.round, 10));
2292
+ }
2293
+ } else {
2294
+ options.round = adapter.config.round;
2295
+ }
2296
+
2297
+ adapter.log.debug(`${options.logId} getHistory call: ${JSON.stringify(options)}`);
2298
+
1949
2299
  if (options.id && aliasMap[options.id]) {
1950
2300
  options.id = aliasMap[options.id];
1951
2301
  }
1952
2302
 
2303
+ if (options.aggregate === 'percentile' && options.percentile < 0 || options.percentile > 100) {
2304
+ adapter.log.error(`Invalid percentile value: ${options.percentile}, use 50 as default`);
2305
+ options.percentile = 50;
2306
+ }
2307
+
2308
+ if (options.aggregate === 'quantile' && options.quantile < 0 || options.quantile > 1) {
2309
+ adapter.log.error(`Invalid quantile value: ${options.quantile}, use 0.5 as default`);
2310
+ options.quantile = 0.5;
2311
+ }
2312
+
2313
+ if (options.aggregate === 'integral' && (typeof options.integralUnit !== 'number' || options.integralUnit <= 0)) {
2314
+ adapter.log.error(`Invalid integralUnit value: ${options.integralUnit}, use 60s as default`);
2315
+ options.integralUnit = 60;
2316
+ }
2317
+
2318
+ const debugLog = options.debugLog = !!(sqlDPs[options.id] && sqlDPs[options.id][adapter.namespace] && sqlDPs[options.id][adapter.namespace].enableDebugLogs);
2319
+
1953
2320
  if (options.ignoreNull === 'true') options.ignoreNull = true; // include nulls and replace them with last value
1954
2321
  if (options.ignoreNull === 'false') options.ignoreNull = false; // include nulls
1955
2322
  if (options.ignoreNull === '0') options.ignoreNull = 0; // include nulls and replace them with 0
@@ -1957,8 +2324,8 @@ function getHistory(msg) {
1957
2324
  options.ignoreNull = false;
1958
2325
  }
1959
2326
 
1960
- if (!sqlDPs[options.id]) {
1961
- return commons.sendResponse(adapter, msg, options, [], startTime);
2327
+ if (!sqlDPs[options.id] || !sqlDPs[options.id][adapter.namespace]) {
2328
+ return commons.sendResponse(adapter, msg, options, `Logging not activated for ${options.id}`, startTime);
1962
2329
  }
1963
2330
 
1964
2331
  if (options.start > options.end) {
@@ -1968,18 +2335,18 @@ function getHistory(msg) {
1968
2335
  }
1969
2336
 
1970
2337
  if (!options.start && !options.count) {
1971
- options.start = Date.now() - 5030000; // - 1 year
2338
+ options.start = Date.now() - 86400000; // - 1 day
1972
2339
  }
1973
2340
 
1974
2341
  if (sqlDPs[options.id].type === undefined && sqlDPs[options.id].dbtype !== undefined) {
1975
2342
  if (sqlDPs[options.id][adapter.namespace] && sqlDPs[options.id][adapter.namespace].storageType) {
1976
2343
  if (storageTypes.indexOf(sqlDPs[options.id][adapter.namespace].storageType) === sqlDPs[options.id].dbtype) {
1977
- adapter.log.debug(`For getHistory for id ${options.id}: Type empty, use storageType dbtype ${sqlDPs[options.id].dbtype}`);
2344
+ debugLog && adapter.log.debug(`${options.logId} For getHistory for id ${options.id}: Type empty, use storageType dbtype ${sqlDPs[options.id].dbtype}`);
1978
2345
  sqlDPs[options.id].type = sqlDPs[options.id].dbtype;
1979
2346
  }
1980
2347
  }
1981
2348
  else {
1982
- adapter.log.debug(`For getHistory for id ${options.id}: Type empty, use dbtype ${sqlDPs[options.id].dbtype}`);
2349
+ debugLog && adapter.log.debug(`${options.logId} For getHistory for id ${options.id}: Type empty, use dbtype ${sqlDPs[options.id].dbtype}`);
1983
2350
  sqlDPs[options.id].type = sqlDPs[options.id].dbtype;
1984
2351
  }
1985
2352
  }
@@ -2006,123 +2373,257 @@ function getHistory(msg) {
2006
2373
  options.id = sqlDPs[options.id].index;
2007
2374
  }
2008
2375
 
2376
+ if (options.debugLog) {
2377
+ options.log = adapter.log.debug;
2378
+ }
2379
+
2009
2380
  // if specific id requested
2010
- if (options.id || options.id === 0) {
2011
- getDataFromDB(dbNames[type], options, (err, data) =>
2012
- commons.sendResponse(adapter, msg, options, (err ? err.toString() : null) || data, startTime));
2381
+ if (options.id) {
2382
+ getCachedData(options, (cacheData, isFull, includesInFlightData, earliestTs) => {
2383
+ debugLog && adapter.log.debug(`${options.logId} after getCachedData: length = ${cacheData.length}, isFull=${isFull}`);
2384
+
2385
+ // if all data read
2386
+ if ((isFull && cacheData.length) && (options.aggregate === 'onchange' || options.aggregate === '' || options.aggregate === 'none')) {
2387
+ cacheData = cacheData.sort(sortByTs);
2388
+ if (options.count && cacheData.length > options.count && options.aggregate === 'none') {
2389
+ cacheData = cacheData.slice(-options.count);
2390
+ debugLog && adapter.log.debug(`${options.logId} cut cacheData to ${options.count} values`);
2391
+ }
2392
+ adapter.log.debug(`${options.logId} Send: ${cacheData.length} values in: ${Date.now() - startTime}ms`);
2393
+
2394
+ adapter.sendTo(msg.from, msg.command, {
2395
+ result: cacheData,
2396
+ step: null,
2397
+ error: null
2398
+ }, msg.callback);
2399
+ } else {
2400
+ const origEnd = options.end;
2401
+ if (includesInFlightData) {
2402
+ options.end = earliestTs;
2403
+ }
2404
+ // if not all data read
2405
+ getDataFromDB(dbNames[type], options, (err, data) => {
2406
+ options.end = origEnd;
2407
+ if (options.aggregate === 'none' && options.count && options.returnNewestEntries) {
2408
+ cacheData = cacheData.reverse()
2409
+ data = cacheData.concat(data);
2410
+ } else {
2411
+ data = data.concat(cacheData);
2412
+ }
2413
+ debugLog && adapter.log.debug(`${options.logId} after getDataFromDB: length = ${data.length}`);
2414
+ if (options.count && data.length > options.count && options.aggregate === 'none' && !options.returnNewestEntries) {
2415
+ if (options.start) {
2416
+ for (let i = 0; i < data.length; i++) {
2417
+ if (data[i].ts < options.start) {
2418
+ data.splice(i, 1);
2419
+ i--;
2420
+ } else {
2421
+ break;
2422
+ }
2423
+ }
2424
+ }
2425
+ data = data.slice(0, options.count);
2426
+ options.debugLog && adapter.log.debug(`${options.logId} pre-cut data to ${options.count} oldest values`);
2427
+ }
2428
+
2429
+ data.sort(sortByTs);
2430
+
2431
+ commons.sendResponse(adapter, msg, options, (err ? err.toString() : null) || data, startTime)
2432
+ });
2433
+ }
2434
+ });
2013
2435
  } else {
2014
2436
  // if all IDs requested
2015
2437
  let rows = [];
2016
2438
  let count = 0;
2017
- for (let db = 0; db < dbNames.length; db++) {
2018
- count++;
2019
- getDataFromDB(dbNames[db], options, (err, data) => {
2020
- if (data) {
2021
- rows = rows.concat(data);
2439
+ getCachedData(options, (cacheData, isFull, includesInFlightData, earliestTs) => {
2440
+ if (isFull && cacheData.length) {
2441
+ cacheData.sort(sortByTs);
2442
+ commons.sendResponse(adapter, msg, options, cacheData, startTime);
2443
+ } else {
2444
+ if (includesInFlightData) {
2445
+ options.end = earliestTs;
2022
2446
  }
2023
- if (!--count) {
2024
- rows.sort(sortByTs);
2025
- commons.sendResponse(adapter, msg, options, rows, startTime);
2447
+ for (let db = 0; db < dbNames.length; db++) {
2448
+ count++;
2449
+ getDataFromDB(dbNames[db], options, (err, data) => {
2450
+ if (data) {
2451
+ rows = rows.concat(data);
2452
+ }
2453
+ if (!--count) {
2454
+ rows.sort(sortByTs);
2455
+ commons.sendResponse(adapter, msg, options, rows, startTime);
2456
+ }
2457
+ });
2026
2458
  }
2027
- });
2028
- }
2459
+ }
2460
+ });
2029
2461
  }
2030
2462
  }
2031
2463
 
2032
2464
  function update(id, state, cb) {
2033
- prepareTaskCheckTypeAndDbId(id, state, false, err => {
2034
- if (err) {
2035
- return cb && cb(err);
2465
+ // first try to find the value in not yet saved data
2466
+ let found = false;
2467
+ if (sqlDPs[id]) {
2468
+ const res = sqlDPs[id].list;
2469
+ if (res) {
2470
+ for (let i = res.length - 1; i >= 0; i--) {
2471
+ if (res[i].state.ts === state.ts) {
2472
+ if (state.val !== undefined) {
2473
+ res[i].state.val = state.val;
2474
+ }
2475
+ if (state.q !== undefined && res[i].q !== undefined) {
2476
+ res[i].state.q = state.q;
2477
+ }
2478
+ if (state.from !== undefined && res[i].from !== undefined) {
2479
+ res[i].state.from = state.from;
2480
+ }
2481
+ if (state.ack !== undefined) {
2482
+ res[i].state.ack = state.ack;
2483
+ }
2484
+ found = true;
2485
+ break;
2486
+ }
2487
+ }
2036
2488
  }
2489
+ }
2037
2490
 
2038
- const type = sqlDPs[id].type;
2491
+ if (!found) {
2492
+ prepareTaskCheckTypeAndDbId(id, state, false, err => {
2493
+ if (err) {
2494
+ return cb && cb(err);
2495
+ }
2496
+
2497
+ const type = sqlDPs[id].type;
2039
2498
 
2040
- const query = SQLFuncs.update(adapter.config.dbname, sqlDPs[id].index, state, from[state.from], dbNames[type]);
2499
+ const query = SQLFuncs.update(adapter.config.dbname, sqlDPs[id].index, state, from[state.from], dbNames[type]);
2041
2500
 
2042
- if (!multiRequests) {
2043
- if (tasks.length > MAXTASKS) {
2044
- const error = 'Cannot queue new requests, because more than '+MAXTASKS;
2045
- adapter.log.error(error);
2046
- cb && cb(error);
2501
+ if (!multiRequests) {
2502
+ if (tasks.length > MAXTASKS) {
2503
+ const error = `Cannot queue new requests, because more than ${MAXTASKS}`;
2504
+ adapter.log.error(error);
2505
+ cb && cb(error);
2506
+ } else {
2507
+ tasks.push({operation: 'query', query, id, callback: cb});
2508
+ tasks.length === 1 && processTasks();
2509
+ }
2047
2510
  } else {
2048
- tasks.push({operation: 'query', query, id, callback: cb});
2049
- tasks.length === 1 && processTasks();
2511
+ _executeQuery(query, id, cb);
2050
2512
  }
2051
- } else {
2052
- _executeQuery(query, id, cb);
2053
- }
2054
- });
2513
+ });
2514
+ } else {
2515
+ cb && cb();
2516
+ }
2055
2517
  }
2056
2518
 
2057
2519
  function _delete(id, state, cb) {
2058
- prepareTaskCheckTypeAndDbId(id, state, false, err => {
2059
- if (err) {
2060
- return cb && cb(err);
2520
+ // first try to find the value in not yet saved data
2521
+ let found = false;
2522
+ if (sqlDPs[id]) {
2523
+ const res = sqlDPs[id].list;
2524
+ if (res) {
2525
+ if (!state.ts && !state.start && !state.end) {
2526
+ sqlDPs[id].list = [];
2527
+ } else {
2528
+ for (let i = res.length - 1; i >= 0; i--) {
2529
+ if (state.start && state.end) {
2530
+ if (res[i].state.ts >= state.start && res[i].state.ts <= state.end) {
2531
+ res.splice(i, 1);
2532
+ }
2533
+ } else if (state.start) {
2534
+ if (res[i].state.ts >= state.start) {
2535
+ res.splice(i, 1);
2536
+ }
2537
+ } else if (state.end) {
2538
+ if (res[i].state.ts <= state.end) {
2539
+ res.splice(i, 1);
2540
+ }
2541
+ } else
2542
+ if (res[i].state.ts === state.ts) {
2543
+ res.splice(i, 1);
2544
+ found = true;
2545
+ break;
2546
+ }
2547
+ }
2548
+ }
2061
2549
  }
2550
+ }
2062
2551
 
2063
- const type = sqlDPs[id].type;
2552
+ if (!found) {
2553
+ prepareTaskCheckTypeAndDbId(id, state, false, err => {
2554
+ if (err) {
2555
+ return cb && cb(err);
2556
+ }
2064
2557
 
2065
- let query;
2066
- if (state.start && state.end) {
2067
- query = SQLFuncs.delete(adapter.config.dbname, dbNames[type], sqlDPs[id].index, state.start, state.end);
2068
- } else if (state.ts) {
2069
- query = SQLFuncs.delete(adapter.config.dbname, dbNames[type], sqlDPs[id].index, state.ts);
2070
- } else {
2071
- query = SQLFuncs.delete(adapter.config.dbname, dbNames[type], sqlDPs[id].index);
2072
- }
2558
+ const type = sqlDPs[id].type;
2073
2559
 
2074
- if (!multiRequests) {
2075
- if (tasks.length > MAXTASKS) {
2076
- const error = 'Cannot queue new requests, because more than '+MAXTASKS;
2077
- adapter.log.error(error);
2078
- cb && cb(error);
2560
+ let query;
2561
+ if (state.start && state.end) {
2562
+ query = SQLFuncs.delete(adapter.config.dbname, dbNames[type], sqlDPs[id].index, state.start, state.end);
2563
+ } else if (state.ts) {
2564
+ query = SQLFuncs.delete(adapter.config.dbname, dbNames[type], sqlDPs[id].index, state.ts);
2079
2565
  } else {
2080
- tasks.push({operation: 'query', query, id, callback: cb});
2081
- tasks.length === 1 && processTasks();
2566
+ query = SQLFuncs.delete(adapter.config.dbname, dbNames[type], sqlDPs[id].index);
2082
2567
  }
2083
- } else {
2084
- _executeQuery(query, id, cb);
2085
- }
2086
- });
2568
+
2569
+ if (!multiRequests) {
2570
+ if (tasks.length > MAXTASKS) {
2571
+ const error = `Cannot queue new requests, because more than ${MAXTASKS}`;
2572
+ adapter.log.error(error);
2573
+ cb && cb(error);
2574
+ } else {
2575
+ tasks.push({operation: 'query', query, id, callback: cb});
2576
+ tasks.length === 1 && processTasks();
2577
+ }
2578
+ } else {
2579
+ _executeQuery(query, id, cb);
2580
+ }
2581
+ });
2582
+ } else {
2583
+ cb && cb();
2584
+ }
2087
2585
  }
2088
2586
 
2089
2587
  function updateState(msg) {
2090
2588
  if (!msg.message) {
2091
2589
  adapter.log.error('updateState called with invalid data');
2092
2590
  return adapter.sendTo(msg.from, msg.command, {
2093
- error: 'Invalid call: ' + JSON.stringify(msg)
2591
+ error: `Invalid call: ${JSON.stringify(msg)}`
2094
2592
  }, msg.callback);
2095
2593
  }
2096
2594
  let id;
2097
2595
  if (Array.isArray(msg.message)) {
2098
- adapter.log.debug('updateState ' + msg.message.length + ' items');
2596
+ adapter.log.debug(`updateState ${msg.message.length} items`);
2099
2597
  for (let i = 0; i < msg.message.length; i++) {
2100
2598
  id = aliasMap[msg.message[i].id] ? aliasMap[msg.message[i].id] : msg.message[i].id;
2101
2599
 
2102
2600
  if (msg.message[i].state && typeof msg.message[i].state === 'object') {
2103
2601
  update(id, msg.message[i].state);
2104
2602
  } else {
2105
- adapter.log.warn('Invalid state for ' + JSON.stringify(msg.message[i]));
2603
+ adapter.log.warn(`Invalid state for ${JSON.stringify(msg.message[i])}`);
2106
2604
  }
2107
2605
  }
2108
2606
  } else if (msg.message.state && Array.isArray(msg.message.state)) {
2109
- adapter.log.debug('updateState ' + msg.message.state.length + ' items');
2607
+ adapter.log.debug(`updateState ${msg.message.state.length} items`);
2110
2608
  id = aliasMap[msg.message.id] ? aliasMap[msg.message.id] : msg.message.id;
2111
2609
  for (let j = 0; j < msg.message.state.length; j++) {
2112
2610
  if (msg.message.state[j] && typeof msg.message.state[j] === 'object') {
2113
2611
  update(id, msg.message.state[j]);
2114
2612
  } else {
2115
- adapter.log.warn('Invalid state for ' + JSON.stringify(msg.message.state[j]));
2613
+ adapter.log.warn(`Invalid state for ${JSON.stringify(msg.message.state[j])}`);
2116
2614
  }
2117
2615
  }
2118
2616
  } else if (msg.message.id && msg.message.state && typeof msg.message.state === 'object') {
2119
2617
  adapter.log.debug('updateState 1 item');
2120
2618
  id = aliasMap[msg.message.id] ? aliasMap[msg.message.id] : msg.message.id;
2121
- update(id, msg.message.state);
2619
+ return update(id, msg.message.state, () => adapter.sendTo(msg.from, msg.command, {
2620
+ success: true,
2621
+ connected: !!clientPool
2622
+ }, msg.callback));
2122
2623
  } else {
2123
2624
  adapter.log.error('updateState called with invalid data');
2124
2625
  return adapter.sendTo(msg.from, msg.command, {
2125
- error: 'Invalid call: ' + JSON.stringify(msg)
2626
+ error: `Invalid call: ${JSON.stringify(msg)}`
2126
2627
  }, msg.callback);
2127
2628
  }
2128
2629
 
@@ -2136,12 +2637,12 @@ function deleteState(msg) {
2136
2637
  if (!msg.message) {
2137
2638
  adapter.log.error('deleteState called with invalid data');
2138
2639
  return adapter.sendTo(msg.from, msg.command, {
2139
- error: 'Invalid call: ' + JSON.stringify(msg)
2640
+ error: `Invalid call: ${JSON.stringify(msg)}`
2140
2641
  }, msg.callback);
2141
2642
  }
2142
2643
  let id;
2143
2644
  if (Array.isArray(msg.message)) {
2144
- adapter.log.debug('deleteState ' + msg.message.length + ' items');
2645
+ adapter.log.debug(`deleteState ${msg.message.length} items`);
2145
2646
  for (let i = 0; i < msg.message.length; i++) {
2146
2647
  id = aliasMap[msg.message[i].id] ? aliasMap[msg.message[i].id] : msg.message[i].id;
2147
2648
 
@@ -2170,11 +2671,11 @@ function deleteState(msg) {
2170
2671
  }
2171
2672
  _delete(id, {start: msg.message[i].state.start, end: msg.message[i].state.end || Date.now()});
2172
2673
  } else {
2173
- adapter.log.warn('Invalid state for ' + JSON.stringify(msg.message[i]));
2674
+ adapter.log.warn(`Invalid state for ${JSON.stringify(msg.message[i])}`);
2174
2675
  }
2175
2676
  }
2176
2677
  } else if (msg.message.state && Array.isArray(msg.message.state)) {
2177
- adapter.log.debug('deleteState ' + msg.message.state.length + ' items');
2678
+ adapter.log.debug(`deleteState ${msg.message.state.length} items`);
2178
2679
  id = aliasMap[msg.message.id] ? aliasMap[msg.message.id] : msg.message.id;
2179
2680
 
2180
2681
  for (let j = 0; j < msg.message.state.length; j++) {
@@ -2193,30 +2694,36 @@ function deleteState(msg) {
2193
2694
  } else if (msg.message.state[j] && typeof msg.message.state[j] === 'number') {
2194
2695
  _delete(id, {ts: msg.message.state[j]});
2195
2696
  } else {
2196
- adapter.log.warn('Invalid state for ' + JSON.stringify(msg.message.state[j]));
2697
+ adapter.log.warn(`Invalid state for ${JSON.stringify(msg.message.state[j])}`);
2197
2698
  }
2198
2699
  }
2199
2700
  } else if (msg.message.ts && Array.isArray(msg.message.ts)) {
2200
- adapter.log.debug('deleteState ' + msg.message.ts.length + ' items');
2701
+ adapter.log.debug(`deleteState ${msg.message.ts.length} items`);
2201
2702
  id = aliasMap[msg.message.id] ? aliasMap[msg.message.id] : msg.message.id;
2202
2703
  for (let j = 0; j < msg.message.ts.length; j++) {
2203
2704
  if (msg.message.ts[j] && typeof msg.message.ts[j] === 'number') {
2204
2705
  _delete(id, {ts: msg.message.ts[j]});
2205
2706
  } else {
2206
- adapter.log.warn('Invalid state for ' + JSON.stringify(msg.message.ts[j]));
2707
+ adapter.log.warn(`Invalid state for ${JSON.stringify(msg.message.ts[j])}`);
2207
2708
  }
2208
2709
  }
2209
2710
  } else if (msg.message.id && msg.message.state && typeof msg.message.state === 'object') {
2210
2711
  adapter.log.debug('deleteState 1 item');
2211
2712
  id = aliasMap[msg.message.id] ? aliasMap[msg.message.id] : msg.message.id;
2212
- _delete(id, {ts: msg.message.state.ts});
2713
+ return _delete(id, {ts: msg.message.state.ts}, () => adapter.sendTo(msg.from, msg.command, {
2714
+ success: true,
2715
+ connected: !!clientPool
2716
+ }, msg.callback));
2213
2717
  } else if (msg.message.id && msg.message.ts && typeof msg.message.ts === 'number') {
2214
2718
  adapter.log.debug('deleteState 1 item');
2215
2719
  id = aliasMap[msg.message.id] ? aliasMap[msg.message.id] : msg.message.id;
2216
- _delete(id, {ts: msg.message.ts});
2720
+ return _delete(id, {ts: msg.message.ts}, () => adapter.sendTo(msg.from, msg.command, {
2721
+ success: true,
2722
+ connected: !!clientPool
2723
+ }, msg.callback));
2217
2724
  } else {
2218
2725
  adapter.log.error('deleteState called with invalid data');
2219
- return adapter.sendTo(msg.from, msg.command, {error: 'Invalid call: ' + JSON.stringify(msg)}, msg.callback);
2726
+ return adapter.sendTo(msg.from, msg.command, {error: `Invalid call: ${JSON.stringify(msg)}`}, msg.callback);
2220
2727
  }
2221
2728
 
2222
2729
  adapter.sendTo(msg.from, msg.command, {
@@ -2229,12 +2736,12 @@ function deleteStateAll(msg) {
2229
2736
  if (!msg.message) {
2230
2737
  adapter.log.error('deleteState called with invalid data');
2231
2738
  return adapter.sendTo(msg.from, msg.command, {
2232
- error: 'Invalid call: ' + JSON.stringify(msg)
2739
+ error: `Invalid call: ${JSON.stringify(msg)}`
2233
2740
  }, msg.callback);
2234
2741
  }
2235
2742
  let id;
2236
2743
  if (Array.isArray(msg.message)) {
2237
- adapter.log.debug('deleteStateAll ' + msg.message.length + ' items');
2744
+ adapter.log.debug(`deleteStateAll ${msg.message.length} items`);
2238
2745
  for (let i = 0; i < msg.message.length; i++) {
2239
2746
  id = aliasMap[msg.message[i].id] ? aliasMap[msg.message[i].id] : msg.message[i].id;
2240
2747
  _delete(id, {});
@@ -2242,10 +2749,13 @@ function deleteStateAll(msg) {
2242
2749
  } else if (msg.message.id) {
2243
2750
  adapter.log.debug('deleteStateAll 1 item');
2244
2751
  id = aliasMap[msg.message.id] ? aliasMap[msg.message.id] : msg.message.id;
2245
- _delete(id, {});
2752
+ return _delete(id, {}, () => adapter.sendTo(msg.from, msg.command, {
2753
+ success: true,
2754
+ connected: !!clientPool
2755
+ }, msg.callback));
2246
2756
  } else {
2247
2757
  adapter.log.error('deleteStateAll called with invalid data');
2248
- return adapter.sendTo(msg.from, msg.command, {error: 'Invalid call: ' + JSON.stringify(msg)}, msg.callback);
2758
+ return adapter.sendTo(msg.from, msg.command, {error: `Invalid call: ${JSON.stringify(msg)}`}, msg.callback);
2249
2759
  }
2250
2760
 
2251
2761
  adapter.sendTo(msg.from, msg.command, {
@@ -2258,28 +2768,28 @@ function storeState(msg) {
2258
2768
  if (!msg.message) {
2259
2769
  adapter.log.error('storeState called with invalid data');
2260
2770
  return adapter.sendTo(msg.from, msg.command, {
2261
- error: 'Invalid call: ' + JSON.stringify(msg)
2771
+ error: `Invalid call: ${JSON.stringify(msg)}`
2262
2772
  }, msg.callback);
2263
2773
  }
2264
2774
 
2265
- let pushFunc = pushValueIntoDB;
2775
+ let pushFunc = pushHelper;
2266
2776
  if (msg.message.rules) {
2267
- pushFunc = pushHistory;
2777
+ pushFunc = pushValueIntoDB;
2268
2778
  }
2269
2779
 
2270
2780
  let id;
2271
2781
  if (Array.isArray(msg.message)) {
2272
- adapter.log.debug('storeState ' + msg.message.length + ' items');
2782
+ adapter.log.debug(`storeState ${msg.message.length} items`);
2273
2783
  for (let i = 0; i < msg.message.length; i++) {
2274
2784
  id = aliasMap[msg.message[i].id] ? aliasMap[msg.message[i].id] : msg.message[i].id;
2275
2785
  if (msg.message[i].state && typeof msg.message[i].state === 'object') {
2276
2786
  pushFunc(id, msg.message[i].state);
2277
2787
  } else {
2278
- adapter.log.warn('Invalid state for ' + JSON.stringify(msg.message[i]));
2788
+ adapter.log.warn(`Invalid state for ${JSON.stringify(msg.message[i])}`);
2279
2789
  }
2280
2790
  }
2281
2791
  } else if (msg.message.state && Array.isArray(msg.message.state)) {
2282
- adapter.log.debug('storeState ' + msg.message.state.length + ' items');
2792
+ adapter.log.debug(`storeState ${msg.message.state.length} items`);
2283
2793
  id = aliasMap[msg.message.id] ? aliasMap[msg.message.id] : msg.message.id;
2284
2794
  for (let j = 0; j < msg.message.state.length; j++) {
2285
2795
  if (msg.message.state[j] && typeof msg.message.state[j] === 'object') {
@@ -2331,7 +2841,7 @@ function getDpOverview(msg) {
2331
2841
  return;
2332
2842
  }
2333
2843
 
2334
- adapter.log.info('Query result ' + JSON.stringify(rows));
2844
+ adapter.log.info(`Query result ${JSON.stringify(rows)}`);
2335
2845
 
2336
2846
  if (rows.length) {
2337
2847
  for (let r = 0; r < rows.length; r++) {
@@ -2358,7 +2868,7 @@ function getDpOverview(msg) {
2358
2868
  }
2359
2869
  }
2360
2870
 
2361
- adapter.log.info('initialisation result: ' + JSON.stringify(result));
2871
+ adapter.log.info(`initialisation result: ${JSON.stringify(result)}`);
2362
2872
  getFirstTsForIds(client, 0, result, msg);
2363
2873
  }
2364
2874
  });
@@ -2399,7 +2909,10 @@ function getFirstTsForIds(dbClient, typeId, resultData, msg) {
2399
2909
  }
2400
2910
 
2401
2911
  adapter.log.info(`enhanced result (${typeId}): ${JSON.stringify(resultData)}`);
2402
- setTimeout(getFirstTsForIds, 5000, dbClient, typeId + 1, resultData, msg);
2912
+ dpOverviewTimeout = setTimeout(() => {
2913
+ dpOverviewTimeout = null;
2914
+ getFirstTsForIds();
2915
+ }, 5000, dbClient, typeId + 1, resultData, msg);
2403
2916
  });
2404
2917
  }
2405
2918
  } else {
@@ -2428,7 +2941,7 @@ function getFirstTsForIds(dbClient, typeId, resultData, msg) {
2428
2941
  }
2429
2942
  }
2430
2943
  }
2431
- adapter.log.info('Result: ' + JSON.stringify(result));
2944
+ adapter.log.info(`Result: ${JSON.stringify(result)}`);
2432
2945
  adapter.sendTo(msg.from, msg.command, {
2433
2946
  success: true,
2434
2947
  result: result
@@ -2459,7 +2972,7 @@ function enableHistory(msg) {
2459
2972
 
2460
2973
  adapter.extendForeignObject(msg.message.id, obj, err => {
2461
2974
  if (err) {
2462
- adapter.log.error('enableHistory: ' + err);
2975
+ adapter.log.error(`enableHistory: ${err}`);
2463
2976
  adapter.sendTo(msg.from, msg.command, {
2464
2977
  error: err
2465
2978
  }, msg.callback);
@@ -2488,7 +3001,7 @@ function disableHistory(msg) {
2488
3001
 
2489
3002
  adapter.extendForeignObject(msg.message.id, obj, err => {
2490
3003
  if (err) {
2491
- adapter.log.error('disableHistory: ' + err);
3004
+ adapter.log.error(`disableHistory: ${err}`);
2492
3005
  adapter.sendTo(msg.from, msg.command, {
2493
3006
  error: err
2494
3007
  }, msg.callback);
@@ -2504,7 +3017,7 @@ function disableHistory(msg) {
2504
3017
  function getEnabledDPs(msg) {
2505
3018
  const data = {};
2506
3019
  for (const id in sqlDPs) {
2507
- if (sqlDPs.hasOwnProperty(id) && sqlDPs[id] && sqlDPs[id][adapter.namespace]) {
3020
+ if (sqlDPs.hasOwnProperty(id) && sqlDPs[id] && sqlDPs[id][adapter.namespace] && sqlDPs[id][adapter.namespace].enabled) {
2508
3021
  data[sqlDPs[id].realId] = sqlDPs[id][adapter.namespace];
2509
3022
  }
2510
3023
  }
@@ -2536,6 +3049,9 @@ function main() {
2536
3049
  }
2537
3050
 
2538
3051
  adapter.config.retention = parseInt(adapter.config.retention, 10) || 0;
3052
+ if (adapter.config.retention === -1 ) { // Custom timeframe
3053
+ adapter.config.retention = (parseInt(adapter.config.customRetentionDuration, 10) || 0) * 24 * 60 * 60;
3054
+ }
2539
3055
  adapter.config.debounce = parseInt(adapter.config.debounce, 10) || 0;
2540
3056
  adapter.config.requestInterval = (adapter.config.requestInterval === undefined || adapter.config.requestInterval === null || adapter.config.requestInterval === '') ? 0 : parseInt(adapter.config.requestInterval, 10) || 0;
2541
3057
 
@@ -2567,6 +3083,22 @@ function main() {
2567
3083
  adapter.config.changesMinDelta = 0;
2568
3084
  }
2569
3085
 
3086
+ if (adapter.config.blockTime !== null && adapter.config.blockTime !== undefined) {
3087
+ adapter.config.blockTime = parseInt(adapter.config.blockTime, 10) || 0;
3088
+ } else {
3089
+ if (adapter.config.debounce !== null && adapter.config.debounce !== undefined) {
3090
+ adapter.config.debounce = parseInt(adapter.config.debounce, 10) || 0;
3091
+ } else {
3092
+ adapter.config.blockTime = 0;
3093
+ }
3094
+ }
3095
+
3096
+ if (adapter.config.debounceTime !== null && adapter.config.debounceTime !== undefined) {
3097
+ adapter.config.debounceTime = parseInt(adapter.config.debounceTime, 10) || 0;
3098
+ } else {
3099
+ adapter.config.debounceTime = 0;
3100
+ }
3101
+
2570
3102
  multiRequests = clients[adapter.config.dbtype].multiRequests;
2571
3103
  if (!multiRequests) {
2572
3104
  adapter.config.writeNulls = false;
@@ -2574,29 +3106,41 @@ function main() {
2574
3106
 
2575
3107
  adapter.config.port = parseInt(adapter.config.port, 10) || 0;
2576
3108
 
2577
- if (adapter.config.round !== null && adapter.config.round !== undefined) {
2578
- adapter.config.round = Math.pow(10, parseInt(adapter.config.round, 10));
3109
+ if (adapter.config.round !== null && adapter.config.round !== undefined && adapter.config.round !== '') {
3110
+ adapter.config.round = parseInt(adapter.config.round, 10);
3111
+ if (!isFinite(adapter.config.round) || adapter.config.round < 0) {
3112
+ adapter.config.round = null;
3113
+ adapter.log.info(`Invalid round value: ${adapter.config.round} - ignore, do not round values`);
3114
+ } else {
3115
+ adapter.config.round = Math.pow(10, parseInt(adapter.config.round, 10));
3116
+ }
2579
3117
  } else {
2580
3118
  adapter.config.round = null;
2581
3119
  }
2582
3120
 
2583
3121
  if (adapter.config.dbtype === 'postgresql' && !SQL.PostgreSQLClient) {
2584
- const postgres = require(__dirname + '/lib/postgresql-client');
3122
+ const postgres = require(`${__dirname}/lib/postgresql-client`);
2585
3123
  for (const attr in postgres) {
2586
3124
  if (postgres.hasOwnProperty(attr) && !SQL[attr]) {
2587
3125
  SQL[attr] = postgres[attr];
2588
3126
  }
2589
3127
  }
2590
- } else
2591
- if (adapter.config.dbtype === 'mssql' && !SQL.MSSQLClient) {
2592
- const mssql = require(__dirname + '/lib/mssql-client');
3128
+ } else if (adapter.config.dbtype === 'mssql' && !SQL.MSSQLClient) {
3129
+ const mssql = require(`${__dirname}/lib/mssql-client`);
2593
3130
  for (const attr_ in mssql) {
2594
3131
  if (mssql.hasOwnProperty(attr_) && !SQL[attr_]) {
2595
3132
  SQL[attr_] = mssql[attr_];
2596
3133
  }
2597
3134
  }
3135
+ } else if (adapter.config.dbtype === 'mysql' && !SQL.MySQL2Client) {
3136
+ const mysql = require(`${__dirname}/lib/mysql-client`);
3137
+ for (const attr_ in mysql) {
3138
+ if (mysql.hasOwnProperty(attr_) && !SQL[attr_]) {
3139
+ SQL[attr_] = mysql[attr_];
3140
+ }
3141
+ }
2598
3142
  }
2599
- SQLFuncs = require(__dirname + '/lib/' + adapter.config.dbtype);
3143
+ SQLFuncs = require(`${__dirname}/lib/${adapter.config.dbtype}`);
2600
3144
 
2601
3145
  if (adapter.config.dbtype === 'sqlite' || adapter.config.host) {
2602
3146
  connect(() => {
@@ -2637,18 +3181,43 @@ function main() {
2637
3181
  count++;
2638
3182
  adapter.log.info(`enabled logging of ${id}, Alias=${id !== realId}, ${count} points now activated`);
2639
3183
 
3184
+ // maxLength
3185
+ if (!sqlDPs[id][adapter.namespace].maxLength && sqlDPs[id][adapter.namespace].maxLength !== '0' && sqlDPs[id][adapter.namespace].maxLength !== 0) {
3186
+ sqlDPs[id][adapter.namespace].maxLength = parseInt(adapter.config.maxLength, 10) || 960;
3187
+ } else {
3188
+ sqlDPs[id][adapter.namespace].maxLength = parseInt(sqlDPs[id][adapter.namespace].maxLength, 10);
3189
+ }
3190
+
2640
3191
  // retention
2641
3192
  if (sqlDPs[id][adapter.namespace].retention !== undefined && sqlDPs[id][adapter.namespace].retention !== null && sqlDPs[id][adapter.namespace].retention !== '') {
2642
3193
  sqlDPs[id][adapter.namespace].retention = parseInt(sqlDPs[id][adapter.namespace].retention, 10) || 0;
2643
3194
  } else {
2644
3195
  sqlDPs[id][adapter.namespace].retention = adapter.config.retention;
2645
3196
  }
3197
+ if (sqlDPs[id][adapter.namespace].retention === -1) {
3198
+ // customRetentionDuration
3199
+ if (sqlDPs[id][adapter.namespace].customRetentionDuration !== undefined && sqlDPs[id][adapter.namespace].customRetentionDuration !== null && sqlDPs[id][adapter.namespace].customRetentionDuration !== '') {
3200
+ sqlDPs[id][adapter.namespace].customRetentionDuration = parseInt(sqlDPs[id][adapter.namespace].customRetentionDuration, 10) || 0;
3201
+ } else {
3202
+ sqlDPs[id][adapter.namespace].customRetentionDuration = adapter.config.customRetentionDuration;
3203
+ }
3204
+ sqlDPs[id][adapter.namespace].retention = sqlDPs[id][adapter.namespace].customRetentionDuration * 24 * 60 * 60
3205
+ }
2646
3206
 
2647
- // debounce
2648
- if (sqlDPs[id][adapter.namespace].debounce !== undefined && sqlDPs[id][adapter.namespace].debounce !== null && sqlDPs[id][adapter.namespace].debounce !== '') {
2649
- sqlDPs[id][adapter.namespace].debounce = parseInt(sqlDPs[id][adapter.namespace].debounce, 10) || 0;
3207
+ // debounceTime and debounce compatibility handling
3208
+ if (!sqlDPs[id][adapter.namespace].blockTime && sqlDPs[id][adapter.namespace].blockTime !== '0' && sqlDPs[id][adapter.namespace].blockTime !== 0) {
3209
+ if (!sqlDPs[id][adapter.namespace].debounce && sqlDPs[id][adapter.namespace].debounce !== '0' && sqlDPs[id][adapter.namespace].debounce !== 0) {
3210
+ sqlDPs[id][adapter.namespace].blockTime = parseInt(adapter.config.blockTime, 10) || 0;
3211
+ } else {
3212
+ sqlDPs[id][adapter.namespace].blockTime = parseInt(sqlDPs[id][adapter.namespace].debounce, 10) || 0;
3213
+ }
3214
+ } else {
3215
+ sqlDPs[id][adapter.namespace].blockTime = parseInt(sqlDPs[id][adapter.namespace].blockTime, 10) || 0;
3216
+ }
3217
+ if (!sqlDPs[id][adapter.namespace].debounceTime && sqlDPs[id][adapter.namespace].debounceTime !== '0' && sqlDPs[id][adapter.namespace].debounceTime !== 0) {
3218
+ sqlDPs[id][adapter.namespace].debounceTime = parseInt(adapter.config.debounceTime, 10) || 0;
2650
3219
  } else {
2651
- sqlDPs[id][adapter.namespace].debounce = adapter.config.debounce;
3220
+ sqlDPs[id][adapter.namespace].debounceTime = parseInt(sqlDPs[id][adapter.namespace].debounceTime, 10) || 0;
2652
3221
  }
2653
3222
 
2654
3223
  // changesOnly
@@ -2657,8 +3226,43 @@ function main() {
2657
3226
  // ignoreZero
2658
3227
  sqlDPs[id][adapter.namespace].ignoreZero = sqlDPs[id][adapter.namespace].ignoreZero === 'true' || sqlDPs[id][adapter.namespace].ignoreZero === true;
2659
3228
 
2660
- // ignoreBelowZero
2661
- sqlDPs[id][adapter.namespace].ignoreBelowZero = sqlDPs[id][adapter.namespace].ignoreBelowZero === 'true' || sqlDPs[id][adapter.namespace].ignoreBelowZero === true;
3229
+ // round
3230
+ if (sqlDPs[id][adapter.namespace].round !== null && sqlDPs[id][adapter.namespace].round !== undefined && sqlDPs[id][adapter.namespace] !== '') {
3231
+ sqlDPs[id][adapter.namespace].round = parseInt(sqlDPs[id][adapter.namespace], 10);
3232
+ if (!isFinite(sqlDPs[id][adapter.namespace].round) || sqlDPs[id][adapter.namespace].round < 0) {
3233
+ sqlDPs[id][adapter.namespace].round = adapter.config.round;
3234
+ } else {
3235
+ sqlDPs[id][adapter.namespace].round = Math.pow(10, parseInt(sqlDPs[id][adapter.namespace].round, 10));
3236
+ }
3237
+ } else {
3238
+ sqlDPs[id][adapter.namespace].round = adapter.config.round;
3239
+ }
3240
+
3241
+ // ignoreAboveNumber
3242
+ if (sqlDPs[id][adapter.namespace].ignoreAboveNumber !== undefined && sqlDPs[id][adapter.namespace].ignoreAboveNumber !== null && sqlDPs[id][adapter.namespace].ignoreAboveNumber !== '') {
3243
+ sqlDPs[id][adapter.namespace].ignoreAboveNumber = parseFloat(sqlDPs[id][adapter.namespace].ignoreAboveNumber) || null;
3244
+ }
3245
+
3246
+ // ignoreBelowNumber and ignoreBelowZero compatibility handling
3247
+ if (sqlDPs[id][adapter.namespace].ignoreBelowNumber !== undefined && sqlDPs[id][adapter.namespace].ignoreBelowNumber !== null && sqlDPs[id][adapter.namespace].ignoreBelowNumber !== '') {
3248
+ sqlDPs[id][adapter.namespace].ignoreBelowNumber = parseFloat(sqlDPs[id][adapter.namespace].ignoreBelowNumber) || null;
3249
+ } else if (sqlDPs[id][adapter.namespace].ignoreBelowZero === 'true' || sqlDPs[id][adapter.namespace].ignoreBelowZero === true) {
3250
+ sqlDPs[id][adapter.namespace].ignoreBelowNumber = 0;
3251
+ }
3252
+
3253
+ // disableSkippedValueLogging
3254
+ if (sqlDPs[id][adapter.namespace].disableSkippedValueLogging !== undefined && sqlDPs[id][adapter.namespace].disableSkippedValueLogging !== null && sqlDPs[id][adapter.namespace].disableSkippedValueLogging !== '') {
3255
+ sqlDPs[id][adapter.namespace].disableSkippedValueLogging = sqlDPs[id][adapter.namespace].disableSkippedValueLogging === 'true' || sqlDPs[id][adapter.namespace].disableSkippedValueLogging === true;
3256
+ } else {
3257
+ sqlDPs[id][adapter.namespace].disableSkippedValueLogging = adapter.config.disableSkippedValueLogging;
3258
+ }
3259
+
3260
+ // enableDebugLogs
3261
+ if (sqlDPs[id][adapter.namespace].enableDebugLogs !== undefined && sqlDPs[id][adapter.namespace].enableDebugLogs !== null && sqlDPs[id][adapter.namespace].enableDebugLogs !== '') {
3262
+ sqlDPs[id][adapter.namespace].enableDebugLogs = sqlDPs[id][adapter.namespace].enableDebugLogs === 'true' || sqlDPs[id][adapter.namespace].enableDebugLogs === true;
3263
+ } else {
3264
+ sqlDPs[id][adapter.namespace].enableDebugLogs = adapter.config.enableDebugLogs;
3265
+ }
2662
3266
 
2663
3267
  // changesRelogInterval
2664
3268
  if (sqlDPs[id][adapter.namespace].changesRelogInterval !== undefined && sqlDPs[id][adapter.namespace].changesRelogInterval !== null && sqlDPs[id][adapter.namespace].changesRelogInterval !== '') {
@@ -2669,7 +3273,7 @@ function main() {
2669
3273
 
2670
3274
  // changesMinDelta
2671
3275
  if (sqlDPs[id][adapter.namespace].changesMinDelta !== undefined && sqlDPs[id][adapter.namespace].changesMinDelta !== null && sqlDPs[id][adapter.namespace].changesMinDelta !== '') {
2672
- sqlDPs[id][adapter.namespace].changesMinDelta = parseFloat(sqlDPs[id][adapter.namespace].changesMinDelta) || 0;
3276
+ sqlDPs[id][adapter.namespace].changesMinDelta = parseFloat(sqlDPs[id][adapter.namespace].changesMinDelta.toString().replace(/,/g, '.')) || 0;
2673
3277
  } else {
2674
3278
  sqlDPs[id][adapter.namespace].changesMinDelta = adapter.config.changesMinDelta;
2675
3279
  }
@@ -2691,6 +3295,8 @@ function main() {
2691
3295
  }
2692
3296
 
2693
3297
  sqlDPs[id].realId = realId;
3298
+ sqlDPs[id].list = sqlDPs[id].list || [];
3299
+ sqlDPs[id].inFlight = sqlDPs[id].inFlight || {};
2694
3300
  }
2695
3301
  }
2696
3302
  }
@@ -2715,19 +3321,14 @@ function main() {
2715
3321
  adapter.log.debug('Initialization done');
2716
3322
  setConnected(true);
2717
3323
  processStartValues();
3324
+
3325
+ // store all buffered data every 10 minutes to not lost the data
3326
+ bufferChecker = setInterval(() => storeCached(), 10 * 60000);
2718
3327
  });
2719
3328
  });
2720
3329
  }
2721
3330
  }
2722
3331
 
2723
- // close connection to DB
2724
- process.on('SIGINT', () => finish());
2725
-
2726
- // close connection to DB
2727
- process.on('SIGTERM', () => finish());
2728
-
2729
- process.on('uncaughtException', err => adapter.log.warn('Exception: ' + err));
2730
-
2731
3332
  // If started as allInOne/compact mode => return function to create instance
2732
3333
  if (module.parent) {
2733
3334
  module.exports = startAdapter;