iobroker.sql 2.0.2 → 2.1.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/README.md +17 -2
- package/admin/i18n/de/translations.json +3 -3
- package/admin/i18n/en/translations.json +1 -1
- package/admin/i18n/zh-cn/translations.json +3 -3
- package/admin/words.js +10 -10
- package/io-package.json +14 -14
- package/lib/aggregate.js +5 -0
- package/lib/mssql.js +2 -0
- package/main.js +241 -115
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -278,7 +278,7 @@ Possible options:
|
|
|
278
278
|
- **ignoreNull** - if null values should be included (false), replaced by last not null value (true) or replaced with 0 (0)
|
|
279
279
|
- **removeBorderValues** - By default additional border values are returned to optimize charting. Set this option to true if this is not wanted (e.g. for script data processing)
|
|
280
280
|
- **returnNewestEntries** - The returned data are always sorted by timestamp ascending. When using aggregate "none" and also providing "count" or "limit" this means that normally the oldest entries are returned (unless no start data is provided). Set this option to true to get the newest entries instead.
|
|
281
|
-
- **aggregate** - aggregate method:
|
|
281
|
+
- **aggregate** - aggregate method (Default: 'average'):
|
|
282
282
|
- *minmax* - used special algorithm. Splice the whole time range in small intervals and find for every interval max, min, start and end values.
|
|
283
283
|
- *max* - Splice the whole time range in small intervals and find for every interval max value and use it for this interval (nulls will be ignored).
|
|
284
284
|
- *min* - Same as max, but take minimal value.
|
|
@@ -364,7 +364,9 @@ Example if your database is called 'iobroker':
|
|
|
364
364
|
If you want to write other data into the InfluxDB/SQL you can use the build in system function **storeState**.
|
|
365
365
|
This function can also be used to convert data from other History adapters like History or SQL.
|
|
366
366
|
|
|
367
|
-
|
|
367
|
+
A successful response do not mean that the data are really written out to the disk. It just means that they were processed.
|
|
368
|
+
|
|
369
|
+
The given ids are not checked against the ioBroker database and do not need to be set up or enabled there. If own IDs are used without settings then the "rules" parameter is not supported and will result in an error. The default "Maximal number of stored in RAM values" is used for such IDs.
|
|
368
370
|
|
|
369
371
|
The Message can have one of the following three formats:
|
|
370
372
|
* one ID and one state object
|
|
@@ -399,6 +401,8 @@ sendTo('history.0', 'storeState', [
|
|
|
399
401
|
|
|
400
402
|
Additionally, you can add attribute `rules: true` in message to activate all rules, like `counter`, `changesOnly`, `de-bounce` and so on.
|
|
401
403
|
|
|
404
|
+
In case of errors an array with all single error messages is returned and also a successCount to see how many entries were stored successfully.
|
|
405
|
+
|
|
402
406
|
## delete state
|
|
403
407
|
If you want to delete entry from the Database you can use the build in system function **delete**:
|
|
404
408
|
|
|
@@ -516,6 +520,17 @@ sendTo('sql.0', 'getEnabledDPs', {}, function (result) {
|
|
|
516
520
|
-->
|
|
517
521
|
|
|
518
522
|
## Changelog
|
|
523
|
+
### 2.1.0 (2022-05-27)
|
|
524
|
+
* (Apollon77) Fix crash cases reported by Sentry
|
|
525
|
+
* (Apollon77) Fix several places where pooled connections might have not been returned to pool correctly and add logging for it
|
|
526
|
+
* (Apollon77) Work around an issue in used Pooling library that potentially gave out too many connections
|
|
527
|
+
* (Apollon77) Optimize retention check to better spread the first checks over time
|
|
528
|
+
* (Apollon77) Default to not use datapoint buffering as in 1.x when set to 0
|
|
529
|
+
* (Apollon77) Make sure disabling "Log changes only" also really do not log the changes anymore
|
|
530
|
+
* (Apollon77) Allow storeState and GetHistory also to be called for "unknown ids"
|
|
531
|
+
* (Apollon77) Adjust the fallback logic for type detection to use the type of the state value to log as last fallback
|
|
532
|
+
* (Apollon77) Fix storing booleans on MSSQL
|
|
533
|
+
|
|
519
534
|
### 2.0.2 (2022-05-11)
|
|
520
535
|
* (Apollon77) BREAKING: Configuration is only working in the new Admin 5 UI!
|
|
521
536
|
* (Apollon77) Did bigger adjustments to the recording logic and added a lot of new Features. Please refer to Changelog and Forum post for details.
|
|
@@ -58,9 +58,9 @@
|
|
|
58
58
|
"Write NULL values on start/stop boundaries": "Schreibe NULL-Werte an Start-/Stop-Grenzen",
|
|
59
59
|
"aliasId": "Alias-ID",
|
|
60
60
|
"blockTime": "Alle neuen Werte für X ms nach dem letzten protokollierten Wert ignorieren",
|
|
61
|
-
"debounce": "
|
|
61
|
+
"debounce": "Änderungen ignorieren, bis der Wert für X Millisekunden unverändert bleibt",
|
|
62
62
|
"ignore values above x": "Ignoriere Werte größer als",
|
|
63
|
-
"ignore values below x": "
|
|
63
|
+
"ignore values below x": "Ignoriere Werte kleiner als",
|
|
64
64
|
"ignore values below zero": "Werte unter 0 ignorieren (<0)",
|
|
65
65
|
"ignore zero or null values": "Ignoriere 0 oder Nullwerte (==0)",
|
|
66
66
|
"keep forever": "keine automatische Löschung",
|
|
@@ -68,6 +68,6 @@
|
|
|
68
68
|
"log changes minimal delta": "Minimale Differenz zum letzten Wert",
|
|
69
69
|
"log changes only": "Nur Änderungen aufzeichnen",
|
|
70
70
|
"note": "History Einstellungen müssen für jeden State einzeln gemacht werden, im Tab \"States\" und nur wenn die Adapter Instanz aktiv ist",
|
|
71
|
-
"requestInterval": "
|
|
71
|
+
"requestInterval": "Wartezeit zwischen DB Anfragen(ms)",
|
|
72
72
|
"retention": "Storage Vorhaltezeit"
|
|
73
73
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
|
-
"0 = disable": "0
|
|
2
|
+
"0 = disable": "0 = 禁用",
|
|
3
3
|
"0 = disable delta check": "0 =禁用增量检查",
|
|
4
4
|
"0 = disabled": "0 =禁用",
|
|
5
5
|
"1 day": "1天",
|
|
@@ -44,7 +44,7 @@
|
|
|
44
44
|
"Password": "密码",
|
|
45
45
|
"Password confirm": "确认密码",
|
|
46
46
|
"Password confirmation is not equal with password!": "密码确认不等于密码!",
|
|
47
|
-
"Port": "
|
|
47
|
+
"Port": "端口",
|
|
48
48
|
"Reject on SSL errors": "拒绝 SSL 错误",
|
|
49
49
|
"Reset DB": "重置数据库",
|
|
50
50
|
"Round real to": "在查询轮数到",
|
|
@@ -70,4 +70,4 @@
|
|
|
70
70
|
"note": "仅在适配器处于活动状态时,才必须在“状态”选项卡上分别为每个状态进行历史记录设置",
|
|
71
71
|
"requestInterval": "请求之间的暂停时间(毫秒)",
|
|
72
72
|
"retention": "储存保留"
|
|
73
|
-
}
|
|
73
|
+
}
|
package/admin/words.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
'use strict';
|
|
3
3
|
|
|
4
4
|
systemDictionary = {
|
|
5
|
-
"0 = disable": { "en": "0 = disable", "de": "0 = Deaktivieren", "ru": "0 = не активно", "pt": "0 = desativar", "nl": "0 = uitschakelen", "fr": "0 = désactiver", "it": "0 = disabilita", "es": "0 = desactivar", "pl": "0 = wyłącz", "zh-cn": "0
|
|
5
|
+
"0 = disable": { "en": "0 = disable", "de": "0 = Deaktivieren", "ru": "0 = не активно", "pt": "0 = desativar", "nl": "0 = uitschakelen", "fr": "0 = désactiver", "it": "0 = disabilita", "es": "0 = desactivar", "pl": "0 = wyłącz", "zh-cn": "0 = 禁用"},
|
|
6
6
|
"0 = disable delta check": { "en": "0 = disable delta check", "de": "0 = Abweichungsprüfung deaktivieren", "ru": "0 = не проверять минимальное изменение", "pt": "0 = desativar o cheque delta", "nl": "0 = delta-controle uitschakelen", "fr": "0 = désactiver le contrôle delta", "it": "0 = disabilita il controllo delta", "es": "0 = deshabilitar la verificación delta", "pl": "0 = wyłącz kontrolę delta", "zh-cn": "0 =禁用增量检查"},
|
|
7
7
|
"0 = disabled": { "en": "0 = disabled", "de": "0 = deaktiviert", "ru": "0 = отключить", "pt": "0 = desabilitar", "nl": "0 = uitschakelen", "fr": "0 = désactiver", "it": "0 = disabilita", "es": "0 = deshabilitar", "pl": "0 = wyłącz", "zh-cn": "0 =禁用"},
|
|
8
8
|
"1 day": { "en": "1 day", "de": "1 Tag", "ru": "1 день", "pt": "1 dia", "nl": "1 dag", "fr": "Un jour", "it": "1 giorno", "es": "1 día", "pl": "1 dzień", "zh-cn": "1天"},
|
|
@@ -20,8 +20,10 @@ systemDictionary = {
|
|
|
20
20
|
"Are you sure? All data will be dropped.": { "en": "All data will be dropped. Are you sure? ", "de": "Sollen wirklich alle Daten gelöscht werden? ", "ru": "Вы уверены? Все данные в базе будут удалены. ", "pt": "Você tem certeza? Todos os dados serão descartados.", "nl": "Weet je het zeker? Alle gegevens worden verwijderd.", "fr": "Êtes-vous sûr? Toutes les données seront supprimées.", "it": "Sei sicuro? Tutti i dati verranno eliminati.", "es": "¿Estás seguro? Todos los datos serán eliminados.", "pl": "Jesteś pewny? Wszystkie dane zostaną usunięte.", "zh-cn": "你确定吗?"},
|
|
21
21
|
"Automatic": { "en": "Automatic", "de": "Automatisch", "ru": "автоматическая", "pt": "Automático", "nl": "automatisch", "fr": "Automatique", "it": "Automatico", "es": "Automatycznyy", "pl": "Automatyczny", "zh-cn": "自动"},
|
|
22
22
|
"Block time": { "en": "Blocktime", "de": "Blockzeit", "ru": "Блокировка", "pt": "Blocktime", "nl": "Bloktijd", "fr": "Temps de blocage", "it": "Blocktime", "es": "hora de bloque", "pl": "Czas blokady", "zh-cn": "出块时间"},
|
|
23
|
-
"Boolean": { "en": "Boolean", "de": "
|
|
23
|
+
"Boolean": { "en": "Boolean", "de": "Boolean", "ru": "логический", "pt": "boleano", "nl": "Boolean", "fr": "Booléen", "it": "booleano", "es": "Booleano", "pl": "Boolean", "zh-cn": "布尔值"},
|
|
24
24
|
"Counter": { "en": "Counter", "de": "Zähler", "ru": "счетчик", "pt": "Contador", "nl": "Teller", "fr": "Compteur", "it": "contatore", "es": "Mostrador", "pl": "Licznik", "zh-cn": "计数器"},
|
|
25
|
+
"Custom retention duration (days)": { "en": "Custom retention duration (days)", "de": "Benutzerdefinierte Aufbewahrungsdauer (Tage)", "ru": "Пользовательский срок хранения (дни)", "pt": "Duração da retenção personalizada (dias)", "nl": "Aangepaste bewaarduur (dagen)", "fr": "Durée de conservation personnalisée (jours)", "it": "Durata di conservazione personalizzata (giorni)", "es": "Duración de la retención personalizada (días)", "pl": "Niestandardowy czas przechowywania (dni)", "zh-cn": "自定义保留期限(天)"},
|
|
26
|
+
"Custom timeframe": { "en": "Custom timeframe", "de": "Benutzerdefinierter Zeitrahmen", "ru": "Пользовательский таймфрейм", "pt": "Período personalizado", "nl": "Aangepast tijdsbestek", "fr": "Délai personnalisé", "it": "Tempi personalizzati", "es": "Marco de tiempo personalizado", "pl": "Niestandardowe ramy czasowe", "zh-cn": "自定义时间范围"},
|
|
25
27
|
"DB Name": { "en": "Database name", "de": "Datenbankname", "ru": "Имя базы данных", "pt": "Nome do banco de dados", "nl": "Database naam", "fr": "Nom de la base de données", "it": "Nome del database", "es": "Nombre de la base de datos", "pl": "Nazwa bazy danych", "zh-cn": "数据库名称"},
|
|
26
28
|
"DB Type": { "en": "DB Type", "de": "DB Typ", "ru": "Тип базы", "pt": "DB Type", "nl": "DB Type", "fr": "Type de DB", "it": "Tipo di DB", "es": "Tipo de DB", "pl": "Typ DB", "zh-cn": "数据库类型"},
|
|
27
29
|
"DB settings": { "en": "DB settings", "de": "DB Einstellungen", "ru": "Настройки соединения с DB", "pt": "Configurações de banco de dados", "nl": "DB-instellingen", "fr": "Paramètres DB", "it": "Impostazioni DB", "es": "Configuración de DB", "pl": "Ustawienia DB", "zh-cn": "数据库设置"},
|
|
@@ -39,12 +41,13 @@ systemDictionary = {
|
|
|
39
41
|
"Input path with the file name.": { "en": "E.g. /opt/sqlite/data.db", "de": "Z.B. /opt/sqlite/data.db", "ru": "Например /opt/sqlite/data.db", "pt": "Por exemplo. /opt/sqlite/data.db", "nl": "Bijv. /opt/sqlite/data.db", "fr": "Par exemple. /opt/sqlite/data.db", "it": "Per esempio. /opt/sqlite/data.db", "es": "P.ej. /opt/sqlite/data.db", "pl": "Na przykład. /opt/sqlite/data.db", "zh-cn": "例如。 "},
|
|
40
42
|
"Maximum concurrent connections": { "en": "Maximum concurrent connections", "de": "Max. gleichzeitige Verbindungen", "ru": "Максимальное количество одновременных подключений", "pt": "Máximo de conexões simultâneas", "nl": "Maximum aantal gelijktijdige verbindingen", "fr": "Nombre maximal de connexions simultanées", "it": "Numero massimo di connessioni simultanee", "es": "Máximas conexiones concurrentes", "pl": "Maksymalna liczba jednoczesnych połączeń", "zh-cn": "最大并发连接数"},
|
|
41
43
|
"Maximum concurrent connections:": { "en": "Maximum concurrent connections:", "de": "Maximale Anzahl parallele Verbindungen:", "ru": "Максимальное количество одновременных подключений:", "pt": "Máximo de conexões simultâneas:", "nl": "Maximale gelijktijdige verbindingen:", "fr": "Connexions simultanées maximales :", "it": "Numero massimo di connessioni simultanee:", "es": "Máximo de conexiones simultáneas:", "pl": "Maksymalna liczba jednoczesnych połączeń:", "zh-cn": "最大并发连接数:"},
|
|
42
|
-
"Number": { "en": "Number", "de": "
|
|
44
|
+
"Number": { "en": "Number", "de": "Zahl", "ru": "Число", "pt": "Número", "nl": "Aantal", "fr": "Nombre", "it": "Numero", "es": "Numer", "pl": "Numer", "zh-cn": "数字"},
|
|
45
|
+
"Number of days to keep the data.": { "en": "Number of days to keep the data.", "de": "Anzahl der Tage, um die Daten aufzubewahren.", "ru": "Количество дней хранения данных.", "pt": "Número de dias para manter os dados.", "nl": "Aantal dagen om de gegevens te bewaren.", "fr": "Nombre de jours de conservation des données.", "it": "Numero di giorni di conservazione dei dati.", "es": "Número de días para conservar los datos.", "pl": "Liczba dni przechowywania danych.", "zh-cn": "保留数据的天数。"},
|
|
43
46
|
"Ok": { "en": "Ok", "de": "Ok", "ru": "Ok", "pt": "Ok", "nl": "OK", "fr": "D'accord", "it": "Ok", "es": "De acuerdo", "pl": "Ok", "zh-cn": "好的"},
|
|
44
47
|
"Password": { "en": "Password", "de": "Passwort", "ru": "Пароль", "pt": "Senha", "nl": "Wachtwoord", "fr": "Mot de passe", "it": "Parola d'ordine", "es": "Contraseña", "pl": "Hasło", "zh-cn": "密码"},
|
|
45
48
|
"Password confirm": { "en": "Password confirm", "de": "Passwort-Wiederholung", "ru": "Подтверждение пароля", "pt": "Confirmação de senha", "nl": "Wachtwoord bevestigen", "fr": "Confirmer le mot de passe", "it": "Conferma la password", "es": "Contraseña confirmada", "pl": "Potwierdź hasło", "zh-cn": "确认密码"},
|
|
46
49
|
"Password confirmation is not equal with password!": {"en": "Password confirmation is not equal with password!", "de": "Passwort-Bestätigung stimmt nicht mit dem Passwort überein!", "ru": "Подтверждение пароля не совпадает с паролем!", "pt": "A confirmação da senha não é igual com a senha!", "nl": "Wachtwoordbevestiging is niet gelijk aan wachtwoord!", "fr": "La confirmation du mot de passe n'est pas égale au mot de passe!", "it": "La conferma della password non è uguale alla password!", "es": "La confirmación de la contraseña no es igual a la contraseña!", "pl": "Potwierdzenie hasła nie jest równe hasłu!", "zh-cn": "密码确认不等于密码!"},
|
|
47
|
-
"Port": { "en": "Port", "de": "Port", "ru": "Порт", "pt": "Porta", "nl": "Haven", "fr": "Port", "it": "Porta", "es": "Puerto", "pl": "Port", "zh-cn": "
|
|
50
|
+
"Port": { "en": "Port", "de": "Port", "ru": "Порт", "pt": "Porta", "nl": "Haven", "fr": "Port", "it": "Porta", "es": "Puerto", "pl": "Port", "zh-cn": "端口"},
|
|
48
51
|
"Reject on SSL errors": { "en": "Reject on SSL errors", "de": "Ablehnen bei SSL-Fehlern", "ru": "Отклонить при ошибках SSL", "pt": "Rejeitar em erros de SSL", "nl": "Weigeren bij SSL-fouten", "fr": "Rejeter sur les erreurs SSL", "it": "Rifiuta errori SSL", "es": "Rechazar en errores de SSL", "pl": "Odrzuć błędy SSL", "zh-cn": "拒绝 SSL 错误"},
|
|
49
52
|
"Reset DB": { "en": "Reset DB", "de": "Alle Daten in Datenbank löschen", "ru": "Очистить базу", "pt": "Redefinir DB", "nl": "Stel DB opnieuw in", "fr": "Reset DB", "it": "Ripristina DB", "es": "Restablecer DB", "pl": "Zresetuj DB", "zh-cn": "重置数据库"},
|
|
50
53
|
"Round real to": { "en": "On query round numbers to", "de": "Runden Sie bei der Abfrage die Zahlen auf", "ru": "По запросу округлить числа до", "pt": "Na consulta arredondar os números para", "nl": "Op query ronde getallen naar", "fr": "Sur requête arrondir les nombres à", "it": "Su interrogazione arrotondare i numeri a", "es": "En consulta números redondos a", "pl": "Na zapytanie okrągłe liczby do", "zh-cn": "在查询轮数到"},
|
|
@@ -58,9 +61,9 @@ systemDictionary = {
|
|
|
58
61
|
"Write NULL values on start/stop boundaries": { "en": "Write NULL values on start/stop boundaries", "de": "Schreibe NULL-Werte an Start-/Stop-Grenzen", "ru": "Запись NULL для отметки старта/остановки экземпляра", "pt": "Escreva valores NULL nos limites de início / parada", "nl": "Schrijf NULL-waarden op start / stop-grenzen", "fr": "Écrire des valeurs NULL sur les limites de démarrage / arrêt", "it": "Scrivi valori NULL sui limiti di avvio / arresto", "es": "Escribe valores NULL en los límites de inicio / finalización", "pl": "Napisz wartości NULL na granicach start / stop", "zh-cn": "在开始/停止边界上写入NULL值"},
|
|
59
62
|
"aliasId": { "en": "Alias-ID", "de": "Alias-ID", "ru": "Псевдоним ИД", "pt": "Alias-ID", "nl": "Alias-ID", "fr": "Alias-ID", "it": "Alias-ID", "es": "Alias-ID", "pl": "Alias-ID", "zh-cn": "别名 ID"},
|
|
60
63
|
"blockTime": { "en": "Ignore all new values for X ms after last logged value", "de": "Alle neuen Werte für X ms nach dem letzten protokollierten Wert ignorieren", "ru": "Игнорировать все новые значения для X мс после последнего зарегистрированного значения", "pt": "Ignore todos os novos valores por X ms após o último valor registrado", "nl": "Negeer alle nieuwe waarden voor X ms na de laatste gelogde waarde", "fr": "Ignorer toutes les nouvelles valeurs pendant X ms après la dernière valeur enregistrée", "it": "Ignora tutti i nuovi valori per X ms dopo l'ultimo valore registrato", "es": "Ignorar todos los valores nuevos para X ms después del último valor registrado", "pl": "Ignoruj wszystkie nowe wartości przez X ms po ostatniej zarejestrowanej wartości", "zh-cn": "在上次记录值之后忽略 X 毫秒的所有新值"},
|
|
61
|
-
"debounce": { "en": "Ignore changes till value stays unchanged for X Milliseconds", "de": "
|
|
64
|
+
"debounce": { "en": "Ignore changes till value stays unchanged for X Milliseconds", "de": "Änderungen ignorieren, bis der Wert für X Millisekunden unverändert bleibt", "ru": "Минимальный интервал(ms)", "pt": "Intervalo de desvio (ms)", "nl": "De-bounce interval (ms)", "fr": "Intervalle de rebond (ms)", "it": "Intervallo di rimbalzo (ms)", "es": "Intervalo de rebote (ms)", "pl": "Interwał odbicia (ms)", "zh-cn": "忽略更改,直到值保持不变为X毫秒<br>(去抖时间)"},
|
|
62
65
|
"ignore values above x": { "en": "Ignore values above", "de": "Ignoriere Werte größer als", "ru": "Игнорировать значения выше", "pt": "Ignorar valores acima", "nl": "Bovenstaande waarden negeren", "fr": "Ignorer les valeurs ci-dessus", "it": "Ignora i valori sopra", "es": "Ignorar los valores anteriores", "pl": "Zignoruj wartości powyżej", "zh-cn": "忽略上面的值"},
|
|
63
|
-
"ignore values below x": { "en": "Ignore values below", "de": "
|
|
66
|
+
"ignore values below x": { "en": "Ignore values below", "de": "Ignoriere Werte kleiner als", "ru": "Игнорировать значения ниже", "pt": "Ignorar valores abaixo", "nl": "Negeer onderstaande waarden", "fr": "Ignorer les valeurs ci-dessous", "it": "Ignora i valori sottostanti", "es": "Ignorar valores a continuación", "pl": "Zignoruj wartości poniżej", "zh-cn": "忽略下面的值"},
|
|
64
67
|
"ignore values below zero": { "en": "ignore values below zero (<0)", "de": "Werte unter 0 ignorieren (<0)", "ru": "игнорировать значения ниже нуля (<0)", "pt": "ignorar valores abaixo de zero (<0)", "nl": "negeer waarden onder nul (<0)", "fr": "ignorer les valeurs inférieures à zéro (<0)", "it": "ignora i valori inferiori a zero (<0)", "es": "ignorar valores por debajo de cero (<0)", "pl": "zignoruj wartości poniżej zera (<0)", "zh-cn": "忽略低于零 (<0) 的值"},
|
|
65
68
|
"ignore zero or null values": { "en": "ignore 0 or null values (==0)", "de": "Ignoriere 0 oder Nullwerte (==0)", "ru": "игнорировать нулевые или нулевые значения (== 0)", "pt": "ignorar valores zero ou nulos (== 0)", "nl": "negeer nul- of null-waarden (==0)", "fr": "ignorer les valeurs nulles ou nulles (==0)", "it": "ignora i valori zero o null (==0)", "es": "ignorar valores cero o nulos (== 0)", "pl": "zignoruj wartości zero lub null (==0)", "zh-cn": "忽略零或空值 (==0)"},
|
|
66
69
|
"keep forever": { "en": "keep forever", "de": "keine automatische Löschung", "ru": "хранить вечно", "pt": "mantenha para sempre", "nl": "blijf voor altijd", "fr": "garde pour toujours", "it": "tienilo per sempre", "es": "mantener para siempre", "pl": "zachowaj na zawsze", "zh-cn": "永远保持"},
|
|
@@ -68,9 +71,6 @@ systemDictionary = {
|
|
|
68
71
|
"log changes minimal delta": { "en": "Minimum difference from last value", "de": "Minimale Differenz zum letzten Wert", "ru": "Минимальное отличие от последнего значения", "pt": "Diferença mínima do último valor", "nl": "Minimaal verschil met laatste waarde", "fr": "Différence minimale par rapport à la dernière valeur", "it": "Differenza minima dall'ultimo valore", "es": "Diferencia mínima desde el último valor", "pl": "Minimalna różnica od ostatniej wartości", "zh-cn": "与上一个值的最小差异"},
|
|
69
72
|
"log changes only": { "en": "Record changes only", "de": "Nur Änderungen aufzeichnen", "ru": "Запись только изменений", "pt": "Registrar apenas alterações", "nl": "Wijzigingen alleen registreren", "fr": "Enregistrer les modifications uniquement", "it": "Registra solo le modifiche", "es": "Registrar solo cambios", "pl": "Zapisz tylko zmiany", "zh-cn": "仅记录更改"},
|
|
70
73
|
"note": { "en": "History settings must be done for every state individually on the tab \"States\" and only if adapter is active", "de": "History Einstellungen müssen für jeden State einzeln gemacht werden, im Tab \"States\" und nur wenn die Adapter Instanz aktiv ist", "ru": "Настройки history делаются для каждого состояния отдельно в закладке \"Состояния\" и только, когда инстанция активирована", "pt": "As configurações de histórico devem ser feitas para cada estado individual na guia \"Estados\" e somente se o adaptador estiver ativo", "nl": "Geschiedenisinstellingen moeten voor elke afzonderlijke status worden uitgevoerd op het tabblad \"Staten\" en alleen als de adapter actief is", "fr": "Les paramètres d'historique doivent être définis pour chaque état individuellement dans l'onglet \"Etats\" et uniquement si l'adaptateur est actif", "it": "Le impostazioni della cronologia devono essere eseguite singolarmente per ogni stato nella scheda \"Stati\" e solo se l'adattatore è attivo", "es": "La configuración del historial se debe realizar para cada estado individualmente en la pestaña \"Estados\" y solo si el adaptador está activo", "pl": "Ustawienia historii muszą być wykonane dla każdego stanu indywidualnie na karcie \"Stany\" i tylko wtedy, gdy adapter jest aktywny", "zh-cn": "仅在适配器处于活动状态时,才必须在“状态”选项卡上分别为每个状态进行历史记录设置"},
|
|
71
|
-
"requestInterval": { "en": "Pause between requests(ms)", "de": "
|
|
74
|
+
"requestInterval": { "en": "Pause between requests(ms)", "de": "Wartezeit zwischen DB Anfragen(ms)", "ru": "Пауза между запросами к базе", "pt": "Pausa entre solicitações (ms)", "nl": "Pauzeren tussen verzoeken (ms)", "fr": "Pause entre les demandes (ms)", "it": "Pausa tra le richieste (ms)", "es": "Pausa entre solicitudes (ms)", "pl": "Wstrzymaj między żądaniami (ms)", "zh-cn": "请求之间的暂停时间(毫秒)"},
|
|
72
75
|
"retention": { "en": "Storage retention", "de": "Storage Vorhaltezeit", "ru": "Время хранения в базе", "pt": "Retenção de armazenamento", "nl": "Bewaring van opslag", "fr": "Rétention de stockage", "it": "Conservazione dello spazio", "es": "Retención de almacenamiento", "pl": "Zatrzymanie przechowywania", "zh-cn": "储存保留"},
|
|
73
|
-
"Custom timeframe": { "en": "Custom timeframe", "de": "Benutzerdefinierter Zeitrahmen", "ru": "Пользовательский таймфрейм", "pt": "Período personalizado", "nl": "Aangepast tijdsbestek", "fr": "Délai personnalisé", "it": "Tempi personalizzati", "es": "Marco de tiempo personalizado", "pl": "Niestandardowe ramy czasowe", "zh-cn": "自定义时间范围"},
|
|
74
|
-
"Custom retention duration (days)": { "en": "Custom retention duration (days)", "de": "Benutzerdefinierte Aufbewahrungsdauer (Tage)", "ru": "Пользовательский срок хранения (дни)", "pt": "Duração da retenção personalizada (dias)", "nl": "Aangepaste bewaarduur (dagen)", "fr": "Durée de conservation personnalisée (jours)", "it": "Durata di conservazione personalizzata (giorni)", "es": "Duración de la retención personalizada (días)", "pl": "Niestandardowy czas przechowywania (dni)", "zh-cn": "自定义保留期限(天)"},
|
|
75
|
-
"Number of days to keep the data.": { "en": "Number of days to keep the data.", "de": "Anzahl der Tage, um die Daten aufzubewahren.", "ru": "Количество дней хранения данных.", "pt": "Número de dias para manter os dados.", "nl": "Aantal dagen om de gegevens te bewaren.", "fr": "Nombre de jours de conservation des données.", "it": "Numero di giorni di conservazione dei dati.", "es": "Número de días para conservar los datos.", "pl": "Liczba dni przechowywania danych.", "zh-cn": "保留数据的天数。"},
|
|
76
76
|
};
|
package/io-package.json
CHANGED
|
@@ -26,8 +26,20 @@
|
|
|
26
26
|
"pl": "Rejestrowanie stanów w SQL DB",
|
|
27
27
|
"zh-cn": "将状态记录到SQL DB"
|
|
28
28
|
},
|
|
29
|
-
"version": "2.0
|
|
29
|
+
"version": "2.1.0",
|
|
30
30
|
"news": {
|
|
31
|
+
"2.1.0": {
|
|
32
|
+
"en": "Fix crash cases reported by Sentry\nFix several places where pooled connections might have not been returned to pool correctly and add logging for it\nWork around an issue in used Pooling library that potentially gave out too many connections\nOptimize retention check to better spread the first checks over time\nDefault to not use datapoint buffering as in 1.x when set to 0\nMake sure disabling \"Log changes only\" also really do not log the changes anymore\nAllow storeState and GetHistory also to be called for \"unknown ids\"\nAdjust the fallback logic for type detection to use the type of the state value to log as last fallback\nFix storing booleans on MSSQL",
|
|
33
|
+
"de": "Von Sentry gemeldete Absturzfälle beheben\nBeheben Sie mehrere Stellen, an denen gepoolte Verbindungen möglicherweise nicht korrekt an den Pool zurückgegeben wurden, und fügen Sie die Protokollierung dafür hinzu\nUmgehung eines Problems in der verwendeten Pooling-Bibliothek, das möglicherweise zu viele Verbindungen ausgegeben hat\nOptimieren Sie die Aufbewahrungsprüfung, um die ersten Prüfungen besser über die Zeit zu verteilen\nStandardmäßig keine Datenpunktpufferung wie in 1.x verwenden, wenn auf 0 gesetzt\nStellen Sie sicher, dass durch Deaktivieren von \"Nur Änderungen protokollieren\" die Änderungen auch wirklich nicht mehr protokolliert werden\nAufruf von storeState und GetHistory auch für \"unbekannte IDs\" zulassen\nPassen Sie die Fallback-Logik für die Typerkennung so an, dass der Typ des Statuswerts als letzter Fallback protokolliert wird\nFehler beim Speichern von booleschen Werten in MSSQL behoben",
|
|
34
|
+
"ru": "Исправить случаи сбоев, о которых сообщил Sentry\nИсправьте несколько мест, где соединения из пула могли быть неправильно возвращены в пул, и добавьте для этого ведение журнала.\nОбойти проблему в используемой библиотеке пулов, которая потенциально выдавала слишком много соединений.\nОптимизируйте проверку хранения, чтобы лучше распределять первые проверки по времени.\nПо умолчанию буферизация точек данных не используется, как в 1.x, если установлено значение 0.\nУбедитесь, что отключение «Только журнал изменений» также действительно больше не регистрирует изменения.\nРазрешить также вызывать storeState и GetHistory для «неизвестных идентификаторов».\nНастройте резервную логику для определения типа, чтобы использовать тип значения состояния для регистрации в качестве последнего резервного варианта.\nИсправление хранения логических значений в MSSQL",
|
|
35
|
+
"pt": "Corrigir casos de travamento relatados pelo Sentinela\nCorrija vários locais onde as conexões em pool podem não ter sido retornadas ao pool corretamente e adicione o registro para ele\nContorne um problema na biblioteca de pooling usada que potencialmente forneceu muitas conexões\nOtimize a verificação de retenção para distribuir melhor as primeiras verificações ao longo do tempo\nPadrão para não usar o buffer de ponto de dados como em 1.x quando definido como 0\nCertifique-se de desativar \"Somente alterações de log\" também não registra mais as alterações\nPermitir que storeState e GetHistory também sejam chamados para \"ids desconhecidos\"\nAjuste a lógica de fallback para detecção de tipo para usar o tipo do valor de estado para registrar como último fallback\nCorrige o armazenamento de booleanos no MSSQL",
|
|
36
|
+
"nl": "Herstel crashgevallen gemeld door Sentry\nLos verschillende plaatsen op waar gepoolde verbindingen mogelijk niet correct zijn teruggestuurd naar de pool en voeg er logboeken voor toe\nOmzeil een probleem in de gebruikte pooling-bibliotheek die mogelijk te veel verbindingen opleverde\nOptimaliseer de retentiecontrole om de eerste controles beter over de tijd te spreiden\nStandaard om datapuntbuffering niet te gebruiken zoals in 1.x indien ingesteld op 0\nZorg ervoor dat het uitschakelen van \"Alleen wijzigingen loggen\" ook echt de wijzigingen niet meer logt\nToestaan dat storeState en GetHistory ook worden aangeroepen voor \"onbekende id's\"\nPas de fallback-logica voor typedetectie aan om het type statuswaarde te gebruiken om te loggen als laatste fallback\nFix opslaan van booleans op MSSQL",
|
|
37
|
+
"fr": "Correction des cas de plantage signalés par Sentry\nCorrigez plusieurs endroits où les connexions groupées n'ont peut-être pas été renvoyées correctement au pool et ajoutez-y une journalisation\nContourner un problème dans la bibliothèque de mise en commun utilisée qui a potentiellement donné trop de connexions\nOptimiser le contrôle de rétention pour mieux répartir les premiers contrôles dans le temps\nPar défaut pour ne pas utiliser la mise en mémoire tampon des points de données comme dans 1.x lorsqu'il est défini sur 0\nAssurez-vous que la désactivation de \"Log changes only\" n'enregistre plus vraiment les modifications\nAutoriser storeState et GetHistory à être également appelés pour les \"identifiants inconnus\"\nAjustez la logique de repli pour la détection de type afin d'utiliser le type de la valeur d'état à enregistrer comme dernier repli\nCorrection du stockage des booléens sur MSSQL",
|
|
38
|
+
"it": "Risolvi i casi di crash segnalati da Sentry\nRisolvi diversi punti in cui le connessioni in pool potrebbero non essere state restituite al pool correttamente e aggiungi la registrazione per esso\nRisolvere un problema nella libreria di pooling utilizzata che potenzialmente ha fornito troppe connessioni\nOttimizza il controllo di conservazione per distribuire meglio i primi controlli nel tempo\nL'impostazione predefinita non utilizza il buffering dei punti dati come in 1.x quando è impostato su 0\nAssicurati che la disabilitazione di \"Registra solo modifiche\" non registri più le modifiche\nConsenti la chiamata anche a storeState e GetHistory per \"ID sconosciuti\"\nRegola la logica di fallback per il rilevamento del tipo per utilizzare il tipo del valore di stato da registrare come ultimo fallback\nRisolto il problema con la memorizzazione dei booleani su MSSQL",
|
|
39
|
+
"es": "Solucionar casos de fallas informados por Sentry\nCorrija varios lugares donde las conexiones agrupadas podrían no haber regresado al grupo correctamente y agregue el registro para ello\nSolucione un problema en la biblioteca de agrupación utilizada que potencialmente proporcionó demasiadas conexiones\nOptimice el control de retención para distribuir mejor los primeros controles a lo largo del tiempo\nPredeterminado para no usar el almacenamiento en búfer de puntos de datos como en 1.x cuando se establece en 0\nAsegúrese de deshabilitar \"Registrar solo cambios\" y realmente no registre más los cambios\nPermitir que storeState y GetHistory también se llamen para \"identificadores desconocidos\"\nAjuste la lógica de respaldo para la detección de tipo para usar el tipo del valor de estado para registrar como último respaldo\nArreglar el almacenamiento de booleanos en MSSQL",
|
|
40
|
+
"pl": "Napraw przypadki awarii zgłoszone przez Sentry\nNapraw kilka miejsc, w których połączenia z puli mogły nie zostać poprawnie zwrócone do puli i dodaj dla tego logowanie\nObejdź problem w używanej bibliotece Pooling, który potencjalnie powodował zbyt wiele połączeń\nZoptymalizuj kontrolę retencji, aby lepiej rozłożyć pierwsze kontrole w czasie\nDomyślnie nie używa buforowania punktu danych, jak w 1.x, gdy jest ustawione na 0\nUpewnij się, że wyłączenie opcji „Zapisuj tylko zmiany” również naprawdę nie powoduje już rejestrowania zmian\nZezwalaj na wywoływanie storeState i GetHistory również dla „nieznanych identyfikatorów”\nDostosuj logikę rezerwy dla wykrywania typu, aby użyć typu wartości stanu do zalogowania jako ostatniej rezerwy\nNapraw przechowywanie wartości logicznych w MSSQL",
|
|
41
|
+
"zh-cn": "修复 Sentry 报告的崩溃案例\n修复池连接可能未正确返回池的几个地方并为其添加日志记录\n解决使用过的池库中可能给出过多连接的问题\n优化保留检查,以便随着时间的推移更好地传播第一次检查\n默认设置为 0 时不使用 1.x 中的数据点缓冲\n确保禁用“仅记录更改”也不再记录更改\n还允许为“未知 ID”调用 storeState 和 GetHistory\n调整类型检测的回退逻辑以使用状态值的类型记录为最后一个回退\n修复在 MSSQL 上存储布尔值"
|
|
42
|
+
},
|
|
31
43
|
"2.0.2": {
|
|
32
44
|
"en": "BREAKING: Configuration is only working in the new Admin 5 UI!\nDid bigger adjustments to the recording logic and added a lot of new Features. Please refer to Changelog and Forum post for details.",
|
|
33
45
|
"de": "BREAKING: Die Konfiguration funktioniert nur in der neuen Admin 5-Benutzeroberfläche!\nGrößere Anpassungen an der Aufnahmelogik vorgenommen und viele neue Features hinzugefügt. Einzelheiten finden Sie im Änderungsprotokoll und im Forumsbeitrag.",
|
|
@@ -99,18 +111,6 @@
|
|
|
99
111
|
"es": "soporte agregado de Admin5",
|
|
100
112
|
"pl": "dodana obsługa Admin5",
|
|
101
113
|
"zh-cn": "增加了对Admin5的支持"
|
|
102
|
-
},
|
|
103
|
-
"1.15.5": {
|
|
104
|
-
"en": "make sure message query is a string (Sentry)",
|
|
105
|
-
"de": "Stellen Sie sicher, dass die Nachrichtenabfrage eine Zeichenfolge ist (Sentry).",
|
|
106
|
-
"ru": "убедитесь, что запрос сообщения является строкой (Sentry)",
|
|
107
|
-
"pt": "certifique-se de que a consulta da mensagem é uma string (Sentry)",
|
|
108
|
-
"nl": "zorg ervoor dat de berichtvraag een tekenreeks is (Sentry)",
|
|
109
|
-
"fr": "assurez-vous que la requête de message est une chaîne (Sentry)",
|
|
110
|
-
"it": "assicurati che la query del messaggio sia una stringa (Sentry)",
|
|
111
|
-
"es": "asegúrese de que la consulta del mensaje sea una cadena (Sentry)",
|
|
112
|
-
"pl": "upewnij się, że zapytanie o wiadomość jest ciągiem (Sentry)",
|
|
113
|
-
"zh-cn": "确保消息查询是字符串(Sentry)"
|
|
114
114
|
}
|
|
115
115
|
},
|
|
116
116
|
"mode": "daemon",
|
|
@@ -197,7 +197,7 @@
|
|
|
197
197
|
"pl": "Ta nowa wersja wprowadza kilka zmian w sposobie rejestrowania wartości, ponieważ naprawiliśmy kilka problemów i dodaliśmy nowe funkcje. W szczególności sprawdź zdefiniowane ustawienia „odbicia” i „czasu blokowania” w punktach danych, jeśli wartości nie są rejestrowane zgodnie z oczekiwaniami i upewnij się, że ustawienia mają sens. Aby uzyskać więcej informacji, zapoznaj się z dziennikiem zmian i Readme.",
|
|
198
198
|
"zh-cn": "这个新版本引入了一些更改值的记录方式,因为我们修复了几个问题并添加了新功能。如果未按预期记录值,请特别检查数据点中定义的“去抖动”和“阻塞时间”设置,并确保设置有意义。有关更多详细信息,请参阅更改日志和自述文件。"
|
|
199
199
|
},
|
|
200
|
-
"link": "https://github.com/ioBroker/ioBroker.sql/blob/master/
|
|
200
|
+
"link": "https://github.com/ioBroker/ioBroker.sql/blob/master/README.md#settings",
|
|
201
201
|
"level": "warn",
|
|
202
202
|
"linkText": {
|
|
203
203
|
"en": "Readme",
|
package/lib/aggregate.js
CHANGED
|
@@ -142,6 +142,11 @@ function aggregationLogic(data, index, options) {
|
|
|
142
142
|
log = options.log || console.log;
|
|
143
143
|
}
|
|
144
144
|
|
|
145
|
+
if (!options.result[index]) {
|
|
146
|
+
log(`${options.logId} Data index ${index} not initialized, ignore!`);
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
|
|
145
150
|
if (options.aggregate !== 'minmax' && !options.result[index].val.ts) {
|
|
146
151
|
options.result[index].val.ts = Math.round(options.start + (((index - 1) + 0.5) * options.step));
|
|
147
152
|
}
|
package/lib/mssql.js
CHANGED
|
@@ -43,6 +43,8 @@ exports.insert = function (dbname, index, values) {
|
|
|
43
43
|
value.state.val = "NULL";
|
|
44
44
|
} else if (value.db === "ts_string") {
|
|
45
45
|
value.state.val = "'" + value.state.val.toString().replace(/'/g, '') + "'";
|
|
46
|
+
} else if (value.db === "ts_bool") {
|
|
47
|
+
value.state.val = value.state.val ? 1 : 0;
|
|
46
48
|
}
|
|
47
49
|
|
|
48
50
|
if (value.db === 'ts_counter') {
|
package/main.js
CHANGED
|
@@ -54,6 +54,9 @@ let reconnectTimeout = null;
|
|
|
54
54
|
let testConnectTimeout = null;
|
|
55
55
|
let dpOverviewTimeout = null;
|
|
56
56
|
let bufferChecker = null;
|
|
57
|
+
let activeConnections = 0;
|
|
58
|
+
let poolBorrowGuard = []; // required until https://github.com/intellinote/sql-client/issues/7 is fixed
|
|
59
|
+
const logConnectionUsage = true;
|
|
57
60
|
|
|
58
61
|
function isEqual(a, b) {
|
|
59
62
|
//console.log('Compare ' + JSON.stringify(a) + ' with ' + JSON.stringify(b));
|
|
@@ -239,6 +242,13 @@ function borrowClientFromPool(callback) {
|
|
|
239
242
|
}
|
|
240
243
|
setConnected(true);
|
|
241
244
|
|
|
245
|
+
if (activeConnections >= adapter.config.maxConnections) {
|
|
246
|
+
logConnectionUsage && adapter.log.debug(`Borrow connection not possible: ${activeConnections} >= Max - Store for Later`);
|
|
247
|
+
poolBorrowGuard.push(callback);
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
activeConnections++;
|
|
251
|
+
logConnectionUsage && adapter.log.debug(`Borrow connection from pool: ${activeConnections} now`);
|
|
242
252
|
clientPool.borrow((err, client) => {
|
|
243
253
|
if (!err && client) {
|
|
244
254
|
// make sure we always have at least one error listener to prevent crashes
|
|
@@ -246,6 +256,8 @@ function borrowClientFromPool(callback) {
|
|
|
246
256
|
client.on('error', err =>
|
|
247
257
|
adapter.log.warn(`SQL client error: ${err}`));
|
|
248
258
|
}
|
|
259
|
+
} else if (!client) {
|
|
260
|
+
activeConnections--;
|
|
249
261
|
}
|
|
250
262
|
|
|
251
263
|
callback(err, client);
|
|
@@ -253,14 +265,31 @@ function borrowClientFromPool(callback) {
|
|
|
253
265
|
}
|
|
254
266
|
|
|
255
267
|
function returnClientToPool(client) {
|
|
256
|
-
|
|
268
|
+
if (client) {
|
|
269
|
+
activeConnections--;
|
|
270
|
+
}
|
|
271
|
+
logConnectionUsage && adapter.log.debug(`Return connection to pool: ${activeConnections} now`);
|
|
272
|
+
if (clientPool && client) {
|
|
273
|
+
if (poolBorrowGuard.length) {
|
|
274
|
+
activeConnections++;
|
|
275
|
+
logConnectionUsage && adapter.log.debug(`Borrow returned connection directly: ${activeConnections} now`);
|
|
276
|
+
const callback = poolBorrowGuard.shift();
|
|
277
|
+
callback(null, client);
|
|
278
|
+
} else {
|
|
279
|
+
try {
|
|
280
|
+
clientPool.return(client);
|
|
281
|
+
} catch (err) {
|
|
282
|
+
// Ignore
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
}
|
|
257
286
|
}
|
|
258
287
|
|
|
259
288
|
function reInit(id, realId, formerAliasId, obj) {
|
|
260
289
|
|
|
261
290
|
// maxLength
|
|
262
291
|
if (!obj.common.custom[adapter.namespace].maxLength && obj.common.custom[adapter.namespace].maxLength !== '0' && obj.common.custom[adapter.namespace].maxLength !== 0) {
|
|
263
|
-
obj.common.custom[adapter.namespace].maxLength = parseInt(adapter.config.maxLength, 10) ||
|
|
292
|
+
obj.common.custom[adapter.namespace].maxLength = parseInt(adapter.config.maxLength, 10) || 0;
|
|
264
293
|
} else {
|
|
265
294
|
obj.common.custom[adapter.namespace].maxLength = parseInt(obj.common.custom[adapter.namespace].maxLength, 10);
|
|
266
295
|
}
|
|
@@ -383,6 +412,7 @@ function reInit(id, realId, formerAliasId, obj) {
|
|
|
383
412
|
const inFlight = sqlDPs[id] ? sqlDPs[id].inFlight: null;
|
|
384
413
|
const timeout = sqlDPs[id] ? sqlDPs[id].timeout : null;
|
|
385
414
|
const ts = sqlDPs[id] ? sqlDPs[id].ts : null;
|
|
415
|
+
const lastCheck = sqlDPs[id] ? sqlDPs[id].lastCheck : null;
|
|
386
416
|
|
|
387
417
|
sqlDPs[id] = obj.common.custom;
|
|
388
418
|
sqlDPs[id].state = state;
|
|
@@ -391,9 +421,11 @@ function reInit(id, realId, formerAliasId, obj) {
|
|
|
391
421
|
sqlDPs[id].timeout = timeout;
|
|
392
422
|
sqlDPs[id].ts = ts;
|
|
393
423
|
sqlDPs[id].realId = realId;
|
|
424
|
+
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
|
|
425
|
+
;
|
|
394
426
|
|
|
395
427
|
// changesRelogInterval
|
|
396
|
-
if (sqlDPs[id][adapter.namespace].changesRelogInterval > 0) {
|
|
428
|
+
if (sqlDPs[id][adapter.namespace].changesOnly && sqlDPs[id][adapter.namespace].changesRelogInterval > 0) {
|
|
397
429
|
sqlDPs[id].relogTimeout = setTimeout(reLogHelper, (sqlDPs[id][adapter.namespace].changesRelogInterval * 500 * Math.random()) + sqlDPs[id][adapter.namespace].changesRelogInterval * 500, id);
|
|
398
430
|
}
|
|
399
431
|
|
|
@@ -430,7 +462,7 @@ function connect(callback) {
|
|
|
430
462
|
};
|
|
431
463
|
|
|
432
464
|
if (adapter.config.maxConnections) {
|
|
433
|
-
params.max_active = adapter.config.maxConnections;
|
|
465
|
+
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
|
|
434
466
|
params.max_wait = 10000; // hard code for now
|
|
435
467
|
params.when_exhausted = 'block';
|
|
436
468
|
}
|
|
@@ -526,6 +558,7 @@ function connect(callback) {
|
|
|
526
558
|
clientPool = new SQL[`${clients[adapter.config.dbtype].name}Pool`](params);
|
|
527
559
|
|
|
528
560
|
return clientPool.open(err => {
|
|
561
|
+
activeConnections = 0;
|
|
529
562
|
if (err) {
|
|
530
563
|
clientPool = null;
|
|
531
564
|
setConnected(false);
|
|
@@ -546,6 +579,7 @@ function connect(callback) {
|
|
|
546
579
|
adapter.log.error(ex.stack);
|
|
547
580
|
}
|
|
548
581
|
clientPool = null;
|
|
582
|
+
activeConnections = 0;
|
|
549
583
|
setConnected(false);
|
|
550
584
|
reconnectTimeout && clearTimeout(reconnectTimeout);
|
|
551
585
|
reconnectTimeout = setTimeout(() => connect(callback), 30000);
|
|
@@ -729,6 +763,7 @@ function _userQuery(msg, callback) {
|
|
|
729
763
|
borrowClientFromPool((err, client) => {
|
|
730
764
|
if (err) {
|
|
731
765
|
adapter.sendTo(msg.from, msg.command, {error: err.toString()}, msg.callback);
|
|
766
|
+
returnClientToPool(client);
|
|
732
767
|
callback && callback();
|
|
733
768
|
} else {
|
|
734
769
|
client.execute(msg.message, (err, rows /* , fields */) => {
|
|
@@ -773,6 +808,7 @@ function oneScript(script, cb) {
|
|
|
773
808
|
borrowClientFromPool((err, client) => {
|
|
774
809
|
if (err || !client) {
|
|
775
810
|
clientPool && clientPool.close();
|
|
811
|
+
activeConnections = 0;
|
|
776
812
|
clientPool = null;
|
|
777
813
|
setConnected(false);
|
|
778
814
|
adapter.log.error(err);
|
|
@@ -859,6 +895,7 @@ function finish(callback) {
|
|
|
859
895
|
function allFinished() {
|
|
860
896
|
if (clientPool) {
|
|
861
897
|
clientPool.close();
|
|
898
|
+
activeConnections = 0;
|
|
862
899
|
clientPool = null;
|
|
863
900
|
setConnected(false);
|
|
864
901
|
}
|
|
@@ -992,6 +1029,7 @@ function finish(callback) {
|
|
|
992
1029
|
if (!dpcount && callback) {
|
|
993
1030
|
if (clientPool) {
|
|
994
1031
|
clientPool.close();
|
|
1032
|
+
activeConnections = 0;
|
|
995
1033
|
clientPool = null;
|
|
996
1034
|
setConnected(false);
|
|
997
1035
|
}
|
|
@@ -1080,10 +1118,11 @@ function processStartValues(callback) {
|
|
|
1080
1118
|
});
|
|
1081
1119
|
}
|
|
1082
1120
|
else {
|
|
1121
|
+
const now = Date.now();
|
|
1083
1122
|
pushHistory(task.id, {
|
|
1084
1123
|
val: null,
|
|
1085
|
-
ts: task.now ||
|
|
1086
|
-
lc: task.now ||
|
|
1124
|
+
ts: task.now || now,
|
|
1125
|
+
lc: task.now || now,
|
|
1087
1126
|
ack: true,
|
|
1088
1127
|
q: 0x40,
|
|
1089
1128
|
from: `system.adapter.${adapter.namespace}`
|
|
@@ -1091,7 +1130,7 @@ function processStartValues(callback) {
|
|
|
1091
1130
|
|
|
1092
1131
|
setImmediate(processStartValues);
|
|
1093
1132
|
}
|
|
1094
|
-
if (sqlDPs[task.id][adapter.namespace] && sqlDPs[task.id][adapter.namespace].changesRelogInterval > 0) {
|
|
1133
|
+
if (sqlDPs[task.id][adapter.namespace] && sqlDPs[task.id][adapter.namespace].changesOnly && sqlDPs[task.id][adapter.namespace].changesRelogInterval > 0) {
|
|
1095
1134
|
sqlDPs[task.id].relogTimeout && clearTimeout(sqlDPs[task.id].relogTimeout);
|
|
1096
1135
|
sqlDPs[task.id].relogTimeout = setTimeout(reLogHelper, (sqlDPs[task.id][adapter.namespace].changesRelogInterval * 500 * Math.random()) + sqlDPs[task.id][adapter.namespace].changesRelogInterval * 500, task.id);
|
|
1097
1136
|
}
|
|
@@ -1262,7 +1301,7 @@ function pushHistory(id, state, timerRelog) {
|
|
|
1262
1301
|
sqlDPs[id].lastLogTime = state.ts;
|
|
1263
1302
|
settings.enableDebugLogs && adapter.log.debug(`Value logged ${id}, value=${sqlDPs[id].state.val}, ts=${sqlDPs[id].state.ts}`);
|
|
1264
1303
|
pushHelper(id);
|
|
1265
|
-
if (settings.changesRelogInterval > 0) {
|
|
1304
|
+
if (settings.changesOnly && settings.changesRelogInterval > 0) {
|
|
1266
1305
|
sqlDPs[id].relogTimeout = setTimeout(reLogHelper, settings.changesRelogInterval * 1000, id);
|
|
1267
1306
|
}
|
|
1268
1307
|
}, settings.debounceTime, id, state);
|
|
@@ -1274,7 +1313,7 @@ function pushHistory(id, state, timerRelog) {
|
|
|
1274
1313
|
|
|
1275
1314
|
settings.enableDebugLogs && adapter.log.debug(`Value logged ${id}, value=${sqlDPs[id].state.val}, ts=${sqlDPs[id].state.ts}`);
|
|
1276
1315
|
pushHelper(id, state);
|
|
1277
|
-
if (settings.changesRelogInterval > 0) {
|
|
1316
|
+
if (settings.changesOnly && settings.changesRelogInterval > 0) {
|
|
1278
1317
|
sqlDPs[id].relogTimeout = setTimeout(reLogHelper, settings.changesRelogInterval * 1000, id);
|
|
1279
1318
|
}
|
|
1280
1319
|
}
|
|
@@ -1306,7 +1345,7 @@ function reLogHelper(_id) {
|
|
|
1306
1345
|
}
|
|
1307
1346
|
}
|
|
1308
1347
|
|
|
1309
|
-
function pushHelper(_id, state) {
|
|
1348
|
+
function pushHelper(_id, state, cb) {
|
|
1310
1349
|
if (!sqlDPs[_id] || (!sqlDPs[_id].state && !state)) {
|
|
1311
1350
|
return;
|
|
1312
1351
|
}
|
|
@@ -1314,45 +1353,42 @@ function pushHelper(_id, state) {
|
|
|
1314
1353
|
state = sqlDPs[_id].state;
|
|
1315
1354
|
}
|
|
1316
1355
|
|
|
1317
|
-
const _settings = sqlDPs[_id][adapter.namespace];
|
|
1356
|
+
const _settings = sqlDPs[_id] && sqlDPs[_id][adapter.namespace] || {};
|
|
1318
1357
|
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
state.val = JSON.stringify(state.val);
|
|
1323
|
-
}
|
|
1358
|
+
if (state.val !== null && (typeof state.val === 'object' || typeof state.val === 'undefined')) {
|
|
1359
|
+
state.val = JSON.stringify(state.val);
|
|
1360
|
+
}
|
|
1324
1361
|
|
|
1325
|
-
|
|
1326
|
-
|
|
1362
|
+
if (state.val !== null && state.val !== undefined) {
|
|
1363
|
+
_settings.enableDebugLogs && adapter.log.debug(`Datatype ${_id}: Currently: ${typeof state.val}, StorageType: ${_settings.storageType}`);
|
|
1327
1364
|
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
}
|
|
1365
|
+
if (typeof state.val === 'string' && _settings.storageType !== 'String') {
|
|
1366
|
+
_settings.enableDebugLogs && adapter.log.debug(`Do Automatic Datatype conversion for ${_id}`);
|
|
1367
|
+
if (isFinite(state.val)) {
|
|
1368
|
+
state.val = parseFloat(state.val);
|
|
1369
|
+
} else if (state.val === 'true') {
|
|
1370
|
+
state.val = true;
|
|
1371
|
+
} else if (state.val === 'false') {
|
|
1372
|
+
state.val = false;
|
|
1337
1373
|
}
|
|
1374
|
+
}
|
|
1338
1375
|
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
}
|
|
1347
|
-
} else if (_settings.storageType === 'Boolean' && typeof state.val !== 'boolean') {
|
|
1348
|
-
state.val = !!state.val;
|
|
1376
|
+
if (_settings.storageType === 'String' && typeof state.val !== 'string') {
|
|
1377
|
+
state.val = state.val.toString();
|
|
1378
|
+
} else if (_settings.storageType === 'Number' && typeof state.val !== 'number') {
|
|
1379
|
+
if (typeof state.val === 'boolean') {
|
|
1380
|
+
state.val = state.val ? 1 : 0;
|
|
1381
|
+
} else {
|
|
1382
|
+
return adapter.log.info(`Do not store value "${state.val}" for ${_id} because no number`);
|
|
1349
1383
|
}
|
|
1350
|
-
} else {
|
|
1351
|
-
|
|
1384
|
+
} else if (_settings.storageType === 'Boolean' && typeof state.val !== 'boolean') {
|
|
1385
|
+
state.val = !!state.val;
|
|
1352
1386
|
}
|
|
1353
|
-
|
|
1354
|
-
|
|
1387
|
+
} else {
|
|
1388
|
+
_settings.enableDebugLogs && adapter.log.debug(`Datatype ${_id}: Currently: null`);
|
|
1355
1389
|
}
|
|
1390
|
+
|
|
1391
|
+
pushValueIntoDB(_id, state, cb);
|
|
1356
1392
|
}
|
|
1357
1393
|
|
|
1358
1394
|
function getAllIds(cb) {
|
|
@@ -1361,6 +1397,7 @@ function getAllIds(cb) {
|
|
|
1361
1397
|
|
|
1362
1398
|
borrowClientFromPool((err, client) => {
|
|
1363
1399
|
if (err) {
|
|
1400
|
+
returnClientToPool(client);
|
|
1364
1401
|
return cb && cb(err);
|
|
1365
1402
|
}
|
|
1366
1403
|
|
|
@@ -1392,6 +1429,7 @@ function getAllFroms(cb) {
|
|
|
1392
1429
|
|
|
1393
1430
|
borrowClientFromPool((err, client) => {
|
|
1394
1431
|
if (err) {
|
|
1432
|
+
returnClientToPool(client);
|
|
1395
1433
|
return cb && cb(err);
|
|
1396
1434
|
}
|
|
1397
1435
|
|
|
@@ -1419,6 +1457,7 @@ function _checkRetention(query, cb) {
|
|
|
1419
1457
|
|
|
1420
1458
|
borrowClientFromPool((err, client) => {
|
|
1421
1459
|
if (err) {
|
|
1460
|
+
returnClientToPool(client);
|
|
1422
1461
|
adapter.log.error(err);
|
|
1423
1462
|
cb && cb();
|
|
1424
1463
|
} else {
|
|
@@ -1433,8 +1472,7 @@ function _checkRetention(query, cb) {
|
|
|
1433
1472
|
|
|
1434
1473
|
function checkRetention(id) {
|
|
1435
1474
|
if (sqlDPs[id] && sqlDPs[id][adapter.namespace] && sqlDPs[id][adapter.namespace].retention) {
|
|
1436
|
-
const
|
|
1437
|
-
const dt = d.getTime();
|
|
1475
|
+
const dt = Date.now();
|
|
1438
1476
|
// check every 6 hours
|
|
1439
1477
|
if (!sqlDPs[id].lastCheck || dt - sqlDPs[id].lastCheck >= 21600000/* 6 hours */) {
|
|
1440
1478
|
sqlDPs[id].lastCheck = dt;
|
|
@@ -1453,7 +1491,7 @@ function checkRetention(id) {
|
|
|
1453
1491
|
tasks.push({operation: 'delete', query});
|
|
1454
1492
|
|
|
1455
1493
|
// delete counters too
|
|
1456
|
-
if (sqlDPs[id].type ===
|
|
1494
|
+
if (sqlDPs[id] && sqlDPs[id].type === 0) { // 0 === number
|
|
1457
1495
|
const query = SQLFuncs.retention(adapter.config.dbname, sqlDPs[id].index, 'ts_counter', sqlDPs[id][adapter.namespace].retention);
|
|
1458
1496
|
tasks.push({operation: 'delete', query});
|
|
1459
1497
|
}
|
|
@@ -1462,7 +1500,7 @@ function checkRetention(id) {
|
|
|
1462
1500
|
} else {
|
|
1463
1501
|
_checkRetention(query, () => {
|
|
1464
1502
|
// delete counters too
|
|
1465
|
-
if (sqlDPs[id].type ===
|
|
1503
|
+
if (sqlDPs[id] && sqlDPs[id].type === 0) { // 0 === number
|
|
1466
1504
|
const query = SQLFuncs.retention(adapter.config.dbname, sqlDPs[id].index, 'ts_counter', sqlDPs[id][adapter.namespace].retention);
|
|
1467
1505
|
_checkRetention(query);
|
|
1468
1506
|
}
|
|
@@ -1478,6 +1516,7 @@ function _insertValueIntoDB(query, id, cb) {
|
|
|
1478
1516
|
|
|
1479
1517
|
borrowClientFromPool((err, client) => {
|
|
1480
1518
|
if (err) {
|
|
1519
|
+
returnClientToPool(client);
|
|
1481
1520
|
adapter.log.error(err);
|
|
1482
1521
|
cb && cb(); // BF asked (2021.12.14): may be return here err?
|
|
1483
1522
|
} else {
|
|
@@ -1499,6 +1538,7 @@ function _executeQuery(query, id, cb) {
|
|
|
1499
1538
|
|
|
1500
1539
|
borrowClientFromPool((err, client) => {
|
|
1501
1540
|
if (err) {
|
|
1541
|
+
returnClientToPool(client);
|
|
1502
1542
|
adapter.log.error(err);
|
|
1503
1543
|
cb && cb();
|
|
1504
1544
|
} else {
|
|
@@ -1515,7 +1555,7 @@ function processReadTypes() {
|
|
|
1515
1555
|
if (tasksReadType && tasksReadType.length) {
|
|
1516
1556
|
const task = tasksReadType[0];
|
|
1517
1557
|
|
|
1518
|
-
if (!sqlDPs[task.id]
|
|
1558
|
+
if (!sqlDPs[task.id]) {
|
|
1519
1559
|
adapter.log.warn(`Ignore type lookup for ${task.id} because not enabled anymore`);
|
|
1520
1560
|
task.cb && task.cb(`Ignore type lookup for ${task.id} because not enabled anymore`)
|
|
1521
1561
|
task.cb = null;
|
|
@@ -1525,22 +1565,24 @@ function processReadTypes() {
|
|
|
1525
1565
|
});
|
|
1526
1566
|
}
|
|
1527
1567
|
|
|
1528
|
-
adapter.log.debug(`Type set in Def for ${task.id}: ${sqlDPs[task.id][adapter.namespace].storageType}`);
|
|
1568
|
+
adapter.log.debug(`Type set in Def for ${task.id}: ${sqlDPs[task.id][adapter.namespace] && sqlDPs[task.id][adapter.namespace].storageType}`);
|
|
1529
1569
|
|
|
1530
|
-
if (sqlDPs[task.id][adapter.namespace].storageType) {
|
|
1570
|
+
if (sqlDPs[task.id][adapter.namespace] && sqlDPs[task.id][adapter.namespace].storageType) {
|
|
1531
1571
|
sqlDPs[task.id].type = types[sqlDPs[task.id][adapter.namespace].storageType.toLowerCase()];
|
|
1532
1572
|
adapter.log.debug(`Type (from Def) for ${task.id}: ${sqlDPs[task.id].type}`);
|
|
1533
1573
|
processVerifyTypes(task);
|
|
1534
1574
|
} else if (sqlDPs[task.id].dbtype !== undefined) {
|
|
1535
1575
|
sqlDPs[task.id].type = sqlDPs[task.id].dbtype;
|
|
1536
|
-
sqlDPs[task.id][adapter.namespace]
|
|
1576
|
+
if (sqlDPs[task.id][adapter.namespace]) {
|
|
1577
|
+
sqlDPs[task.id][adapter.namespace].storageType = storageTypes[sqlDPs[task.id].type];
|
|
1578
|
+
}
|
|
1537
1579
|
adapter.log.debug(`Type (from DB-Type) for ${task.id}: ${sqlDPs[task.id].type}`);
|
|
1538
1580
|
processVerifyTypes(task);
|
|
1539
1581
|
} else {
|
|
1540
1582
|
adapter.getForeignObject(sqlDPs[task.id].realId, (err, obj) => {
|
|
1541
|
-
err && adapter.log.warn(`Error while get Object for Def: ${err}`);
|
|
1583
|
+
err && adapter.log.warn(`Error while get Object for Def for ${sqlDPs[task.id].realId}: ${err}`);
|
|
1542
1584
|
|
|
1543
|
-
if (!sqlDPs[task.id]
|
|
1585
|
+
if (!sqlDPs[task.id]) {
|
|
1544
1586
|
adapter.log.warn(`Ignore type lookup for ${task.id} because not enabled anymore`);
|
|
1545
1587
|
task.cb && task.cb(`Ignore type lookup for ${task.id} because not enabled anymore`)
|
|
1546
1588
|
task.cb = null;
|
|
@@ -1553,12 +1595,14 @@ function processReadTypes() {
|
|
|
1553
1595
|
if (obj && obj.common && obj.common.type && types[obj.common.type.toLowerCase()] !== undefined) {
|
|
1554
1596
|
adapter.log.debug(`${obj.common.type.toLowerCase()} / ${types[obj.common.type.toLowerCase()]} / ${JSON.stringify(obj.common)}`);
|
|
1555
1597
|
sqlDPs[task.id].type = types[obj.common.type.toLowerCase()];
|
|
1556
|
-
sqlDPs[task.id][adapter.namespace]
|
|
1598
|
+
if (sqlDPs[task.id][adapter.namespace]) {
|
|
1599
|
+
sqlDPs[task.id][adapter.namespace].storageType = storageTypes[sqlDPs[task.id].type];
|
|
1600
|
+
}
|
|
1557
1601
|
adapter.log.debug(`Type (from Obj) for ${task.id}: ${sqlDPs[task.id].type}`);
|
|
1558
1602
|
processVerifyTypes(task);
|
|
1559
1603
|
} else if (sqlDPs[task.id].type === undefined) {
|
|
1560
1604
|
adapter.getForeignState(sqlDPs[task.id].realId, (err, state) => {
|
|
1561
|
-
if (!sqlDPs[task.id]
|
|
1605
|
+
if (!sqlDPs[task.id]) {
|
|
1562
1606
|
adapter.log.warn(`Ignore type lookup for ${task.id} because not enabled anymore`);
|
|
1563
1607
|
task.cb && task.cb(`Ignore type lookup for ${task.id} because not enabled anymore`)
|
|
1564
1608
|
task.cb = null;
|
|
@@ -1568,12 +1612,15 @@ function processReadTypes() {
|
|
|
1568
1612
|
});
|
|
1569
1613
|
}
|
|
1570
1614
|
|
|
1571
|
-
if (err) {
|
|
1572
|
-
adapter.log.warn(`
|
|
1573
|
-
|
|
1574
|
-
}
|
|
1615
|
+
if (err && task.state) {
|
|
1616
|
+
adapter.log.warn(`Fallback to type of current state value because no other valid type found`);
|
|
1617
|
+
state = task.state;
|
|
1618
|
+
}
|
|
1619
|
+
if (state && state.val !== null && state.val !== undefined && types[typeof state.val] !== undefined) {
|
|
1575
1620
|
sqlDPs[task.id].type = types[typeof state.val];
|
|
1576
|
-
sqlDPs[task.id][adapter.namespace]
|
|
1621
|
+
if (sqlDPs[task.id][adapter.namespace]) {
|
|
1622
|
+
sqlDPs[task.id][adapter.namespace].storageType = storageTypes[sqlDPs[task.id].type];
|
|
1623
|
+
}
|
|
1577
1624
|
} else {
|
|
1578
1625
|
adapter.log.warn(`Store data for ${task.id} as string because no other valid type found (${state ? (typeof state.val) : 'state not existing'})`);
|
|
1579
1626
|
sqlDPs[task.id].type = 1; // string
|
|
@@ -1603,6 +1650,7 @@ function processVerifyTypes(task) {
|
|
|
1603
1650
|
|
|
1604
1651
|
return borrowClientFromPool((err, client) => {
|
|
1605
1652
|
if (err) {
|
|
1653
|
+
returnClientToPool(client);
|
|
1606
1654
|
return processVerifyTypes(task);
|
|
1607
1655
|
}
|
|
1608
1656
|
|
|
@@ -1628,6 +1676,9 @@ function processVerifyTypes(task) {
|
|
|
1628
1676
|
}
|
|
1629
1677
|
|
|
1630
1678
|
function prepareTaskReadDbId(id, state, isCounter, cb) {
|
|
1679
|
+
if (!sqlDPs[id]) {
|
|
1680
|
+
return cb && cb(`${id} not active any more`);
|
|
1681
|
+
}
|
|
1631
1682
|
const type = sqlDPs[id].type;
|
|
1632
1683
|
|
|
1633
1684
|
if (type === undefined) { // Can not happen anymore
|
|
@@ -1730,7 +1781,12 @@ function prepareTaskCheckTypeAndDbId(id, state, isCounter, cb) {
|
|
|
1730
1781
|
prepareTaskReadDbId(id, state, isCounter, cb)
|
|
1731
1782
|
} else {
|
|
1732
1783
|
// read type from DB
|
|
1733
|
-
tasksReadType.push({id, state, cb:
|
|
1784
|
+
tasksReadType.push({id, state, cb: err => {
|
|
1785
|
+
if (err) {
|
|
1786
|
+
return cb && cb(err);
|
|
1787
|
+
}
|
|
1788
|
+
prepareTaskReadDbId(id, state, isCounter, cb);
|
|
1789
|
+
}});
|
|
1734
1790
|
|
|
1735
1791
|
tasksReadType.length === 1 && processReadTypes();
|
|
1736
1792
|
}
|
|
@@ -1754,6 +1810,9 @@ function pushValueIntoDB(id, state, isCounter, storeInCacheOnly, cb) {
|
|
|
1754
1810
|
adapter.log.debug(`pushValueIntoDB called for ${id} (type: ${sqlDPs[id].type}, ID: ${sqlDPs[id].index}) and state: ${JSON.stringify(state)}`);
|
|
1755
1811
|
|
|
1756
1812
|
prepareTaskCheckTypeAndDbId(id, state, isCounter, err => {
|
|
1813
|
+
if (!sqlDPs[id]) {
|
|
1814
|
+
return cb && cb()
|
|
1815
|
+
}
|
|
1757
1816
|
adapter.log.debug(`pushValueIntoDB-prepareTaskCheckTypeAndDbId RESULT for ${id} (type: ${sqlDPs[id].type}, ID: ${sqlDPs[id].index}) and state: ${JSON.stringify(state)}: ${err}`);
|
|
1758
1817
|
if (err) {
|
|
1759
1818
|
return cb && cb(err);
|
|
@@ -1774,8 +1833,9 @@ function pushValueIntoDB(id, state, isCounter, storeInCacheOnly, cb) {
|
|
|
1774
1833
|
|
|
1775
1834
|
sqlDPs[id].list.push({state, from: from[state.from] || 0, db: isCounter ? 'ts_counter' : dbNames[type]});
|
|
1776
1835
|
|
|
1777
|
-
const _settings = sqlDPs[id][adapter.namespace];
|
|
1778
|
-
|
|
1836
|
+
const _settings = sqlDPs[id][adapter.namespace] || {};
|
|
1837
|
+
const maxLength = _settings.maxLength !== undefined ? _settings.maxLength : parseInt(adapter.config.maxLength, 10) || 0;
|
|
1838
|
+
if ((cb || _settings && sqlDPs[id].list.length > maxLength) && !storeInCacheOnly) {
|
|
1779
1839
|
storeCached(id, cb);
|
|
1780
1840
|
} else if (cb && storeInCacheOnly) {
|
|
1781
1841
|
setImmediate(cb);
|
|
@@ -1790,7 +1850,7 @@ function storeCached(onlyId, cb) {
|
|
|
1790
1850
|
continue;
|
|
1791
1851
|
}
|
|
1792
1852
|
|
|
1793
|
-
const _settings = sqlDPs[id][adapter.namespace];
|
|
1853
|
+
const _settings = sqlDPs[id][adapter.namespace] || {};
|
|
1794
1854
|
if (_settings && sqlDPs[id].list && sqlDPs[id].list.length) {
|
|
1795
1855
|
_settings.enableDebugLogs && adapter.log.debug(`inserting ${sqlDPs[id].list.length} entries from ${id} to DB`);
|
|
1796
1856
|
const inFlightId = `${id}_${Date.now()}_${Math.random()}`;
|
|
@@ -1912,10 +1972,15 @@ function getId(id, type, cb) {
|
|
|
1912
1972
|
|
|
1913
1973
|
borrowClientFromPool((err, client) => {
|
|
1914
1974
|
if (err) {
|
|
1975
|
+
returnClientToPool(client);
|
|
1915
1976
|
return cb && cb(err, id);
|
|
1916
1977
|
}
|
|
1917
1978
|
|
|
1918
1979
|
client.execute(query, (err, rows /* , fields */) => {
|
|
1980
|
+
if (!sqlDPs[id]) {
|
|
1981
|
+
returnClientToPool(client);
|
|
1982
|
+
return cb && cb(new Error(`ID ${id} no longer active`), id);
|
|
1983
|
+
}
|
|
1919
1984
|
if (rows && rows.rows) {
|
|
1920
1985
|
rows = rows.rows;
|
|
1921
1986
|
}
|
|
@@ -2004,6 +2069,7 @@ function getFrom(_from, cb) {
|
|
|
2004
2069
|
|
|
2005
2070
|
borrowClientFromPool((err, client) => {
|
|
2006
2071
|
if (err) {
|
|
2072
|
+
returnClientToPool(client);
|
|
2007
2073
|
return cb && cb(err, _from);
|
|
2008
2074
|
}
|
|
2009
2075
|
client.execute(query, (err, rows /* , fields */) => {
|
|
@@ -2132,10 +2198,10 @@ function getCachedData(options, callback) {
|
|
|
2132
2198
|
if (options.ack) {
|
|
2133
2199
|
cache[c].ack = !!cache[c].ack;
|
|
2134
2200
|
}
|
|
2135
|
-
if (cache[c].val
|
|
2201
|
+
if (typeof cache[c].val === 'number' && isFinite(cache[c].val) && options.round) {
|
|
2136
2202
|
cache[c].val = Math.round(cache[c].val * options.round) / options.round;
|
|
2137
2203
|
}
|
|
2138
|
-
if (sqlDPs[options.index].type === 2) {
|
|
2204
|
+
if (sqlDPs[options.index || options.id] && sqlDPs[options.index || options.id].type === 2) { // 2 === boolean
|
|
2139
2205
|
cache[c].val = !!cache[c].val;
|
|
2140
2206
|
}
|
|
2141
2207
|
if (options.addId && !cache[c].id && options.id) {
|
|
@@ -2156,6 +2222,7 @@ function _getDataFromDB(query, options, callback) {
|
|
|
2156
2222
|
|
|
2157
2223
|
borrowClientFromPool((err, client) => {
|
|
2158
2224
|
if (err) {
|
|
2225
|
+
returnClientToPool(client);
|
|
2159
2226
|
return callback && callback(err);
|
|
2160
2227
|
}
|
|
2161
2228
|
client.execute(query, (err, rows /* , fields */) => {
|
|
@@ -2175,10 +2242,10 @@ function _getDataFromDB(query, options, callback) {
|
|
|
2175
2242
|
if (options.ack) {
|
|
2176
2243
|
rows[c].ack = !!rows[c].ack;
|
|
2177
2244
|
}
|
|
2178
|
-
if (rows[c].val
|
|
2245
|
+
if (typeof rows[c].val === 'number' && isFinite(rows[c].val) && options.round) {
|
|
2179
2246
|
rows[c].val = Math.round(rows[c].val * options.round) / options.round;
|
|
2180
2247
|
}
|
|
2181
|
-
if (sqlDPs[options.index].type === 2) {
|
|
2248
|
+
if (sqlDPs[options.index || options.id] && sqlDPs[options.index || options.id].type === 2) { // 2 === boolean
|
|
2182
2249
|
rows[c].val = !!rows[c].val;
|
|
2183
2250
|
}
|
|
2184
2251
|
if (options.addId && !rows[c].id && options.id) {
|
|
@@ -2279,6 +2346,26 @@ function getHistory(msg) {
|
|
|
2279
2346
|
logId: (msg.message.id ? msg.message.id : 'all') + Date.now() + Math.random()
|
|
2280
2347
|
};
|
|
2281
2348
|
|
|
2349
|
+
try {
|
|
2350
|
+
if (options.start && typeof options.start !== 'number') {
|
|
2351
|
+
options.start = new Date(options.start).getTime();
|
|
2352
|
+
}
|
|
2353
|
+
} catch (err) {
|
|
2354
|
+
return adapter.sendTo(msg.from, msg.command, {
|
|
2355
|
+
error: 'Invalid call. Start date ' + JSON.stringify(options.start) + ' is not a valid date'
|
|
2356
|
+
}, msg.callback);
|
|
2357
|
+
}
|
|
2358
|
+
|
|
2359
|
+
try {
|
|
2360
|
+
if (options.end && typeof options.end !== 'number') {
|
|
2361
|
+
options.end = new Date(options.end).getTime();
|
|
2362
|
+
}
|
|
2363
|
+
} catch (err) {
|
|
2364
|
+
return adapter.sendTo(msg.from, msg.command, {
|
|
2365
|
+
error: 'Invalid call. End date ' + JSON.stringify(options.end) + ' is not a valid date'
|
|
2366
|
+
}, msg.callback);
|
|
2367
|
+
}
|
|
2368
|
+
|
|
2282
2369
|
if (!options.start && options.count) {
|
|
2283
2370
|
options.returnNewestEntries = true;
|
|
2284
2371
|
}
|
|
@@ -2315,6 +2402,7 @@ function getHistory(msg) {
|
|
|
2315
2402
|
options.integralUnit = 60;
|
|
2316
2403
|
}
|
|
2317
2404
|
|
|
2405
|
+
sqlDPs[options.id] = sqlDPs[options.id] || {};
|
|
2318
2406
|
const debugLog = options.debugLog = !!(sqlDPs[options.id] && sqlDPs[options.id][adapter.namespace] && sqlDPs[options.id][adapter.namespace].enableDebugLogs);
|
|
2319
2407
|
|
|
2320
2408
|
if (options.ignoreNull === 'true') options.ignoreNull = true; // include nulls and replace them with last value
|
|
@@ -2324,10 +2412,6 @@ function getHistory(msg) {
|
|
|
2324
2412
|
options.ignoreNull = false;
|
|
2325
2413
|
}
|
|
2326
2414
|
|
|
2327
|
-
if (!sqlDPs[options.id] || !sqlDPs[options.id][adapter.namespace]) {
|
|
2328
|
-
return commons.sendResponse(adapter, msg, options, `Logging not activated for ${options.id}`, startTime);
|
|
2329
|
-
}
|
|
2330
|
-
|
|
2331
2415
|
if (options.start > options.end) {
|
|
2332
2416
|
const _end = options.end;
|
|
2333
2417
|
options.end = options.start;
|
|
@@ -2403,31 +2487,32 @@ function getHistory(msg) {
|
|
|
2403
2487
|
}
|
|
2404
2488
|
// if not all data read
|
|
2405
2489
|
getDataFromDB(dbNames[type], options, (err, data) => {
|
|
2406
|
-
|
|
2407
|
-
|
|
2408
|
-
|
|
2409
|
-
|
|
2410
|
-
|
|
2411
|
-
|
|
2412
|
-
|
|
2413
|
-
|
|
2414
|
-
|
|
2415
|
-
if (options.
|
|
2416
|
-
|
|
2417
|
-
|
|
2418
|
-
data.
|
|
2419
|
-
|
|
2420
|
-
|
|
2421
|
-
|
|
2490
|
+
if (!err && data) {
|
|
2491
|
+
options.end = origEnd;
|
|
2492
|
+
if (options.aggregate === 'none' && options.count && options.returnNewestEntries) {
|
|
2493
|
+
cacheData = cacheData.reverse()
|
|
2494
|
+
data = cacheData.concat(data);
|
|
2495
|
+
} else {
|
|
2496
|
+
data = data.concat(cacheData);
|
|
2497
|
+
}
|
|
2498
|
+
debugLog && adapter.log.debug(`${options.logId} after getDataFromDB: length = ${data.length}`);
|
|
2499
|
+
if (options.count && data.length > options.count && options.aggregate === 'none' && !options.returnNewestEntries) {
|
|
2500
|
+
if (options.start) {
|
|
2501
|
+
for (let i = 0; i < data.length; i++) {
|
|
2502
|
+
if (data[i].ts < options.start) {
|
|
2503
|
+
data.splice(i, 1);
|
|
2504
|
+
i--;
|
|
2505
|
+
} else {
|
|
2506
|
+
break;
|
|
2507
|
+
}
|
|
2422
2508
|
}
|
|
2423
2509
|
}
|
|
2510
|
+
data = data.slice(0, options.count);
|
|
2511
|
+
options.debugLog && adapter.log.debug(`${options.logId} pre-cut data to ${options.count} oldest values`);
|
|
2424
2512
|
}
|
|
2425
|
-
data = data.slice(0, options.count);
|
|
2426
|
-
options.debugLog && adapter.log.debug(`${options.logId} pre-cut data to ${options.count} oldest values`);
|
|
2427
|
-
}
|
|
2428
|
-
|
|
2429
|
-
data.sort(sortByTs);
|
|
2430
2513
|
|
|
2514
|
+
data.sort(sortByTs);
|
|
2515
|
+
}
|
|
2431
2516
|
commons.sendResponse(adapter, msg, options, (err ? err.toString() : null) || data, startTime)
|
|
2432
2517
|
});
|
|
2433
2518
|
}
|
|
@@ -2764,7 +2849,30 @@ function deleteStateAll(msg) {
|
|
|
2764
2849
|
}, msg.callback);
|
|
2765
2850
|
}
|
|
2766
2851
|
|
|
2767
|
-
function
|
|
2852
|
+
function storeStatePushData(id, state, applyRules) {
|
|
2853
|
+
if (!state || typeof state !== 'object') {
|
|
2854
|
+
throw new Error(`State ${JSON.stringify(state)} for ${id} is not valid`);
|
|
2855
|
+
}
|
|
2856
|
+
|
|
2857
|
+
let pushFunc = applyRules ? pushHistory : pushHelper;
|
|
2858
|
+
if (!sqlDPs[id] || !sqlDPs[id][adapter.namespace]) {
|
|
2859
|
+
if (applyRules) {
|
|
2860
|
+
throw new Error(`history not enabled for ${id}, so can not apply the rules as requested`);
|
|
2861
|
+
}
|
|
2862
|
+
sqlDPs[id] = sqlDPs[id] || {};
|
|
2863
|
+
}
|
|
2864
|
+
return new Promise((resolve, reject) => {
|
|
2865
|
+
pushFunc(id, state , err => {
|
|
2866
|
+
if (err) {
|
|
2867
|
+
reject(new Error(`Error writing state for ${id}: ${err.message}, Data: ${JSON.stringify(state)}`));
|
|
2868
|
+
} else {
|
|
2869
|
+
resolve(true);
|
|
2870
|
+
}
|
|
2871
|
+
});
|
|
2872
|
+
});
|
|
2873
|
+
}
|
|
2874
|
+
|
|
2875
|
+
async function storeState(msg) {
|
|
2768
2876
|
if (!msg.message) {
|
|
2769
2877
|
adapter.log.error('storeState called with invalid data');
|
|
2770
2878
|
return adapter.sendTo(msg.from, msg.command, {
|
|
@@ -2772,45 +2880,59 @@ function storeState(msg) {
|
|
|
2772
2880
|
}, msg.callback);
|
|
2773
2881
|
}
|
|
2774
2882
|
|
|
2775
|
-
let
|
|
2776
|
-
|
|
2777
|
-
pushFunc = pushValueIntoDB;
|
|
2778
|
-
}
|
|
2779
|
-
|
|
2780
|
-
let id;
|
|
2883
|
+
let errors = [];
|
|
2884
|
+
let successCount = 0;
|
|
2781
2885
|
if (Array.isArray(msg.message)) {
|
|
2782
2886
|
adapter.log.debug(`storeState ${msg.message.length} items`);
|
|
2783
2887
|
for (let i = 0; i < msg.message.length; i++) {
|
|
2784
|
-
id = aliasMap[msg.message[i].id] ? aliasMap[msg.message[i].id] : msg.message[i].id;
|
|
2785
|
-
|
|
2786
|
-
|
|
2787
|
-
|
|
2788
|
-
|
|
2888
|
+
const id = aliasMap[msg.message[i].id] ? aliasMap[msg.message[i].id] : msg.message[i].id;
|
|
2889
|
+
try {
|
|
2890
|
+
await storeStatePushData(id, msg.message[i].state, msg.message.rules);
|
|
2891
|
+
successCount++;
|
|
2892
|
+
} catch (err) {
|
|
2893
|
+
errors.push(err.message);
|
|
2789
2894
|
}
|
|
2790
2895
|
}
|
|
2791
|
-
} else if (msg.message.
|
|
2896
|
+
} else if (msg.message.id && Array.isArray(msg.message.state)) {
|
|
2792
2897
|
adapter.log.debug(`storeState ${msg.message.state.length} items`);
|
|
2793
|
-
id = aliasMap[msg.message.id] ? aliasMap[msg.message.id] : msg.message.id;
|
|
2898
|
+
const id = aliasMap[msg.message.id] ? aliasMap[msg.message.id] : msg.message.id;
|
|
2794
2899
|
for (let j = 0; j < msg.message.state.length; j++) {
|
|
2795
|
-
|
|
2796
|
-
|
|
2797
|
-
|
|
2798
|
-
|
|
2900
|
+
try {
|
|
2901
|
+
await storeStatePushData(id, msg.message.state[j], msg.message.rules);
|
|
2902
|
+
successCount++;
|
|
2903
|
+
} catch (err) {
|
|
2904
|
+
errors.push(err.message);
|
|
2799
2905
|
}
|
|
2800
2906
|
}
|
|
2801
|
-
} else if (msg.message.id && msg.message.state
|
|
2907
|
+
} else if (msg.message.id && msg.message.state) {
|
|
2802
2908
|
adapter.log.debug('storeState 1 item');
|
|
2803
|
-
id = aliasMap[msg.message.id] ? aliasMap[msg.message.id] : msg.message.id;
|
|
2804
|
-
|
|
2909
|
+
const id = aliasMap[msg.message.id] ? aliasMap[msg.message.id] : msg.message.id;
|
|
2910
|
+
try {
|
|
2911
|
+
await storeStatePushData(id, msg.message.state, msg.message.rules);
|
|
2912
|
+
successCount++;
|
|
2913
|
+
} catch (err) {
|
|
2914
|
+
errors.push(err.message);
|
|
2915
|
+
}
|
|
2805
2916
|
} else {
|
|
2806
2917
|
adapter.log.error('storeState called with invalid data');
|
|
2807
2918
|
return adapter.sendTo(msg.from, msg.command, {
|
|
2808
2919
|
error: `Invalid call: ${JSON.stringify(msg)}`
|
|
2809
2920
|
}, msg.callback);
|
|
2810
2921
|
}
|
|
2922
|
+
if (errors.length) {
|
|
2923
|
+
adapter.log.warn(`storeState executed with ${errors.length} errors: ${errors.join(', ')}`);
|
|
2924
|
+
return adapter.sendTo(msg.from, msg.command, {
|
|
2925
|
+
error: `${errors.length} errors happened while storing data`,
|
|
2926
|
+
errors: errors,
|
|
2927
|
+
successCount
|
|
2928
|
+
}, msg.callback);
|
|
2929
|
+
}
|
|
2930
|
+
|
|
2931
|
+
adapter.log.debug(`storeState executed with ${successCount} states successfully`);
|
|
2811
2932
|
|
|
2812
2933
|
adapter.sendTo(msg.from, msg.command, {
|
|
2813
2934
|
success: true,
|
|
2935
|
+
successCount,
|
|
2814
2936
|
connected: !!clientPool
|
|
2815
2937
|
}, msg.callback);
|
|
2816
2938
|
}
|
|
@@ -2822,6 +2944,7 @@ function getDpOverview(msg) {
|
|
|
2822
2944
|
|
|
2823
2945
|
borrowClientFromPool((err, client) => {
|
|
2824
2946
|
if (err) {
|
|
2947
|
+
returnClientToPool(client);
|
|
2825
2948
|
return adapter.sendTo(msg.from, msg.command, {
|
|
2826
2949
|
error: `Cannot select ${query}: ${err}`
|
|
2827
2950
|
}, msg.callback);
|
|
@@ -3074,7 +3197,7 @@ function main() {
|
|
|
3074
3197
|
adapter.config.maxConnections = 100;
|
|
3075
3198
|
}
|
|
3076
3199
|
} else {
|
|
3077
|
-
adapter.config.maxConnections =
|
|
3200
|
+
adapter.config.maxConnections = 1; // SQLite does not support multiple connections
|
|
3078
3201
|
}
|
|
3079
3202
|
|
|
3080
3203
|
if (adapter.config.changesMinDelta !== null && adapter.config.changesMinDelta !== undefined) {
|
|
@@ -3183,7 +3306,7 @@ function main() {
|
|
|
3183
3306
|
|
|
3184
3307
|
// maxLength
|
|
3185
3308
|
if (!sqlDPs[id][adapter.namespace].maxLength && sqlDPs[id][adapter.namespace].maxLength !== '0' && sqlDPs[id][adapter.namespace].maxLength !== 0) {
|
|
3186
|
-
sqlDPs[id][adapter.namespace].maxLength = parseInt(adapter.config.maxLength, 10) ||
|
|
3309
|
+
sqlDPs[id][adapter.namespace].maxLength = parseInt(adapter.config.maxLength, 10) || 0;
|
|
3187
3310
|
} else {
|
|
3188
3311
|
sqlDPs[id][adapter.namespace].maxLength = parseInt(sqlDPs[id][adapter.namespace].maxLength, 10);
|
|
3189
3312
|
}
|
|
@@ -3289,7 +3412,7 @@ function main() {
|
|
|
3289
3412
|
}
|
|
3290
3413
|
|
|
3291
3414
|
// relogTimeout
|
|
3292
|
-
if (sqlDPs[id][adapter.namespace] && sqlDPs[id][adapter.namespace].changesRelogInterval > 0) {
|
|
3415
|
+
if (sqlDPs[id][adapter.namespace] && sqlDPs[id][adapter.namespace].changesOnly && sqlDPs[id][adapter.namespace].changesRelogInterval > 0) {
|
|
3293
3416
|
sqlDPs[id].relogTimeout && clearTimeout(sqlDPs[id].relogTimeout);
|
|
3294
3417
|
sqlDPs[id].relogTimeout = setTimeout(reLogHelper, (sqlDPs[id][adapter.namespace].changesRelogInterval * 500 * Math.random()) + sqlDPs[id][adapter.namespace].changesRelogInterval * 500, id);
|
|
3295
3418
|
}
|
|
@@ -3297,6 +3420,9 @@ function main() {
|
|
|
3297
3420
|
sqlDPs[id].realId = realId;
|
|
3298
3421
|
sqlDPs[id].list = sqlDPs[id].list || [];
|
|
3299
3422
|
sqlDPs[id].inFlight = sqlDPs[id].inFlight || {};
|
|
3423
|
+
|
|
3424
|
+
// randomize lastCheck to avoid all datapoints to be checked at same timepoint
|
|
3425
|
+
sqlDPs[id].lastCheck = Date.now() - Math.floor(Math.random() * 21600000/* 6 hours */);
|
|
3300
3426
|
}
|
|
3301
3427
|
}
|
|
3302
3428
|
}
|
package/package.json
CHANGED