iobroker.hass 1.2.0 → 1.4.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  The MIT License (MIT)
2
2
 
3
- Copyright (c) 2018-2022 bluefox <dogafox@gmail.com>
3
+ Copyright (c) 2018-2023 bluefox <dogafox@gmail.com>
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -18,10 +18,19 @@ This adapter allows the connecting of Home Assistant to ioBroker.
18
18
  Create a long term token in HASS and use it as PW (copy it also in the repeat field).
19
19
 
20
20
  Then it should read out all attributes for all devices. Services might be controllable (e.g. "turn_on"). To control services you have two options:
21
- * Set the state with an ack=false value which is not a string (e.g. Boolean true) then it will be triggered also in HASS without additional service data
22
- * Set the state with an ack=false String value which is a stringified JSON object to call the service and use the JSON object as service data
23
21
 
24
- For the last option on a light.turn_off with e.g. `{"transition":10,"flash":"short"}` these two service data details are sent with the call to HASS. The available fields with their data definition can be seen in the JSON definition of the ioBroker object in the native.fields section and would look like the following in the above example:
22
+ ### Set a direct value
23
+ Set the state with an ack=false value which is not a string (e.g. Boolean true) then it will be triggered also in HASS without additional service data. This will only work if the service has one field to be sent - then the value is sent as this field! If the service has more than one field you will find a warning in the log that provides more details about the fields taht are possible to be sent, e.g.
24
+
25
+ ```
26
+ Please make sure to provide a stringified JSON as value to set relevant fields! Please refer to the Readme for details!
27
+ Allowed field keys are: temperature, target_temp_high, target_temp_low, hvac_mode
28
+ ```
29
+
30
+ ### Set a stringified JSON to provide one or multiple fields
31
+ Set the state with an ack=false String value which is a stringified JSON object to call the service and use the JSON object as service data
32
+
33
+ For the last option on a light.turn_off with e.g. `{"transition":10,"flash":"short"}` these two service data details are sent with the call to HASS. The available fields with their exact data definition can be seen in the JSON definition of the ioBroker object in the native.fields section and would look like the following in the above example:
25
34
 
26
35
  `
27
36
  ...
@@ -93,6 +102,14 @@ Please check it https://www.smarthomejetzt.de/mit-iobroker-auf-eine-home-assista
93
102
  -->
94
103
 
95
104
  ## Changelog
105
+ ### 1.4.0 (2023-01-03)
106
+ * (Apollon77) Added more guidance logging when setting services incorrectly
107
+ * (Apollon77) Prevent crashes when attributes contain "." at the end of their names
108
+ * (Apollon77) Added logging for state updates for unknown objects
109
+
110
+ ### 1.3.0 (2022-07-01)
111
+ * (Apollon77) Further optimize sending data to HASS and allow to set values like numbers as normal states if the service has one attribute and it can be mapped
112
+
96
113
  ### 1.2.0 (2022-06-17)
97
114
  * (Apollon77) IMPORTANT: Replace special characters in entity attribute names with an underscore! Object IDs might change!
98
115
  * (Apollon77) make sure a "null" value in state changes is not crashing
@@ -123,7 +140,7 @@ Please check it https://www.smarthomejetzt.de/mit-iobroker-auf-eine-home-assista
123
140
  ## License
124
141
  The MIT License (MIT)
125
142
 
126
- Copyright (c) 2018-2022 bluefox <dogafox@gmail.com>
143
+ Copyright (c) 2018-2023 bluefox <dogafox@gmail.com>
127
144
 
128
145
  Permission is hereby granted, free of charge, to any person obtaining a copy
129
146
  of this software and associated documentation files (the "Software"), to deal
@@ -5,4 +5,4 @@
5
5
  "Password:": "Clave:",
6
6
  "Passwords missmatch!": "¡Las contraseñas no coinciden!",
7
7
  "Secure:": "¿HTTPS?:"
8
- }
8
+ }
@@ -0,0 +1,8 @@
1
+ {
2
+ "Home assistant IP:": "Домашній помічник IP:",
3
+ "Home assistant WS Port:": "Домашній помічник WS Порт:",
4
+ "Password repeat:": "Повторення пароля:",
5
+ "Password:": "Пароль:",
6
+ "Passwords missmatch!": "Паролі не збігаються!",
7
+ "Secure:": "HTTPS?"
8
+ }
package/admin/words.js CHANGED
@@ -1,11 +1,17 @@
1
1
  /*global systemDictionary:true */
2
+ /*
3
+ +===================== DO NOT MODIFY ======================+
4
+ | This file was generated by translate-adapter, please use |
5
+ | `translate-adapter adminLanguages2words` to update it. |
6
+ +===================== DO NOT MODIFY ======================+
7
+ */
2
8
  'use strict';
3
9
 
4
10
  systemDictionary = {
5
- "Home assistant IP:": { "en": "Home assistant IP:", "de": "IP-Adresse des Heimassistenten:", "ru": "Домашний помощник IP:", "pt": "IP do assistente doméstico:", "nl": "Thuisassistent IP:", "fr": "IP de l'assistant à domicile :", "it": "IP assistente domestico:", "es": "IP del asistente de hogar:", "pl": "Adres IP asystenta domowego:", "zh-cn": "家庭助理IP:"},
6
- "Home assistant WS Port:": { "en": "Home assistant WS Port:", "de": "Home Assistant WS-Port:", "ru": "Домашний помощник WS Порт:", "pt": "Assistente doméstico Porta WS:", "nl": "Thuisassistent WS Poort:", "fr": "Port WS de l'assistant domestique :", "it": "Porta WS dell'assistente domestico:", "es": "Asistente doméstico Puerto WS:", "pl": "Asystent domowy Port WS:", "zh-cn": "家庭助理 WS 端口:"},
7
- "Password repeat:": { "en": "Password repeat:", "de": "Passwort wiederholen:", "ru": "Повтор пароля:", "pt": "Repetição de senha:", "nl": "Wachtwoord herhalen:", "fr": "Répéter le mot de passe :", "it": "Ripeti password:", "es": "Repite la contraseña:", "pl": "Powtórz hasło:", "zh-cn": "密码重复:"},
8
- "Password:": { "en": "Password:", "de": "Passwort:", "ru": "Пароль:", "pt": "Senha:", "nl": "Wachtwoord:", "fr": "Mot de passe:", "it": "Parola d'ordine:", "es": "Clave:", "pl": "Hasło:", "zh-cn": "密码:"},
9
- "Passwords missmatch!": { "en": "Passwords missmatch!", "de": "Passwörter stimmen nicht überein!", "ru": "Пароли не совпадают!", "pt": "As senhas não correspondem!", "nl": "Wachtwoorden komen niet overeen!", "fr": "Les mots de passe ne correspondent pas !", "it": "Le password non corrispondono!", "es": "¡Las contraseñas no coinciden!", "pl": "Niezgodność haseł!", "zh-cn": "密码不匹配!"},
10
- "Secure:": { "en": "HTTPS?", "de": "HTTPS?", "ru": "HTTPS?", "pt": "HTTPS?", "nl": "HTTPS?", "fr": "HTTPS ?", "it": "HTTPS?", "es": "¿HTTPS?", "pl": "HTTPS?", "zh-cn": "HTTPS?"},
11
- };
11
+ "Home assistant IP:": { "en": "Home assistant IP:", "de": "IP-Adresse des Heimassistenten:", "ru": "Домашний помощник IP:", "pt": "IP do assistente doméstico:", "nl": "Thuisassistent IP:", "fr": "IP de l'assistant à domicile :", "it": "IP assistente domestico:", "es": "IP del asistente de hogar:", "pl": "Adres IP asystenta domowego:", "uk": "Домашній помічник IP:", "zh-cn": "家庭助理IP:"},
12
+ "Home assistant WS Port:": { "en": "Home assistant WS Port:", "de": "Home Assistant WS-Port:", "ru": "Домашний помощник WS Порт:", "pt": "Assistente doméstico Porta WS:", "nl": "Thuisassistent WS Poort:", "fr": "Port WS de l'assistant domestique :", "it": "Porta WS dell'assistente domestico:", "es": "Asistente doméstico Puerto WS:", "pl": "Asystent domowy Port WS:", "uk": "Домашній помічник WS Порт:", "zh-cn": "家庭助理 WS 端口:"},
13
+ "Password repeat:": { "en": "Password repeat:", "de": "Passwort wiederholen:", "ru": "Повтор пароля:", "pt": "Repetição de senha:", "nl": "Wachtwoord herhalen:", "fr": "Répéter le mot de passe :", "it": "Ripeti password:", "es": "Repite la contraseña:", "pl": "Powtórz hasło:", "uk": "Повторення пароля:", "zh-cn": "密码重复:"},
14
+ "Password:": { "en": "Password:", "de": "Passwort:", "ru": "Пароль:", "pt": "Senha:", "nl": "Wachtwoord:", "fr": "Mot de passe:", "it": "Parola d'ordine:", "es": "Clave:", "pl": "Hasło:", "uk": "Пароль:", "zh-cn": "密码:"},
15
+ "Passwords missmatch!": { "en": "Passwords missmatch!", "de": "Passwörter stimmen nicht überein!", "ru": "Пароли не совпадают!", "pt": "As senhas não correspondem!", "nl": "Wachtwoorden komen niet overeen!", "fr": "Les mots de passe ne correspondent pas !", "it": "Le password non corrispondono!", "es": "¡Las contraseñas no coinciden!", "pl": "Niezgodność haseł!", "uk": "Паролі не збігаються!", "zh-cn": "密码不匹配!"},
16
+ "Secure:": { "en": "HTTPS?", "de": "HTTPS?", "ru": "HTTPS?", "pt": "HTTPS?", "nl": "HTTPS?", "fr": "HTTPS ?", "it": "HTTPS?", "es": "¿HTTPS?:", "pl": "HTTPS?", "uk": "HTTPS?", "zh-cn": "HTTPS?"},
17
+ };
package/io-package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "common": {
3
3
  "name": "hass",
4
- "version": "1.2.0",
4
+ "version": "1.4.0",
5
5
  "title": "Home Assistant",
6
6
  "titleLang": {
7
7
  "en": "Home Assistant",
@@ -13,7 +13,8 @@
13
13
  "it": "Assistente domiciliare",
14
14
  "es": "Asistente de hogar",
15
15
  "pl": "Asystent domowy",
16
- "zh-cn": "家庭助理"
16
+ "zh-cn": "家庭助理",
17
+ "uk": "Домашній помічник"
17
18
  },
18
19
  "desc": {
19
20
  "en": "Home Assistant connection for ioBroker",
@@ -25,9 +26,36 @@
25
26
  "it": "Connessione Home Assistant per ioBroker",
26
27
  "es": "Conexión de Home Assistant para ioBroker",
27
28
  "pl": "Połączenie Home Assistant dla ioBroker",
28
- "zh-cn": "ioBroker 的家庭助理连接"
29
+ "zh-cn": "ioBroker 的家庭助理连接",
30
+ "uk": "Підключення Home Assistant для ioBroker"
29
31
  },
30
32
  "news": {
33
+ "1.4.0": {
34
+ "en": "Added more guidance logging when setting services incorrectly\nPrevent crashes when attributes contain \".\" at the end of their names\nAdded logging for state updates for unknown objects",
35
+ "de": "Mehr Anleitungsprotokollierung hinzugefügt, wenn Dienste falsch eingestellt werden\nVerhindern Sie Abstürzen, wenn Attribute \" enthalten.\" am Ende ihrer Namen\nHinzugefügt Protokollierung für Zustandsaktualisierungen für unbekannte Objekte",
36
+ "ru": "Добавили больше руководства, когда установка услуг неправильно\nПредотвратить сбои, когда атрибуты содержат \".\" в конце их имен\nДобавлен вход для государственных обновлений для неизвестных объектов",
37
+ "pt": "Adicionado mais registro de orientação ao definir serviços incorretamente\nImpedir falhas quando os atributos contêm \". no final de seus nomes\nRegisto adicionado para atualizações de estado para objetos desconhecidos",
38
+ "nl": "Voeg meer begeleiding toe als ze onjuiste diensten indienen\nVertaling:\nVermeld inloggen op staatsinformatie voor onbekende objecten",
39
+ "fr": "Ajout d'autres lignes directrices lorsqu'on établit des services incorrectement\nPrévenir les crashes lorsque les attributs contiennent \".\" à la fin de leurs noms\nAjout de logging pour les mises à jour de l'état des objets inconnus",
40
+ "it": "Aggiunto più guida logging quando imposta i servizi in modo errato\nPrevenire crash quando gli attributi contengono \". alla fine dei loro nomi\nAggiunto logging per aggiornamenti di stato per oggetti sconosciuti",
41
+ "es": "Se agregó más registro de guía cuando se establecen los servicios incorrectamente\nEvitar fallos cuando los atributos contienen \".\" al final de sus nombres\nRegistro añadido para actualizaciones estatales para objetos desconocidos",
42
+ "pl": "Wprowadzone są bardziej wytyczne, gdy ustawienie usług nieprawidłowo błędnie\nPrevent rozbija się, gdy atrybuty zawierają „”\nWprowadzone logowanie dla aktualizacji stanów nieznanych obiektów",
43
+ "uk": "Додайте більше звітів при установці послуг неправильно\nПрофілактика аварійних випадків, коли атрибути містять \".\" в кінці їх імен\nДодана записка для державних оновлень для невідомих об'єктів",
44
+ "zh-cn": "在不正确地建立服务时增加指导标志\n在名称末尾含有“第2款”的预防事故\n增加用于不明物品的国家更新的伐木"
45
+ },
46
+ "1.3.0": {
47
+ "en": "Further optimize sending data to HASS and allow to set values like numbers as normal states if the service has one attribute and it can be mapped",
48
+ "de": "Weitere optimieren Sie das Senden von Daten an HASS und ermöglichen es, Werte wie Zahlen als normale Zustände festzulegen, wenn der Dienst ein Attribut hat und es abgebildet werden kann",
49
+ "ru": "Далее оптимизируйте отправку данных в HASS и позвольте установить значения, такие как цифры, как нормальные состояния, если услуга имеет один атрибут, и она может быть загружена",
50
+ "pt": "Além disso otimizar o envio de dados para HASS e permitir definir valores como números como estados normais se o serviço tem um atributo e pode ser mapeado",
51
+ "nl": "Verder optimiliseer het sturen van gegevens naar HASS en sta toe om waarden als normale staten te plaatsen als de dienst een Attribuut heeft en het kan worden in kaart gebracht",
52
+ "fr": "Optimiser l'envoi de données à HASS et permettre de définir des valeurs comme des nombres comme des états normaux si le service a un attribut et il peut être mappé",
53
+ "it": "Ottimizzare ulteriormente l'invio di dati a HASS e consentire di impostare valori come numeri come stati normali se il servizio ha un attributo e può essere mappato",
54
+ "es": "Optimizar aún más el envío de datos a HASS y permitir establecer valores como números como estados normales si el servicio tiene un atributo y puede ser mapeado",
55
+ "pl": "Dalsze optymalizowanie danych do HASS i umożliwienie ustalenie wartości takich jak stany normalne, jeśli usługa ma jeden atrybut i może być zmapowana",
56
+ "zh-cn": "进一步优化向人道协调厅系统传送数据,如果该服务具有属性,它可以绘制图表,从而能够将数字象正常国家一样。",
57
+ "uk": "Додатково оптимізуйте надсилання даних до HASS і дозвольте встановлювати такі значення, як числа, як звичайні стани, якщо служба має один атрибут і його можна зіставити"
58
+ },
31
59
  "1.2.0": {
32
60
  "en": "IMPORTANT: Replace special characters in entity attribute names with an underscore! Object IDs might change!\nmake sure a \"null\" value in state changes is not crashing",
33
61
  "de": "WICHTIG: Ersetzen Sie Sonderzeichen in Namen des Attributes der Einheit mit einem Unterpunkt! Objekt-IDs können sich ändern!\nsicherstellen, dass ein nullwert bei zustandsänderungen nicht abstürzt",
@@ -38,7 +66,8 @@
38
66
  "it": "IMPORTANTE: Sostituisci caratteri speciali in nomi attributo entità con un underscore! Gli ID degli Oggetti potrebbero cambiare!\nassicurarsi che un valore nullo nei cambiamenti di stato non è crash",
39
67
  "es": "IMPORTANTE: Reemplazar caracteres especiales en nombres de atributos de entidad con un subrayado! ¡Las identificaciones de objetos pueden cambiar!\nasegúrese de que un valor nulo en los cambios estatales no se estrella",
40
68
  "pl": "IMPORTANT: Replace special characters in identity attribution names with an underscore! (ang.). Zmiany obiektów mogą się zmieniać!\nniewątpliwą wartością w zmianach stanowych nie jest rozbicie się",
41
- "zh-cn": "IMPORTANT:将实体的特色性改为强调的! 目标国际组织可能改变!\n确保在国家变化中确保无效不失"
69
+ "zh-cn": "IMPORTANT:将实体的特色性改为强调的! 目标国际组织可能改变!\n确保在国家变化中确保无效不失",
70
+ "uk": "ВАЖЛИВО: Замініть спеціальні символи в іменах атрибутів сутності на підкреслення! Ідентифікатори об'єктів можуть змінитися!\nпереконайтеся, що \"нульове\" значення в змінах стану не аварійно завершує роботу"
42
71
  },
43
72
  "1.1.2": {
44
73
  "en": "Fix crash cases reported by Sentry",
@@ -50,7 +79,8 @@
50
79
  "it": "Risolvi i casi di crash segnalati da Sentry",
51
80
  "es": "Solucionar casos de fallas informados por Sentry",
52
81
  "pl": "Napraw przypadki awarii zgłoszone przez Sentry",
53
- "zh-cn": "修复 Sentry 报告的崩溃案例"
82
+ "zh-cn": "修复 Sentry 报告的崩溃案例",
83
+ "uk": "Виправте випадки збоїв, про які повідомляє Sentry"
54
84
  },
55
85
  "1.1.1": {
56
86
  "en": "Show password fields masked again in config",
@@ -62,7 +92,8 @@
62
92
  "it": "Mostra i campi password mascherati di nuovo in config",
63
93
  "es": "Mostrar campos de contraseña enmascarados nuevamente en la configuración",
64
94
  "pl": "Pokaż ponownie zamaskowane pola haseł w konfiguracji",
65
- "zh-cn": "在配置中再次显示被屏蔽的密码字段"
95
+ "zh-cn": "在配置中再次显示被屏蔽的密码字段",
96
+ "uk": "Знову показати замасковані поля пароля в конфігурації"
66
97
  },
67
98
  "1.1.0": {
68
99
  "en": "IMPORTANT: You need to re-enter the password once after installing this version!\nImplement Service triggers to use any value to trigger or stringified JSON to call with fields\nOptimize unload handling\nAdd Sentry for crash reporting",
@@ -74,7 +105,8 @@
74
105
  "it": "IMPORTANTE: è necessario reinserire la password una volta dopo aver installato questa versione!\nImplementa i trigger del servizio per utilizzare qualsiasi valore per attivare o JSON in formato stringa per chiamare con i campi\nOttimizza la gestione dello scarico\nAggiungi Sentinella per la segnalazione degli arresti anomali",
75
106
  "es": "IMPORTANTE: ¡Debe volver a ingresar la contraseña una vez después de instalar esta versión!\nImplementar disparadores de servicio para usar cualquier valor para disparar o JSON en cadena para llamar con campos\nOptimizar el manejo de descarga\nAgregar Sentry para informes de fallas",
76
107
  "pl": "WAŻNE: Po zainstalowaniu tej wersji należy raz ponownie wprowadzić hasło!\nZaimplementuj wyzwalacze usługi, aby używać dowolnej wartości do wyzwalania lub skróconego JSON do wywołania z polami\nZoptymalizuj obsługę rozładunku\nDodaj Sentry do zgłaszania awarii",
77
- "zh-cn": "重要提示:安装此版本后需要重新输入一次密码!\n实现服务触发器以使用任何值触发或字符串化 JSON 以使用字段调用\n优化卸载处理\n添加 Sentry 以进行崩溃报告"
108
+ "zh-cn": "重要提示:安装此版本后需要重新输入一次密码!\n实现服务触发器以使用任何值触发或字符串化 JSON 以使用字段调用\n优化卸载处理\n添加 Sentry 以进行崩溃报告",
109
+ "uk": "ВАЖЛИВО: після встановлення цієї версії потрібно повторно ввести пароль!\nРеалізуйте тригери служби, щоб використовувати будь-яке значення для запуску або рядковий JSON для виклику з полями\nОптимізуйте роботу з розвантаженням\nДодайте Sentry для звітування про збої"
78
110
  },
79
111
  "1.0.1": {
80
112
  "en": "IMPORTANT: js-controller 2.0 is needed st least!\nFix start issue\n(Apollon77/Garfonso) Fix issue where value could not be set in hass",
@@ -86,31 +118,8 @@
86
118
  "it": "IMPORTANTE: come minimo è necessario js-controller 2.0!\nRisolvi il problema di avvio\n(Apollon77/Garfonso) Risolto il problema per cui il valore non poteva essere impostato in hass",
87
119
  "es": "IMPORTANTE: ¡js-controller 2.0 es lo menos necesario!\nSolucionar problema de inicio\n(Apollon77 / Garfonso) Se solucionó el problema por el cual no se podía establecer el valor en hass",
88
120
  "pl": "WAŻNE: js-controller 2.0 jest potrzebny przynajmniej!\nNapraw problem z uruchomieniem\n(Apollon77/Garfonso) Napraw problem, w którym nie można było ustawić wartości w hass",
89
- "zh-cn": "重要提示:至少需要 js-controller 2.0!\n修复启动问题\n(Apollon77/Garfonso) 修复无法在 hass 中设置值的问题"
90
- },
91
- "1.0.0": {
92
- "en": "added the support of compact mode",
93
- "de": "fügte die Unterstützung des Kompaktmodus hinzu",
94
- "ru": "добавлена поддержка компактного режима",
95
- "pt": "adicionado o suporte do modo compacto",
96
- "nl": "de ondersteuning van de compacte modus toegevoegd",
97
- "fr": "ajouté le support du mode compact",
98
- "it": "aggiunto il supporto della modalità compatta",
99
- "es": "agregó el soporte del modo compacto",
100
- "pl": "dodano obsługę trybu kompaktowego",
101
- "zh-cn": "增加了对紧凑模式的支持"
102
- },
103
- "0.1.0": {
104
- "en": "initial version",
105
- "de": "erste Version",
106
- "ru": "Первоначальная версия",
107
- "pt": "versão inicial",
108
- "nl": "eerste versie",
109
- "fr": "version initiale",
110
- "it": "versione iniziale",
111
- "es": "versión inicial",
112
- "pl": "początkowa wersja",
113
- "zh-cn": "初始版本"
121
+ "zh-cn": "重要提示:至少需要 js-controller 2.0!\n修复启动问题\n(Apollon77/Garfonso) 修复无法在 hass 中设置值的问题",
122
+ "uk": "ВАЖЛИВО: як мінімум потрібен js-контроллер 2.0!\nВиправити проблему запуску\n(Apollon77/Garfonso) Виправлено проблему, через яку значення не можна було встановити в hass"
114
123
  }
115
124
  },
116
125
  "localLink": "http://%host%:8123",
@@ -170,7 +179,8 @@
170
179
  "it": "Reinserire la password dopo l'aggiornamento!",
171
180
  "es": "Vuelva a ingresar la contraseña después de ¡Actualizar!",
172
181
  "pl": "Wprowadź hasło ponownie po aktualizacji!",
173
- "zh-cn": "更新后重新输入密码!"
182
+ "zh-cn": "更新后重新输入密码!",
183
+ "uk": "Повторно введіть пароль після оновлення!"
174
184
  },
175
185
  "text": {
176
186
  "en": "After installing this update the password/token used to access the HASS installation needs to be re-entered in the Instance-Settings!",
@@ -182,7 +192,8 @@
182
192
  "it": "Dopo aver installato questo aggiornamento, la password/token utilizzato per accedere all'installazione HASS deve essere reinserito nelle impostazioni dell'istanza!",
183
193
  "es": "¡Después de instalar esta actualización, la contraseña/token utilizada para acceder a la instalación de HASS debe volver a ingresarse en la configuración de la instancia!",
184
194
  "pl": "Po zainstalowaniu tej aktualizacji hasło/token używane do uzyskania dostępu do instalacji HASS należy ponownie wprowadzić w ustawieniach instancji!",
185
- "zh-cn": "安装此更新后,用于访问 HASS 安装的密码/令牌需要在实例设置中重新输入!"
195
+ "zh-cn": "安装此更新后,用于访问 HASS 安装的密码/令牌需要在实例设置中重新输入!",
196
+ "uk": "Після встановлення цього оновлення пароль/токен, який використовується для доступу до встановлення HASS, потрібно повторно ввести в налаштуваннях екземпляра!"
186
197
  },
187
198
  "level": "warn",
188
199
  "buttons": [
@@ -208,7 +219,8 @@
208
219
  "it": "Avviso IMPORTANTE!",
209
220
  "es": "Noticia importante!",
210
221
  "pl": "Ważna uwaga!",
211
- "zh-cn": "重要通知!"
222
+ "zh-cn": "重要通知!",
223
+ "uk": "Важливе повідомлення!"
212
224
  },
213
225
  "text": {
214
226
  "en": "The new version 1.2.x will potentially change the Names of Objects when special characters like \".\", \"-\" or spaces were used in entity attributes! Please delete the old objects manually if needed.",
@@ -220,7 +232,8 @@
220
232
  "it": "La nuova versione 1.2.x cambierà potenzialmente i nomi degli oggetti quando caratteri speciali come \".\", \"-\" o spazi sono stati utilizzati negli attributi dell'entità! Si prega di eliminare i vecchi oggetti manualmente se necessario.",
221
233
  "es": "La nueva versión 1.2.x potencialmente cambiará los Nombres de Objetos cuando caracteres especiales como \"., \"-\" o espacios fueron utilizados en atributos de entidad! Por favor, borre los viejos objetos manualmente si es necesario.",
222
234
  "pl": "Nowa wersja 1.2.x będzie potencjalnie zmieniać nazwy obiektów, kiedy szczególne postacie takie jak „.”, „-” lub przestrzenie były używane w atrybutach. Okazuje się, że stare obiekty ręcznie będą potrzebne.",
223
- "zh-cn": "新版本1.2.x将可能改变物体的名称,如“......”、“-”或空间在实体的属性中使用。 请在必要时删除旧物体。."
235
+ "zh-cn": "新版本1.2.x将可能改变物体的名称,如“......”、“-”或空间在实体的属性中使用。 请在必要时删除旧物体。.",
236
+ "uk": "Нова версія 1.2.x потенційно змінить назви об’єктів, якщо в атрибутах об’єктів використовувалися спеціальні символи, такі як «.», «-» або пробіли! За потреби видаліть старі об’єкти вручну."
224
237
  },
225
238
  "level": "warn",
226
239
  "buttons": [
package/main.js CHANGED
@@ -25,7 +25,7 @@ function startAdapter(options) {
25
25
  // you can use the ack flag to detect if it is status (true) or command (false)
26
26
  if (state && !state.ack) {
27
27
  if (!connected) {
28
- return adapter.log.warn('Cannot send command to "' + id + '", because not connected');
28
+ return adapter.log.warn(`Cannot send command to "${id}", because not connected`);
29
29
  }
30
30
  /*if (id === adapter.namespace + '.' + '.info.resync') {
31
31
  queue.push({command: 'resync'});
@@ -33,7 +33,7 @@ function startAdapter(options) {
33
33
  } else */
34
34
  if (hassObjects[id]) {
35
35
  if (!hassObjects[id].common.write) {
36
- adapter.log.warn('Object ' + id + ' is not writable!');
36
+ adapter.log.warn(`Object ${id} is not writable!`);
37
37
  } else {
38
38
  const serviceData = {};
39
39
  const fields = hassObjects[id].native.fields;
@@ -41,30 +41,52 @@ function startAdapter(options) {
41
41
 
42
42
  let requestFields = {};
43
43
  if (typeof state.val === 'string') {
44
- try {
45
- requestFields = JSON.parse(state.val) || {};
46
- } catch (err) {
47
- adapter.log.info(`Ignore data for service call ${id} is no valid JSON: ${err.message}`);
48
- requestFields = {};
44
+ state.val = state.val.trim();
45
+ if (state.val.startsWith('{') && state.val.endsWith('}')) {
46
+ try {
47
+ requestFields = JSON.parse(state.val) || {};
48
+ } catch (err) {
49
+ adapter.log.info(`Ignore data for service call ${id} is no valid JSON: ${err.message}`);
50
+ requestFields = {};
51
+ }
49
52
  }
50
53
  }
51
54
 
52
- for (const field in fields) {
53
- if (!fields.hasOwnProperty(field)) {
54
- continue;
55
+ // If a non-JSON value was set, and we only have one relevant field, use this field as value
56
+ if (fields && Object.keys(requestFields).length === 0) {
57
+ const fieldList = Object.keys(fields);
58
+ if (fieldList.length === 1 && fieldList[0] !== 'entity_id') {
59
+ requestFields[fieldList[0]] = state.val;
60
+ } else if (fieldList.length === 2 && fields.entity_id) {
61
+ requestFields[fieldList[1 - fields.indexOf('entity_id')]] = state.val;
55
62
  }
63
+ }
56
64
 
57
- if (field === 'entity_id') {
58
- target.entity_id = hassObjects[id].native.entity_id
59
- } else if (requestFields[field] !== undefined) {
60
- serviceData[field] = requestFields[field];
65
+ adapter.log.debug(`Prepare service call for ${id} with (mapped) request parameters ${JSON.stringify(requestFields)} from value: ${JSON.stringify(state.val)}`);
66
+ if (fields) {
67
+ for (const field in fields) {
68
+ if (!fields.hasOwnProperty(field)) {
69
+ continue;
70
+ }
71
+
72
+ if (field === 'entity_id') {
73
+ target.entity_id = hassObjects[id].native.entity_id
74
+ } else if (requestFields[field] !== undefined) {
75
+ serviceData[field] = requestFields[field];
76
+ }
61
77
  }
62
78
  }
79
+ const noFields = Object.keys(serviceData).length === 0;
63
80
  serviceData.entity_id = hassObjects[id].native.entity_id
64
81
 
65
82
  adapter.log.debug(`Send to HASS for service ${hassObjects[id].native.attr} with ${hassObjects[id].native.domain || hassObjects[id].native.type} and data ${JSON.stringify(serviceData)}`)
66
- hass.callService(hassObjects[id].native.attr, hassObjects[id].native.domain || hassObjects[id].native.type, serviceData, target, err =>
67
- err && adapter.log.error('Cannot control ' + id + ': ' + err));
83
+ hass.callService(hassObjects[id].native.attr, hassObjects[id].native.domain || hassObjects[id].native.type, serviceData, target, err => {
84
+ err && adapter.log.error(`Cannot control ${id}: ${err}`);
85
+ if (err && fields && noFields) {
86
+ adapter.log.warn(`Please make sure to provide a stringified JSON as value to set relevant fields! Please refer to the Readme for details!`);
87
+ adapter.log.warn(`Allowed field keys are: ${Object.keys(fields).join(', ')}`);
88
+ }
89
+ });
68
90
  }
69
91
  }
70
92
  }
@@ -126,7 +148,7 @@ function syncObjects(objects, cb) {
126
148
  err && adapter.log.error(err);
127
149
 
128
150
  if (!oldObj) {
129
- adapter.log.debug('Create "' + obj._id + '": ' + JSON.stringify(obj.common));
151
+ adapter.log.debug(`Create "${obj._id}": ${JSON.stringify(obj.common)}`);
130
152
  hassObjects[obj._id] = obj;
131
153
  adapter.setForeignObject(obj._id, obj, err => {
132
154
  err && adapter.log.error(err);
@@ -137,7 +159,7 @@ function syncObjects(objects, cb) {
137
159
  if (JSON.stringify(obj.native) !== JSON.stringify(oldObj.native)) {
138
160
  oldObj.native = obj.native;
139
161
 
140
- adapter.log.debug('Update "' + obj._id + '": ' + JSON.stringify(obj.common));
162
+ adapter.log.debug(`Update "${obj._id}": ${JSON.stringify(obj.common)}`);
141
163
  adapter.setForeignObject(obj._id, oldObj, err => {
142
164
  err => adapter.log.error(err);
143
165
  setImmediate(syncObjects, objects, cb);
@@ -150,10 +172,10 @@ function syncObjects(objects, cb) {
150
172
  }
151
173
 
152
174
  function syncRoom(room, members, cb) {
153
- adapter.getForeignObject('enum.rooms.' + room, (err, obj) => {
175
+ adapter.getForeignObject(`enum.rooms.${room}`, (err, obj) => {
154
176
  if (!obj) {
155
177
  obj = {
156
- _id: 'enum.rooms.' + room,
178
+ _id: `enum.rooms.${room}`,
157
179
  type: 'enum',
158
180
  common: {
159
181
  name: room,
@@ -161,7 +183,7 @@ function syncRoom(room, members, cb) {
161
183
  },
162
184
  native: {}
163
185
  };
164
- adapter.log.debug('Update "' + obj._id + '"');
186
+ adapter.log.debug(`Update "${obj._id}"`);
165
187
  adapter.setForeignObject(obj._id, obj, err => {
166
188
  err && adapter.log.error(err);
167
189
  cb();
@@ -177,7 +199,7 @@ function syncRoom(room, members, cb) {
177
199
  }
178
200
  }
179
201
  if (changed) {
180
- adapter.log.debug('Update "' + obj._id + '"');
202
+ adapter.log.debug(`Update "${obj._id}"`);
181
203
  adapter.setForeignObject(obj._id, obj, err => {
182
204
  err && adapter.log.error(err);
183
205
  cb();
@@ -283,8 +305,9 @@ function parseStates(entities, services, callback) {
283
305
  common = {};
284
306
  }
285
307
 
308
+ const attrId = attr.replace(adapter.FORBIDDEN_CHARS, '_').replace(/\.+$/, '_');
286
309
  obj = {
287
- _id: `${adapter.namespace}.entities.${entity.entity_id}.${attr.replace(adapter.FORBIDDEN_CHARS, '_')}`,
310
+ _id: `${adapter.namespace}.entities.${entity.entity_id}.${attrId}`,
288
311
  type: 'state',
289
312
  common: common,
290
313
  native: {
@@ -295,7 +318,7 @@ function parseStates(entities, services, callback) {
295
318
  }
296
319
  };
297
320
  if (!common.name) {
298
- common.name = name + ' ' + attr.replace(/_/g, ' ');
321
+ common.name = `${name} ${attr.replace(/_/g, ' ')}`;
299
322
  }
300
323
  if (common.read === undefined) {
301
324
  common.read = true;
@@ -375,11 +398,15 @@ function main() {
375
398
  return;
376
399
  }
377
400
 
378
- const id = adapter.namespace + '.entities.' + entity.entity_id + '.';
401
+ const id = `entities.${entity.entity_id}.`;
379
402
  const lc = entity.last_changed ? new Date(entity.last_changed).getTime() : undefined;
380
403
  const ts = entity.last_updated ? new Date(entity.last_updated).getTime() : undefined;
381
404
  if (entity.state !== undefined) {
382
- adapter.setForeignState(id + 'state', {val: entity.state, ack: true, lc: lc, ts: ts});
405
+ if (hassObjects[`${adapter.namespace}.${id}state`]) {
406
+ adapter.setState(`${id}state`, {val: entity.state, ack: true, lc: lc, ts: ts});
407
+ } else {
408
+ adapter.log.info(`State changed for unknown object ${`${id}state`}. Please restart the adapter to resync the objects.`);
409
+ }
383
410
  }
384
411
  if (entity.attributes) {
385
412
  for (const attr in entity.attributes) {
@@ -390,7 +417,12 @@ function main() {
390
417
  if ((typeof val === 'object' && val !== null) || Array.isArray(val)) {
391
418
  val = JSON.stringify(val);
392
419
  }
393
- adapter.setForeignState(id + attr.replace(adapter.FORBIDDEN_CHARS, '_'), {val, ack: true, lc, ts});
420
+ const attrId = attr.replace(adapter.FORBIDDEN_CHARS, '_').replace(/\.+$/, '_');
421
+ if (hassObjects[`${adapter.namespace}.${id}state`]) {
422
+ adapter.setState(id + attrId, {val, ack: true, lc, ts});
423
+ } else {
424
+ adapter.log.info(`State changed for unknown object ${id + attrId}. Please restart the adapter to resync the objects.`);
425
+ }
394
426
  }
395
427
  }
396
428
  });
@@ -402,7 +434,7 @@ function main() {
402
434
  adapter.setState('info.connection', true, true);
403
435
  hass.getConfig((err, config) => {
404
436
  if (err) {
405
- adapter.log.error('Cannot read config: ' + err);
437
+ adapter.log.error(`Cannot read config: ${err}`);
406
438
  return;
407
439
  }
408
440
  //adapter.log.debug(JSON.stringify(config));
@@ -413,7 +445,7 @@ function main() {
413
445
  return;
414
446
  }
415
447
  if (err) {
416
- return adapter.log.error('Cannot read states: ' + err);
448
+ return adapter.log.error(`Cannot read states: ${err}`);
417
449
  }
418
450
  //adapter.log.debug(JSON.stringify(states));
419
451
  delayTimeout = setTimeout(() => {
@@ -423,7 +455,7 @@ function main() {
423
455
  return;
424
456
  }
425
457
  if (err) {
426
- adapter.log.error('Cannot read states: ' + err);
458
+ adapter.log.error(`Cannot read states: ${err}`);
427
459
  } else {
428
460
  //adapter.log.debug(JSON.stringify(services));
429
461
  parseStates(states, services, () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "iobroker.hass",
3
- "version": "1.2.0",
3
+ "version": "1.4.0",
4
4
  "description": "Home Assistant",
5
5
  "author": {
6
6
  "name": "bluefox",
@@ -26,17 +26,16 @@
26
26
  },
27
27
  "dependencies": {
28
28
  "websocket": "^1.0.34",
29
- "ws": "^8.8.0",
30
- "@iobroker/adapter-core": "^2.6.0"
29
+ "ws": "^8.11.0",
30
+ "@iobroker/adapter-core": "^2.6.7"
31
31
  },
32
32
  "devDependencies": {
33
33
  "@alcalzone/release-script": "^3.5.9",
34
34
  "@alcalzone/release-script-plugin-iobroker": "^3.5.9",
35
35
  "@alcalzone/release-script-plugin-license": "^3.5.9",
36
- "axios": "^0.27.2",
37
- "gulp": "^4.0.2",
38
- "mocha": "^10.0.0",
39
- "chai": "^4.3.6"
36
+ "@iobroker/adapter-dev": "^1.2.0",
37
+ "mocha": "^10.2.0",
38
+ "chai": "^4.3.7"
40
39
  },
41
40
  "main": "main.js",
42
41
  "scripts": {
@@ -44,7 +43,8 @@
44
43
  "release": "release-script",
45
44
  "release-patch": "release-script patch --yes",
46
45
  "release-minor": "release-script minor --yes",
47
- "release-major": "release-script major --yes"
46
+ "release-major": "release-script major --yes",
47
+ "translate": "translate-adapter"
48
48
  },
49
49
  "bugs": {
50
50
  "url": "https://github.com/ioBroker/ioBroker.hass/issues"
package/lib/tools.js DELETED
@@ -1,92 +0,0 @@
1
- const axios = require("axios");
2
-
3
- /**
4
- * Tests whether the given variable is a real object and not an Array
5
- * @param {any} it The variable to test
6
- * @returns {it is Record<string, any>}
7
- */
8
- function isObject(it) {
9
- // This is necessary because:
10
- // typeof null === 'object'
11
- // typeof [] === 'object'
12
- // [] instanceof Object === true
13
- return Object.prototype.toString.call(it) === "[object Object]";
14
- }
15
-
16
- /**
17
- * Tests whether the given variable is really an Array
18
- * @param {any} it The variable to test
19
- * @returns {it is any[]}
20
- */
21
- function isArray(it) {
22
- if (Array.isArray != null)
23
- return Array.isArray(it);
24
- return Object.prototype.toString.call(it) === "[object Array]";
25
- }
26
-
27
- /**
28
- * Choose the right tranalation API
29
- * @param {string} text The text to translate
30
- * @param {string} targetLang The target languate
31
- * @param {string} yandex api key
32
- * @returns {Promise<string>}
33
- */
34
- async function translateText(text, targetLang, yandex) {
35
- if (targetLang === "en") {
36
- return text;
37
- }
38
- if (yandex) {
39
- return await translateYandex(text, targetLang, yandex);
40
- } else {
41
- return await translateGoogle(text, targetLang);
42
- }
43
- }
44
-
45
- /**
46
- * Translates text with Yandex API
47
- * @param {string} text The text to translate
48
- * @param {string} targetLang The target languate
49
- * @param {string} yandex api key
50
- * @returns {Promise<string>}
51
- */
52
- async function translateYandex(text, targetLang, yandex) {
53
- if (targetLang === "zh-cn") {
54
- targetLang = "zh";
55
- }
56
- try {
57
- const url = `https://translate.yandex.net/api/v1.5/tr.json/translate?key=${yandex}&text=${encodeURIComponent(text)}&lang=en-${targetLang}`;
58
- const response = await axios({url, timeout: 15000});
59
- if (response.data && response.data['text']) {
60
- return response.data['text'][0];
61
- }
62
- throw new Error("Invalid response for translate request");
63
- } catch (e) {
64
- throw new Error(`Could not translate to "${targetLang}": ${e}`);
65
- }
66
- }
67
-
68
- /**
69
- * Translates text with Google API
70
- * @param {string} text The text to translate
71
- * @param {string} targetLang The target languate
72
- * @returns {Promise<string>}
73
- */
74
- async function translateGoogle(text, targetLang) {
75
- try {
76
- const url = `http://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=${targetLang}&dt=t&q=${encodeURIComponent(text)}&ie=UTF-8&oe=UTF-8`;
77
- const response = await axios({url, timeout: 15000});
78
- if (isArray(response.data)) {
79
- // we got a valid response
80
- return response.data[0][0][0];
81
- }
82
- throw new Error("Invalid response for translate request");
83
- } catch (e) {
84
- throw new Error(`Could not translate to "${targetLang}": ${e}`);
85
- }
86
- }
87
-
88
- module.exports = {
89
- isArray,
90
- isObject,
91
- translateText
92
- };