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