iobroker.zigbee2mqtt 3.2.10 → 3.2.12

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 CHANGED
@@ -29,7 +29,21 @@ check you VM Settings
29
29
 
30
30
  [Adapter Documentation](https://github.com/arteck/ioBroker.zigbee2mqtt/blob/main/docs/wiki.md)
31
31
 
32
+ ## Update timestamps
33
+
34
+ Enable **Always update received states, even when unchanged** in the instance configuration to write every regular state contained in a received Zigbee2MQTT payload. This follows ioBroker's timestamp semantics: `ts` tracks updates and `lc` tracks value changes. The option is disabled by default to preserve existing behavior and reduce writes. It applies to all regular states, including additional fields, while action/event and impulse handling remain unchanged.
35
+
36
+ Missing fields are not refreshed. Zigbee2MQTT can include cached values, so `ts` does not guarantee a new physical measurement. Sensor reporting intervals and history settings are unaffected.
37
+
32
38
  ## Changelog
39
+ ### 3.2.12 (2026-11-29)
40
+ * (arteck) the `available` state now reflects the availability reported by Zigbee2MQTT only; cached device data replayed on WebSocket connect no longer flips an explicitly offline device back to true (#713)
41
+ * (arteck) subscribe to state changes with one wildcard pattern instead of one subscription per writable state, which reduces the Redis pattern count and the load on the states DB (#706)
42
+ * (DutchmanNL) add pairing from ioBroker: the switch `info.permit_join` opens Zigbee2MQTT's permit join for 254 seconds (false closes it), `info.permit_join_timeout` counts the seconds left and `info.pairing_message` reports open/closed, joined devices and interview results. While Zigbee2MQTT is offline or unreachable the switch stays closed and a request is refused at once
43
+
44
+ ### 3.2.11 (2026-11-07)
45
+ * (DutchmanNL) fix devices staying unknown and commands being dropped after a WebSocket reconnect (e.g. heartbeat timeout): the bridge/devices and bridge/groups hash is now reset together with the caches
46
+
33
47
  ### 3.2.10 (2026-10-24)
34
48
  * (arteck) Dependencies have been updated
35
49
  * (arteck) fix high CPU load: skip reprocessing of unchanged bridge/devices and bridge/groups payloads (e.g. caused by a device in a rejoin/announce loop)
@@ -41,13 +55,6 @@ check you VM Settings
41
55
  ### 3.2.8 (2026-09-19)
42
56
  * (arteck) fix also for dummy mqtt if ws selected
43
57
 
44
- ### 3.2.7 (2026-09-19)
45
- * (arteck) fix available status direct after new device is paired
46
- * (arteck) fix internal mqtt handling
47
-
48
- ### 3.2.6 (2026-08-20)
49
- * (arteck) add wait time for internal mqtt server into settings
50
-
51
58
  ## License
52
59
 
53
60
  MIT License
@@ -63,5 +63,7 @@
63
63
  "Debug": "Debug",
64
64
  "Info": "Info",
65
65
  "Warning": "Warnung",
66
- "Error": "Fehler"
66
+ "Error": "Fehler",
67
+ "Always update received states, even when unchanged": "Empfangene Zustände immer aktualisieren, auch bei gleichem Wert",
68
+ "Refreshes the update timestamp (ts) for all received regular states. The change timestamp (lc) and action/event handling remain unchanged. Increases ioBroker load.": "Aktualisiert den Empfangszeitstempel (ts) aller empfangenen regulären Zustände. Änderungszeitstempel (lc) und Ereignisbehandlung bleiben unverändert. Erhöht die ioBroker-Last."
67
69
  }
@@ -63,5 +63,7 @@
63
63
  "Debug": "Debug",
64
64
  "Info": "Info",
65
65
  "Warning": "Warning",
66
- "Error": "Error"
66
+ "Error": "Error",
67
+ "Always update received states, even when unchanged": "Always update received states, even when unchanged",
68
+ "Refreshes the update timestamp (ts) for all received regular states. The change timestamp (lc) and action/event handling remain unchanged. Increases ioBroker load.": "Refreshes the update timestamp (ts) for all received regular states. The change timestamp (lc) and action/event handling remain unchanged. Increases ioBroker load."
67
69
  }
@@ -63,5 +63,7 @@
63
63
  "Debug": "Depuración",
64
64
  "Info": "Información",
65
65
  "Warning": "Advertencia",
66
- "Error": "Error"
66
+ "Error": "Error",
67
+ "Always update received states, even when unchanged": "Always update received states, even when unchanged",
68
+ "Refreshes the update timestamp (ts) for all received regular states. The change timestamp (lc) and action/event handling remain unchanged. Increases ioBroker load.": "Refreshes the update timestamp (ts) for all received regular states. The change timestamp (lc) and action/event handling remain unchanged. Increases ioBroker load."
67
69
  }
@@ -63,5 +63,7 @@
63
63
  "Debug": "Débogage",
64
64
  "Info": "Info",
65
65
  "Warning": "Avertissement",
66
- "Error": "Erreur"
66
+ "Error": "Erreur",
67
+ "Always update received states, even when unchanged": "Always update received states, even when unchanged",
68
+ "Refreshes the update timestamp (ts) for all received regular states. The change timestamp (lc) and action/event handling remain unchanged. Increases ioBroker load.": "Refreshes the update timestamp (ts) for all received regular states. The change timestamp (lc) and action/event handling remain unchanged. Increases ioBroker load."
67
69
  }
@@ -63,5 +63,7 @@
63
63
  "Debug": "Debug",
64
64
  "Info": "Info",
65
65
  "Warning": "Avviso",
66
- "Error": "Errore"
66
+ "Error": "Errore",
67
+ "Always update received states, even when unchanged": "Always update received states, even when unchanged",
68
+ "Refreshes the update timestamp (ts) for all received regular states. The change timestamp (lc) and action/event handling remain unchanged. Increases ioBroker load.": "Refreshes the update timestamp (ts) for all received regular states. The change timestamp (lc) and action/event handling remain unchanged. Increases ioBroker load."
67
69
  }
@@ -63,5 +63,7 @@
63
63
  "Debug": "Debug",
64
64
  "Info": "Info",
65
65
  "Warning": "Waarschuwing",
66
- "Error": "Fout"
66
+ "Error": "Fout",
67
+ "Always update received states, even when unchanged": "Always update received states, even when unchanged",
68
+ "Refreshes the update timestamp (ts) for all received regular states. The change timestamp (lc) and action/event handling remain unchanged. Increases ioBroker load.": "Refreshes the update timestamp (ts) for all received regular states. The change timestamp (lc) and action/event handling remain unchanged. Increases ioBroker load."
67
69
  }
@@ -63,5 +63,7 @@
63
63
  "Debug": "Debugowanie",
64
64
  "Info": "Informacja",
65
65
  "Warning": "Ostrzeżenie",
66
- "Error": "Błąd"
66
+ "Error": "Błąd",
67
+ "Always update received states, even when unchanged": "Always update received states, even when unchanged",
68
+ "Refreshes the update timestamp (ts) for all received regular states. The change timestamp (lc) and action/event handling remain unchanged. Increases ioBroker load.": "Refreshes the update timestamp (ts) for all received regular states. The change timestamp (lc) and action/event handling remain unchanged. Increases ioBroker load."
67
69
  }
@@ -63,5 +63,7 @@
63
63
  "Debug": "Depuração",
64
64
  "Info": "Info",
65
65
  "Warning": "Aviso",
66
- "Error": "Erro"
66
+ "Error": "Erro",
67
+ "Always update received states, even when unchanged": "Always update received states, even when unchanged",
68
+ "Refreshes the update timestamp (ts) for all received regular states. The change timestamp (lc) and action/event handling remain unchanged. Increases ioBroker load.": "Refreshes the update timestamp (ts) for all received regular states. The change timestamp (lc) and action/event handling remain unchanged. Increases ioBroker load."
67
69
  }
@@ -63,5 +63,7 @@
63
63
  "Debug": "Отладка",
64
64
  "Info": "Информация",
65
65
  "Warning": "Предупреждение",
66
- "Error": "Ошибка"
66
+ "Error": "Ошибка",
67
+ "Always update received states, even when unchanged": "Always update received states, even when unchanged",
68
+ "Refreshes the update timestamp (ts) for all received regular states. The change timestamp (lc) and action/event handling remain unchanged. Increases ioBroker load.": "Refreshes the update timestamp (ts) for all received regular states. The change timestamp (lc) and action/event handling remain unchanged. Increases ioBroker load."
67
69
  }
@@ -63,5 +63,7 @@
63
63
  "Debug": "Налагодження",
64
64
  "Info": "Інформація",
65
65
  "Warning": "Попередження",
66
- "Error": "Помилка"
66
+ "Error": "Помилка",
67
+ "Always update received states, even when unchanged": "Always update received states, even when unchanged",
68
+ "Refreshes the update timestamp (ts) for all received regular states. The change timestamp (lc) and action/event handling remain unchanged. Increases ioBroker load.": "Refreshes the update timestamp (ts) for all received regular states. The change timestamp (lc) and action/event handling remain unchanged. Increases ioBroker load."
67
69
  }
@@ -63,5 +63,7 @@
63
63
  "Debug": "调试",
64
64
  "Info": "信息",
65
65
  "Warning": "警告",
66
- "Error": "错误"
66
+ "Error": "错误",
67
+ "Always update received states, even when unchanged": "Always update received states, even when unchanged",
68
+ "Refreshes the update timestamp (ts) for all received regular states. The change timestamp (lc) and action/event handling remain unchanged. Increases ioBroker load.": "Refreshes the update timestamp (ts) for all received regular states. The change timestamp (lc) and action/event handling remain unchanged. Increases ioBroker load."
67
69
  }
@@ -551,6 +551,17 @@
551
551
  "newLine": true,
552
552
  "hidden": "data.coordinatorCheck != true"
553
553
  },
554
+ "alwaysUpdateStates": {
555
+ "type": "checkbox",
556
+ "label": "Always update received states, even when unchanged",
557
+ "help": "Refreshes the update timestamp (ts) for all received regular states. The change timestamp (lc) and action/event handling remain unchanged. Increases ioBroker load.",
558
+ "xs": 12,
559
+ "sm": 12,
560
+ "md": 12,
561
+ "lg": 12,
562
+ "xl": 12,
563
+ "newLine": true
564
+ },
554
565
  "alwaysUpdateOccupancyState": {
555
566
  "type": "checkbox",
556
567
  "label": "Always update state for occupancy when message arrives from zigbee2mqtt server (Only for true state). Increases load on ioBroker System",
package/io-package.json CHANGED
@@ -1,8 +1,34 @@
1
1
  {
2
2
  "common": {
3
3
  "name": "zigbee2mqtt",
4
- "version": "3.2.10",
4
+ "version": "3.2.12",
5
5
  "news": {
6
+ "3.2.12": {
7
+ "en": "the `available` state now reflects the availability reported by Zigbee2MQTT only; cached device data replayed on WebSocket connect no longer flips an explicitly offline device back to true (#713)\nsubscribe to state changes with one wildcard pattern instead of one subscription per writable state, which reduces the Redis pattern count and the load on the states DB (#706)\nadd pairing from ioBroker: the switch `info.permit_join` opens Zigbee2MQTT's permit join for 254 seconds (false closes it), `info.permit_join_timeout` counts the seconds left and `info.pairing_message` reports open/closed, joined devices and interview results. While Zigbee2MQTT is offline or unreachable the switch stays closed and a request is refused at once",
8
+ "de": "Der Status `verfügbar` entspricht nun nur der Verfügbarkeit von Zigbee2MQTT; über WebSocket Connect zwischengespeicherte Gerätedaten kehren nicht mehr explizit auf „true“ zurück (#713)\nStatusänderungen mit einem Platzhaltermuster statt einem pro beschreibbarem Status abonnieren, was die Anzahl der Redis-Muster und die Belastung der States-DB reduziert (#706)\nKopplung von ioBroker hinzufügen: Der Schalter `info.permit_join` öffnet Zigbee2MQTTs Permit Join für 254 Sekunden (false schließt ihn), `info.permit_join_timeout` zählt die verbleibenden Sekunden und `info.pairing_message` meldet geöffnete/geschlossene Geräte und Interview-Ergebnisse. Wenn Zigbee2MQTT offline oder unerreichbar ist, bleibt der Switch zu und lehnt sofort ab",
9
+ "ru": "состояние «доступно» теперь отражает доступность, о которой сообщает только ZigBee2MQTT; кэшированные данные устройства, воспроизводимые при подключении к WebSocket, больше не возвращают устройство, явно находящееся в автономном режиме (#713)\nподписывайтесь на изменения состояния с помощью одного шаблона подстановочных знаков вместо одной подписки на каждое доступное для записи состояние, что снижает количество шаблонов Redis и нагрузку на базу данных состояний (#706)\nдобавьте сопряжение от IOBroker: переключатель `info.permit_join` открывает разрешение Zigbee2mqtt на 254 секунды (false закрывает его), `info.permit_join_timeout` считает оставшиеся секунды, а `info.pairing_message` сообщает об открытом/закрытом, подключенных устройствах и результатах интервью. Пока Zigbee2mqtt находится в автономном режиме или недоступен, коммутатор остается закрытым, а запрос немедленно отклоняется.",
10
+ "pt": "o estado “disponível” agora reflete apenas a disponibilidade relatada pelo ZigBee2MQTT; dados em cache reproduzidos no WebSocket Connect não tornam mais verdadeiro (#713)\nassine mudanças de estado com um padrão curinga em vez de uma assinatura por estado gravável, o que reduz a contagem de padrões do Redis e a carga no banco de dados (#706)\nadicionar emparelhamento do IOBroker: o switch `info.permit_join` abre a permissão de junção do ZigBee2MQTT por 254 segundos (false a fecha), `info.permit_join_timeout` conta os segundos restantes e `info.pairing_message` relata dispositivos abertos/fechados, unidos e resultados de entrevistas. Enquanto o ZigBee2MQTT está offline ou inacessível, o switch fecha e o pedido é recusado.",
11
+ "nl": "de status „beschikbaar” geeft nu alleen de beschikbaarheid weer die door ZigBee2MQTT is gerapporteerd; apparaatgegevens in de cache die opnieuw worden afgespeeld op WebSocket connect zetten niet langer een apparaat dat expliciet offline is, terug naar true (#713)\nabonneer u op statuswijzigingen met één jokertekenpatroon in plaats van één abonnement per beschrijfbare staat, waardoor het aantal Redis-patronen afneemt en de database van de staat minder wordt belast (#706)\nkoppeling van IOBroker toevoegen: de switch `info.permit_join` opent ZigBee2MQTT's permit join gedurende 254 seconden (false sluit deze), `info.permit_join_timeout` telt de resterende seconden en `info.pairing_message` rapporteert open/gesloten, samengevoegde apparaten en interviewresultaten. Als ZigBee2mqtt offline of onbereikbaar is, blijft de switch gesloten en wordt een verzoek onmiddellijk afgewezen.",
12
+ "fr": "l'état « disponible » reflète désormais uniquement la disponibilité signalée par Zigbee2MQTT ; les données mises en cache et rediffusées sur WebSocket Connect ne redonnent plus la vérité à un appareil hors ligne (#713)\ns'abonner aux changements d'état avec un seul joker au lieu d'un abonnement par état inscriptible, ce qui réduit le nombre de modèles Redis et la charge sur la base de données des états (#706)\najouter le jumelage depuis IObroker : le switch « info.permit_join » ouvre Zigbee2mqtt pendant 254 secondes (false le ferme), « info.permit_join_timeout » compte les secondes restantes et « info.pairing_message » indique les appareils ouverts/fermés, joints et les résultats des entretiens. Lorsque Zigbee2MQTT est hors ligne ou inaccessible, le switch reste fermé et une demande est refusée",
13
+ "it": "lo stato «disponibile» ora riflette solo la disponibilità riportata da ZigBee2mqtt; i dati memorizzati nella cache riprodotti su WebSocket connect non tornano più a true (#713)\nsi iscrive ai cambi di stato con un jolly anziché un abbonamento per stato scrivibile, il che riduce il numero di pattern Redis e il carico sul DB degli stati (#706)\naggiungi abbinamento da IOBroker: lo switch `info.permit_join` apre il permesso join di Zigbee2mqtt per 254 secondi (false lo chiude), `info.permit_join_timeout` conta i secondi rimasti e `info.pairing_message` riporta i dispositivi aperti/chiusi e i risultati delle interviste. Mentre Zigbee2mqtt è offline o irraggiungibile, lo switch è chiuso e la richiesta è rifiutata",
14
+ "es": "el estado «disponible» ahora refleja únicamente la disponibilidad indicada por ZigBee2MQTT; los datos del dispositivo en caché que se reproducen en WebSocket connect ya no vuelven a ser verdaderos (#713)\nsuscribirse a los cambios de estado con un patrón comodín en lugar de una suscripción por estado grabable, lo que reduce el recuento de patrones de Redis y la carga en la base de datos de estados (#706)\nañadir emparejamiento desde IOBroker: el conmutador `info.permit_join` abre el permiso de unión de Zigbee2MQTT durante 254 segundos (si es falso lo cierra), `info.permit_join_timeout` cuenta los segundos que quedan e `info.pairing_message` informa de apertura/cerrada, dispositivos unidos y resultados de entrevistas. Mientras ZigBee2MQTT está desconectado o inaccesible, el switch permanece cerrado y se rechaza la solicitud",
15
+ "pl": "stan „dostępny” odzwierciedla teraz dostępność zgłoszoną tylko przez ZigBee2MQTT; buforowane dane urządzenia odtwarzane na WebSocket connect nie odwracają już urządzenia jawnie offline z powrotem do wartości true (#713)\nsubskrybuj zmiany stanu za pomocą jednego wzoru wieloznacznego zamiast jednej subskrypcji na stan zapisywny, co zmniejsza liczbę wzorców Redis i obciążenie bazy danych stanów (#706)\ndodaj parowanie z iOBroker: przełącznik `info.permit_join` otwiera zezwolenie na połączenie ZigBee2MQTT na 254 sekundy (false zamyka je), `info.permit_join_timeout` liczy pozostałe sekundy, a `info.pairing_message` zgłasza otwarte/zamknięte, połączone urządzenia i wyniki wywiadu. Podczas gdy ZigBee2MQTT jest offline lub nieosiągalny, przełącznik pozostaje zamknięty, a żądanie jest natychmiast odrzucane",
16
+ "uk": "стан «доступний» тепер відображає доступність, про яку повідомляє лише ZigBee2MQTT; кешовані дані пристрою, відтворені під час підключення WebSocket, більше не повертають явно офлайн-пристрій назад до true (#713)\nпідписатися на зміни стану за допомогою одного шаблону підстановки замість однієї підписки на стан запису, що зменшує кількість шаблонів Redis та навантаження на стани БД (#706)\nдодати сполучення з IObroker: перемикач `info.permit_join` відкриває приєднання дозволу ZigBee2mqtt на 254 секунди (false закриває його), `info.permit_join_timeout` підраховує залишені секунди, а `info.pairing_message` повідомляє про відкриті/закриті, приєднані пристрої та результати інтерв'ю. Поки ZigBee2mqtt знаходиться в автономному режимі або недосяжний, перемикач залишається закритим, і запит відразу відхиляється",
17
+ "zh-cn": "现在,“可用” 状态仅反映 Zigbee2mqtt 报告的可用性;在 WebSocket 连接上重放的缓存设备数据不再会将显式离线的设备恢复为真值 (#713)\n使用一种通配符模式订阅状态更改,而不是每个可写状态一次订阅,这减少了 Redis 模式数量和状态数据库的负载 (#706)\n添加来自 ioBroker 的配对:交换机 “info.permit_join” 打开 Zigbee2MQTT 的许可加入 254 秒(假将其关闭),“info.permit_join_timeout” 计算剩余的秒数,“info.pairing_message” 报告打开/关闭、加入的设备和面试结果。当 Zigbee2mqtt 处于离线状态或无法访问时,交换机将保持关闭状态,请求会立即被拒绝"
18
+ },
19
+ "3.2.11": {
20
+ "en": "fix devices staying unknown and commands being dropped after a WebSocket reconnect (e.g. heartbeat timeout): the bridge/devices and bridge/groups hash is now reset together with the caches",
21
+ "de": "beheben, dass Geräte und Befehle nach einer WebSocket-Verbindung unbekannt bleiben (z. B. Heartbeat-Timeout): Der Bridge/Geräte- und Bridge/Groups-Hash wird nun zusammen mit den Caches zurückgesetzt",
22
+ "ru": "исправляйте неизвестные устройства и отбрасываемые команды после повторного подключения к WebSocket (например, время ожидания сердцебиения): хэш моста/устройств и моста/групп теперь обнуляется вместе с кешами",
23
+ "pt": "corrige dispositivos desconhecidos e comandos perdidos após uma reconexão do WebSocket (ex. pulsação): o hash bridge/devices e bridge/groups agora é redefinido junto com os caches",
24
+ "nl": "apparaten repareren die onbekend blijven en opdrachten die worden weggelaten nadat een WebSocket-verbinding opnieuw is verbonden (bijv. een time-out voor de hartslag): de hash van de bridge/apparaten en bridge/groepen wordt nu samen met de caches gereset",
25
+ "fr": "réparer les appareils inconnus et les commandes supprimées après une reconnexion au WebSocket (par exemple, heartbeat timeout) : le hachage bridge/devices et bridge/groups est désormais réinitialisé avec les caches",
26
+ "it": "corregge i dispositivi sconosciuti e i comandi eliminati dopo una riconnessione WebSocket (ad es. heartbeat timeout): l'hash bridge/devices e bridge/groups è ora resettato insieme alle cache",
27
+ "es": "arreglar los dispositivos que permanecen desconocidos y los comandos que se omiten tras la reconexión de WebSocket (p. ej., tiempo de espera): el hash de puente/dispositivos y puente/grupos se restablece junto con las cachés",
28
+ "pl": "naprawa urządzeń pozostających nieznanych i poleceń wycofywanych po ponownym połączeniu WebSocket (np. przekroczenie czasu bicia serca): skrót mostów/urządzeń i mostów/grup jest teraz resetowany wraz z pamięcią podręczną",
29
+ "uk": "виправлення пристроїв, які залишаються невідомими, а команди скидаються після повторного підключення WebSocket (наприклад, тайм-аут серцебиття): хеш мост/пристроїв та мостів/груп тепер скидається разом із кешами",
30
+ "zh-cn": "修复在 WebSocket 重新连接(例如心跳超时)后设备保持未知状态和命令丢失的问题:网桥/设备和网桥/群组的哈希值现在与缓存一起重置"
31
+ },
6
32
  "3.2.10": {
7
33
  "en": "Dependencies have been updated\nfix high CPU load: skip reprocessing of unchanged bridge/devices and bridge/groups payloads (e.g. caused by a device in a rejoin/announce loop)\nfix restart loop",
8
34
  "de": "Abhängigkeiten wurden aktualisiert\nhohe CPU-Last beheben: überspringe die Neuverarbeitung unveränderter Bridge/Geräte- und Gruppen-Payloads (z. B. durch ein Gerät im Rejoin/Announce-Loop)\nNeustartschleife reparieren",
@@ -67,32 +93,6 @@
67
93
  "pl": "dodaj czas oczekiwania na wewnętrzny serwer MQTT do ustawień",
68
94
  "uk": "додати час очікування для внутрішнього сервера mqtt у налаштування",
69
95
  "zh-cn": "在设置中添加内部 MQTT 服务器的等待时间"
70
- },
71
- "3.2.5": {
72
- "en": "State updates lag issue https://github.com/arteck/ioBroker.zigbee2mqtt/issues/662",
73
- "de": "Problem mit verzögerten Statusaktualisierungen https://github.com/arteck/ioBroker.zigbee2mqtt/issues/662",
74
- "ru": "Проблема задержки обновления состояния: https://github.com/arteck/ioBroker.zigbee2mqtt/issues/662",
75
- "pt": "Problema de atraso nas atualizações de estado https://github.com/arteck/ioBroker.zigbee2mqtt/issues/662",
76
- "nl": "Probleem met vertraging bij statusupdates: https://github.com/arteck/ioBroker.zigbee2mqtt/issues/662",
77
- "fr": "Problème de latence lors de la mise à jour de l'état : https://github.com/arteck/ioBroker.zigbee2mqtt/issues/662",
78
- "it": "Problema di ritardo nell'aggiornamento dello stato https://github.com/arteck/ioBroker.zigbee2mqtt/issues/662",
79
- "es": "Problema de retraso en las actualizaciones de estado https://github.com/arteck/ioBroker.zigbee2mqtt/issues/662",
80
- "pl": "Problem z opóźnieniem aktualizacji stanu https://github.com/arteck/ioBroker.zigbee2mqtt/issues/662",
81
- "uk": "Проблема із затримкою оновлення стану https://github.com/arteck/ioBroker.zigbee2mqtt/issues/662",
82
- "zh-cn": "状态更新延迟问题 https://github.com/arteck/ioBroker.zigbee2mqtt/issues/662"
83
- },
84
- "3.2.4": {
85
- "en": "Dependencies have been updated\n",
86
- "de": "Die Abhängigkeiten wurden aktualisiert.\n",
87
- "ru": "Зависимости обновлены.\n",
88
- "pt": "As dependências foram atualizadas.\n",
89
- "nl": "Afhankelijkheden zijn bijgewerkt.\n",
90
- "fr": "Les dépendances ont été mises à jour\n",
91
- "it": "Le dipendenze sono state aggiornate\n",
92
- "es": "Se han actualizado las dependencias.\n",
93
- "pl": "Zaktualizowano zależności\n",
94
- "uk": "Залежності оновлено\n",
95
- "zh-cn": "依赖项已更新\n"
96
96
  }
97
97
  },
98
98
  "messages": [
@@ -265,6 +265,7 @@
265
265
  "coordinatorCheck": false,
266
266
  "coordinatorCheckLogLvl": "info",
267
267
  "coordinatorCheckCron": "0 3 * * *",
268
+ "alwaysUpdateStates": false,
268
269
  "alwaysUpdateOccupancyState": false,
269
270
  "alwaysUpdateAvailableState": false
270
271
  },
@@ -377,6 +378,46 @@
377
378
  },
378
379
  "native": {}
379
380
  },
381
+ {
382
+ "_id": "info.permit_join",
383
+ "type": "state",
384
+ "common": {
385
+ "name": "Pairing: allow new devices to join (true opens it for 254 seconds, false closes it)",
386
+ "type": "boolean",
387
+ "role": "switch",
388
+ "read": true,
389
+ "write": true,
390
+ "def": false
391
+ },
392
+ "native": {}
393
+ },
394
+ {
395
+ "_id": "info.permit_join_timeout",
396
+ "type": "state",
397
+ "common": {
398
+ "name": "Pairing: seconds until it closes",
399
+ "type": "number",
400
+ "role": "value",
401
+ "unit": "s",
402
+ "read": true,
403
+ "write": false,
404
+ "def": 0
405
+ },
406
+ "native": {}
407
+ },
408
+ {
409
+ "_id": "info.pairing_message",
410
+ "type": "state",
411
+ "common": {
412
+ "name": "Pairing: last message (opened, closed, device joined, interview)",
413
+ "type": "string",
414
+ "role": "text",
415
+ "read": true,
416
+ "write": false,
417
+ "def": ""
418
+ },
419
+ "native": {}
420
+ },
380
421
  {
381
422
  "_id": "",
382
423
  "type": "meta",
@@ -0,0 +1,263 @@
1
+ 'use strict';
2
+
3
+ /** Längste Anlerndauer, die Zigbee2MQTT für permit_join annimmt (Sekunden). */
4
+ const PERMIT_JOIN_MAX_TIME = 254;
5
+
6
+ /**
7
+ * Anlernen neuer Geräte (permit_join) über die States
8
+ * info.permit_join (Schalter), info.permit_join_timeout (Restsekunden) und
9
+ * info.pairing_message (letzte Meldung zum Anlernen, z.B. "Device 0x… joined").
10
+ *
11
+ * Der tatsächliche Zustand kommt immer von Zigbee2MQTT (bridge/info); der Schalter
12
+ * wird erst bestätigt (ack), wenn Zigbee2MQTT das Öffnen bzw. Schließen meldet.
13
+ * Geöffnet wird der Schalter nur, solange der letzte bridge/state "online" war.
14
+ */
15
+ class PermitJoinController {
16
+ /**
17
+ * Erstellt eine neue PermitJoinController-Instanz.
18
+ *
19
+ * @param {object} adapter Die ioBroker-Adapter-Instanz
20
+ * @param {() => number} [now] Uhr in Millisekunden (für Tests austauschbar)
21
+ */
22
+ constructor(adapter, now = Date.now) {
23
+ this.adapter = adapter;
24
+ this.now = now;
25
+ // letzter von Zigbee2MQTT gemeldeter Zustand (null = noch unbekannt)
26
+ this.open = null;
27
+ // Zeitpunkt (ms), zu dem das Anlernen endet; 0 = kein bekanntes Ende
28
+ this.endTime = 0;
29
+ // Intervall des Sekunden-Countdowns, solange das Anlernen offen ist
30
+ this.countdownTimer = null;
31
+ // true nach allTimerClear(): kein neuer Countdown mehr
32
+ this.unloaded = false;
33
+ // letzter bridge/state: true = online, false = offline gemeldet,
34
+ // null = unbekannt (Adapterstart oder Verbindung zu Zigbee2MQTT weg)
35
+ this.bridgeOnline = null;
36
+ // bridge/info, das bei unbekanntem bridge/state eintraf (retained-Nachrichten kommen
37
+ // nach dem Verbinden in beliebiger Reihenfolge); wird bei "online" übernommen
38
+ this.pendingInfo = null;
39
+ }
40
+
41
+ /**
42
+ * Erzeugt die Zigbee2MQTT-Anfrage zum Öffnen (true) oder Schließen (false) des Anlernens.
43
+ * "time" verlangt Zigbee2MQTT 2.x, "value" Zigbee2MQTT 1.x; beide ignorieren das jeweils andere Feld.
44
+ *
45
+ * @param {ioBroker.StateValue} val Gewünschter Zustand
46
+ * @returns {{topic: string, payload: {value: boolean, time: number}}} Die Z2M-Nachricht
47
+ */
48
+ static createRequest(val) {
49
+ const open = val === true || val === 'true' || val === 1;
50
+ return {
51
+ topic: 'bridge/request/permit_join',
52
+ payload: { value: open, time: open ? PERMIT_JOIN_MAX_TIME : 0 },
53
+ };
54
+ }
55
+
56
+ /**
57
+ * Übernimmt permit_join aus bridge/info (wird von Zigbee2MQTT bei jeder Änderung neu gesendet).
58
+ *
59
+ * @param {object} payload Der Payload des bridge/info-Topics
60
+ */
61
+ async onBridgeInfo(payload) {
62
+ if (!payload || typeof payload.permit_join !== 'boolean') {
63
+ return;
64
+ }
65
+ if (this.bridgeOnline !== true) {
66
+ // Zigbee2MQTT nicht online: nie öffnen (z.B. ein veraltetes retained bridge/info).
67
+ // Bei unbekanntem Zustand wird es übernommen, sobald bridge/state "online" meldet.
68
+ this.pendingInfo = this.bridgeOnline === null ? payload : null;
69
+ return;
70
+ }
71
+ let open = payload.permit_join;
72
+ let remaining = 0;
73
+ if (open) {
74
+ if (typeof payload.permit_join_end === 'number') {
75
+ // Zigbee2MQTT 2.x: Endzeitpunkt in ms
76
+ remaining = Math.ceil((payload.permit_join_end - this.now()) / 1000);
77
+ // Ein (z.B. retained) bridge/info, dessen Ende schon vorbei ist, gilt als geschlossen
78
+ if (remaining <= 0) {
79
+ open = false;
80
+ }
81
+ } else if (typeof payload.permit_join_timeout === 'number') {
82
+ // Zigbee2MQTT 1.x: Restsekunden
83
+ remaining = payload.permit_join_timeout;
84
+ }
85
+ }
86
+ remaining = open ? Math.min(Math.max(remaining, 0), PERMIT_JOIN_MAX_TIME) : 0;
87
+
88
+ const wasOpen = this.open;
89
+ this.open = open;
90
+
91
+ await this.adapter.setStateChangedAsync('info.permit_join', open, true);
92
+ await this.adapter.setStateChangedAsync('info.permit_join_timeout', remaining, true);
93
+
94
+ if (open && remaining > 0) {
95
+ this.endTime = this.now() + remaining * 1000;
96
+ this.startCountdown();
97
+ } else {
98
+ this.endTime = 0;
99
+ this.stopCountdown();
100
+ }
101
+
102
+ if (open && wasOpen !== true) {
103
+ await this.setMessage(remaining > 0 ? `Pairing open for ${remaining} seconds` : 'Pairing open');
104
+ } else if (!open && wasOpen === true) {
105
+ await this.setMessage('Pairing closed');
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Übernimmt bridge/state. "online" übernimmt ein vorher eingetroffenes bridge/info;
111
+ * jeder andere Zustand schließt das Anlernen, bis Zigbee2MQTT wieder "online" meldet.
112
+ *
113
+ * @param {boolean} online true, wenn Zigbee2MQTT "online" meldet
114
+ */
115
+ async onBridgeState(online) {
116
+ if (!online) {
117
+ await this.close('Zigbee2MQTT offline', false);
118
+ return;
119
+ }
120
+ this.bridgeOnline = true;
121
+ const pending = this.pendingInfo;
122
+ this.pendingInfo = null;
123
+ if (pending) {
124
+ await this.onBridgeInfo(pending);
125
+ }
126
+ }
127
+
128
+ /**
129
+ * Meldet Beitritt und Interview neuer Geräte aus bridge/event in info.pairing_message.
130
+ *
131
+ * @param {object} payload Der Payload des bridge/event-Topics
132
+ */
133
+ async onBridgeEvent(payload) {
134
+ if (!payload || typeof payload !== 'object') {
135
+ return;
136
+ }
137
+ const data = payload.data || {};
138
+ const device = data.ieee_address || data.friendly_name;
139
+ if (!device) {
140
+ return;
141
+ }
142
+
143
+ if (payload.type === 'device_joined') {
144
+ await this.setMessage(`Device ${device} joined`);
145
+ } else if (payload.type === 'device_interview') {
146
+ if (data.status === 'started') {
147
+ await this.setMessage(`Interview started: ${device}`);
148
+ } else if (data.status === 'successful') {
149
+ const def = data.definition;
150
+ const what = def && (def.vendor || def.model)
151
+ ? [def.vendor, def.model].filter((x) => x).join(' ')
152
+ : 'device not supported';
153
+ await this.setMessage(`Interview successful: ${device}, ${what}`);
154
+ } else if (data.status === 'failed') {
155
+ await this.setMessage(`Interview failed: ${device}`);
156
+ }
157
+ }
158
+ }
159
+
160
+ /**
161
+ * Wertet die Antwort auf bridge/request/permit_join aus. Bei einem Fehler wird der
162
+ * Schalter auf den letzten von Zigbee2MQTT gemeldeten Zustand zurückgesetzt.
163
+ *
164
+ * @param {object} payload Der Payload des bridge/response/permit_join-Topics
165
+ */
166
+ async onPermitJoinResponse(payload) {
167
+ if (!payload || payload.status !== 'error') {
168
+ return;
169
+ }
170
+ await this.onRequestFailed(payload.error || 'unknown error');
171
+ }
172
+
173
+ /**
174
+ * Die Anfrage zum Öffnen/Schließen kam nicht bei Zigbee2MQTT an oder wurde abgelehnt:
175
+ * Schalter auf den letzten von Zigbee2MQTT gemeldeten Zustand zurücksetzen (ack) und den Grund melden.
176
+ *
177
+ * @param {string} reason Grund, z.B. "no connection to Zigbee2MQTT"
178
+ */
179
+ async onRequestFailed(reason) {
180
+ await this.adapter.setStateAsync('info.permit_join', this.open === true, true);
181
+ await this.setMessage(`Pairing failed: ${reason}`);
182
+ }
183
+
184
+ /**
185
+ * Zigbee2MQTT ist nicht (mehr) erreichbar oder der Adapter startet neu: Das Anlernen wird
186
+ * als geschlossen gemeldet, bis Zigbee2MQTT mit bridge/info wieder den echten Zustand liefert.
187
+ * Eine Meldung gibt es nur, wenn das Anlernen bis dahin offen war.
188
+ * Läuft im selben Mutex wie messageParse (siehe closePermitJoin in main.js).
189
+ *
190
+ * @param {string} reason Grund, z.B. "connection to Zigbee2MQTT lost"
191
+ * @param {false|null} [bridgeOnline] false: Zigbee2MQTT meldet offline; null: Zustand unbekannt
192
+ */
193
+ async close(reason, bridgeOnline = null) {
194
+ this.bridgeOnline = bridgeOnline;
195
+ this.pendingInfo = null;
196
+ this.stopCountdown();
197
+ this.endTime = 0;
198
+ const state = await this.adapter.getStateAsync('info.permit_join');
199
+ const wasOpen = this.open === true || !!(state && state.val === true);
200
+ this.open = false;
201
+ if (!state || state.val !== false || state.ack !== true) {
202
+ await this.adapter.setStateAsync('info.permit_join', false, true);
203
+ }
204
+ await this.adapter.setStateChangedAsync('info.permit_join_timeout', 0, true);
205
+ if (wasOpen) {
206
+ await this.setMessage(`Pairing closed: ${reason}`);
207
+ }
208
+ }
209
+
210
+ /**
211
+ * Schreibt die Restsekunden; beendet den Countdown bei 0.
212
+ * Das Schließen selbst meldet Zigbee2MQTT anschließend über bridge/info.
213
+ */
214
+ async countdownTick() {
215
+ const remaining = Math.max(0, Math.ceil((this.endTime - this.now()) / 1000));
216
+ if (remaining === 0) {
217
+ this.stopCountdown();
218
+ }
219
+ await this.adapter.setStateChangedAsync('info.permit_join_timeout', remaining, true);
220
+ }
221
+
222
+ /** Startet den Sekunden-Countdown (falls nicht schon aktiv und der Adapter nicht entladen wird). */
223
+ startCountdown() {
224
+ if (this.countdownTimer || this.unloaded) {
225
+ return;
226
+ }
227
+ this.countdownTimer = setInterval(() => {
228
+ this.countdownTick().catch((e) => this.adapter.log.error(`permit_join countdown: ${e.message || e}`));
229
+ }, 1000);
230
+ }
231
+
232
+ /** Stoppt den Sekunden-Countdown. */
233
+ stopCountdown() {
234
+ if (this.countdownTimer) {
235
+ clearInterval(this.countdownTimer);
236
+ this.countdownTimer = null;
237
+ }
238
+ }
239
+
240
+ /**
241
+ * Schreibt eine Meldung in info.pairing_message und ins Log.
242
+ *
243
+ * @param {string} message Die Meldung
244
+ */
245
+ async setMessage(message) {
246
+ this.adapter.log.info(message);
247
+ await this.adapter.setStateAsync('info.pairing_message', message, true);
248
+ }
249
+
250
+ /**
251
+ * Stoppt alle Timer (beim Entladen des Adapters). Danach startet auch ein noch in der
252
+ * messageParse-Warteschlange stehendes bridge/info keinen neuen Countdown mehr.
253
+ */
254
+ allTimerClear() {
255
+ this.unloaded = true;
256
+ this.stopCountdown();
257
+ }
258
+ }
259
+
260
+ module.exports = {
261
+ PermitJoinController,
262
+ PERMIT_JOIN_MAX_TIME,
263
+ };
@@ -231,25 +231,17 @@ class StatesController {
231
231
 
232
232
  // COLLECTION: Alle non-action state write-Promises sammeln und dann parallel ausführen
233
233
  const stateWrites = [];
234
- // Flag für available-Update (wenn last_seen vorhanden und config aktiv, oder generell
235
- // wenn echte Nutzdaten empfangen wurden – siehe Begründung weiter unten)
234
+ // Flag für available-Update über die (optionale) last_seen-Auswertung.
235
+ //
236
+ // WICHTIG: Der "available"-State wird ansonsten AUSSCHLIESSLICH aus den
237
+ // Availability-Meldungen von Zigbee2MQTT gesetzt (Topic "<device>/availability",
238
+ // vom Adapter zu { available: <bool> } umgebaut) sowie beim Verbindungsverlust
239
+ // über setAllAvailableToFalse(). Es gibt bewusst KEINE Heuristik mehr, die aus
240
+ // empfangenen Nutzdaten auf "online" schließt (Issue #713): Diese Heuristik hat
241
+ // die explizite "offline"-Meldung überschrieben, weil Z2M beim WebSocket-Connect
242
+ // direkt danach die gecachten Gerätedaten erneut sendet.
236
243
  let needSetAvailableTrue = false;
237
244
 
238
- // Bugfix: Wenn eine Nachricht ausschließlich das "available"-Property enthält
239
- // (z.B. aus dem ".../availability"-Topic oder bridge/event device_leave), soll
240
- // dessen Wert unverändert übernommen werden. Enthält die Nachricht jedoch
241
- // zusätzliche/echte Nutzdaten (state, brightness, temperature, ...), beweist das
242
- // bereits, dass das Gerät aktiv kommuniziert hat – unabhängig davon, ob Zigbee2MQTT
243
- // das (per Default deaktivierte) "availability"-Feature nutzt oder last_seen sendet
244
- // (advanced.last_seen ist bei Z2M ebenfalls per Default "disable"). Ohne diesen Fix
245
- // bleibt der "available"-State nach einem MQTT-/Adapter-Neustart dauerhaft auf
246
- // "false", obwohl die Geräte normal erreichbar und schaltbar sind.
247
- const payloadKeys = Object.keys(messageObj.payload);
248
- const hasOnlyAvailableKey = payloadKeys.length > 0 && payloadKeys.every((k) => k === 'available');
249
- if (!hasOnlyAvailableKey && payloadKeys.length > 0 && !device.ieee_address.includes('group')) {
250
- needSetAvailableTrue = true;
251
- }
252
-
253
245
  for (let [key, value] of Object.entries(messageObj.payload)) {
254
246
  if (value === undefined || value === null) {
255
247
  continue;
@@ -295,7 +287,7 @@ class StatesController {
295
287
  // write additional state without awaiting
296
288
  stateWrites.push((async () => {
297
289
  try {
298
- await this.adapter.setStateChangedAsync(`${fullPath}.${key}`, value, true);
290
+ await this.setReceivedStateAsync(`${fullPath}.${key}`, value);
299
291
  } catch (e) {
300
292
  this.adapter.log.warn(`Cannot set additional state ${fullPath}.${key}: ${e}`);
301
293
  }
@@ -342,7 +334,7 @@ class StatesController {
342
334
  // schedule changed-safe write
343
335
  stateWrites.push((async () => {
344
336
  try {
345
- await this.setStateChangedSafelyAsync(stateName, state.getter(messageObj.payload));
337
+ await this.setReceivedStateAsync(stateName, state.getter(messageObj.payload));
346
338
  } catch (e) {
347
339
  this.adapter.log.warn(`Cannot set state ${stateName}: ${e}`);
348
340
  }
@@ -350,7 +342,7 @@ class StatesController {
350
342
  } else {
351
343
  stateWrites.push((async () => {
352
344
  try {
353
- await this.setStateChangedSafelyAsync(stateName, value);
345
+ await this.setReceivedStateAsync(stateName, value);
354
346
  } catch (e) {
355
347
  this.adapter.log.warn(`Cannot set state ${stateName}: ${e}`);
356
348
  }
@@ -441,6 +433,24 @@ class StatesController {
441
433
  await this.adapter.setStateChangedAsync(stateName, value, true);
442
434
  }
443
435
 
436
+ /**
437
+ * Write a regular field received from Zigbee2MQTT, optionally refreshing unchanged values.
438
+ * Action/event states use their existing dedicated handlers instead.
439
+ *
440
+ * @param {string} stateName State identifier
441
+ * @param {ioBroker.StateValue} value Received value
442
+ */
443
+ async setReceivedStateAsync(stateName, value) {
444
+ if (value === undefined || value === null) {
445
+ return;
446
+ }
447
+ if (this.adapter.config.alwaysUpdateStates === true) {
448
+ await this.adapter.setStateAsync(stateName, value, true);
449
+ } else {
450
+ await this.setStateChangedSafelyAsync(stateName, value);
451
+ }
452
+ }
453
+
444
454
  /**
445
455
  * Setzt einen State sofort auf den angegebenen Wert und – nur bei value=true –
446
456
  * nach Ablauf des Timeouts automatisch zurück auf false (Button/Event-Reset).
@@ -499,25 +509,26 @@ class StatesController {
499
509
  }
500
510
 
501
511
  /**
502
- * Meldet alle bisherigen State-Subscriptions ab und subscribt neu
503
- * nur auf beschreibbare States aller bekannten Geräte und Gruppen.
512
+ * Meldet alle bisherigen State-Subscriptions ab und subscribt neu.
513
+ *
514
+ * PERFORMANCE (Issue #706): Früher wurde jeder schreibbare State einzeln
515
+ * subscribed (~1.100 Patterns). Mit einer Redis-States-DB registriert der
516
+ * js-controller jede Subscription als PSUBSCRIBE-Pattern, und Redis prüft
517
+ * bei jedem PUBLISH der gesamten Installation alle Patterns. Deshalb wird
518
+ * jetzt genau EIN Wildcard-Pattern verwendet.
519
+ *
520
+ * Die Filterung auf schreibbare States passiert dafür in
521
+ * Z2mController.createZ2MMessage() (Guard auf `deviceState.write`).
522
+ *
523
+ * WICHTIG: unsubscribe/subscribe werden awaited, damit das Unsubscribe
524
+ * abgeschlossen ist, bevor neu subscribed wird – sonst überlappen die
525
+ * Patterns und der js-controller liefert Events doppelt.
504
526
  */
505
- subscribeWritableStates() {
506
- // Alle bestehenden State-Subscriptions zuerst abmelden
507
- this.adapter.unsubscribeStates('*');
508
- for (const device of this.groupCache.concat(this.deviceCache)) {
509
- if (!device || !Array.isArray(device.states)) {
510
- continue;
511
- }
512
- for (const state of device.states) {
513
- if (state && state.write === true) {
514
- this.adapter.subscribeStates(`${device.ieee_address}.${state.id}`);
515
- }
516
- }
517
- }
518
- this.adapter.subscribeStates('info.debugmessages');
519
- this.adapter.subscribeStates('info.logfilter');
520
- this.adapter.subscribeStates('info.coordinator_check');
527
+ async subscribeWritableStates() {
528
+ // Alle bestehenden State-Subscriptions zuerst abmelden (inkl. 'info.*',
529
+ // die vom Wildcard-Pattern mit abgedeckt werden).
530
+ await this.adapter.unsubscribeStatesAsync('*');
531
+ await this.adapter.subscribeStatesAsync('*');
521
532
  }
522
533
 
523
534
  /**
@@ -158,10 +158,19 @@ class WebsocketController {
158
158
  } catch (err) {
159
159
  this.adapter.log.error(`close handler setAllAvailableToFalse error: ${err}`);
160
160
  }
161
+ if (typeof this.adapter.closePermitJoin === 'function') {
162
+ await this.adapter.closePermitJoin('connection to Zigbee2MQTT lost');
163
+ }
161
164
 
162
165
  // Caches leeren
163
166
  this.adapter.deviceCache.length = 0;
164
167
  this.adapter.groupCache.length = 0;
168
+ // Mit den Caches auch den bridge/devices-/bridge/groups-Hash (Fix #692) verwerfen:
169
+ // Z2M sendet beim Reconnect dieselben Listen erneut. Ohne Reset werden sie als
170
+ // "unchanged" übersprungen und deviceCache/groupCache bleiben leer (z.B. nach
171
+ // "WebSocket connection timed out", wenn kein bridge/state offline eintrifft).
172
+ this.adapter.lastDevicesJson = null;
173
+ this.adapter.lastGroupsJson = null;
165
174
  for (const key of Object.keys(this.adapter.createCache)) {
166
175
  delete this.adapter.createCache[key];
167
176
  }
@@ -181,16 +190,19 @@ class WebsocketController {
181
190
  * Sendet eine serialisierte Nachricht an Zigbee2MQTT über den WebSocket.
182
191
  *
183
192
  * @param {string} message JSON-String der zu sendenden Nachricht
193
+ * @returns {boolean} true wenn die Nachricht an den WebSocket übergeben wurde
184
194
  */
185
195
  send(message) {
186
196
  if (!this.wsClient || this.wsClient.readyState !== WebSocket.OPEN) {
187
197
  this.adapter.log.warn('Cannot set State, no websocket connection to Zigbee2MQTT!');
188
- return;
198
+ return false;
189
199
  }
190
200
  try {
191
201
  this.wsClient.send(message);
202
+ return true;
192
203
  } catch (err) {
193
204
  this.adapter.log.error(`WebSocket send error: ${err && err.message ? err.message : String(err)}`);
205
+ return false;
194
206
  }
195
207
  }
196
208
 
@@ -1,3 +1,5 @@
1
+ const { PermitJoinController } = require('./permitJoinController');
2
+
1
3
  /**
2
4
  * Übersetzt ioBroker-State-Änderungen in Zigbee2MQTT-MQTT-Nachrichten
3
5
  * und leitet Z2M-Log-Nachrichten in den ioBroker-Logger weiter.
@@ -18,6 +20,26 @@ class Z2mController {
18
20
  this.logCustomizations = logCustomizations;
19
21
  }
20
22
 
23
+ /**
24
+ * Prüft exakt, ob die State-ID ein info-State dieses Adapters ist.
25
+ *
26
+ * Bewusst kein `endsWith()`: seit der Wildcard-Subscription (siehe
27
+ * StatesController.subscribeWritableStates) erreichen uns alle State-Changes
28
+ * des eigenen Namespace, daher darf kein Geräte-State, der zufällig auf
29
+ * "...info.<name>" endet, als Adapter-Kommando interpretiert werden.
30
+ *
31
+ * @param {string} id Vollständige State-ID
32
+ * @param {string} name Name des info-States, z.B. "permit_join"
33
+ * @returns {boolean} true wenn die ID exakt auf diesen info-State zeigt
34
+ */
35
+ isOwnInfoState(id, name) {
36
+ if (id === `${this.adapter.namespace}.info.${name}`) {
37
+ return true;
38
+ }
39
+ // Interner Cron-Trigger für den Coordinator-Check (siehe main.js)
40
+ return id.endsWith(`._.info.${name}`);
41
+ }
42
+
21
43
  /**
22
44
  * Erzeugt aus einer ioBroker-State-Änderung eine Zigbee2MQTT-Nachricht.
23
45
  * Gibt null zurück wenn kein Gerät/State gefunden wurde oder der Setter undefined liefert.
@@ -33,11 +55,15 @@ class Z2mController {
33
55
  return;
34
56
  }
35
57
 
36
- if (id.endsWith('info.coordinator_check')) {
58
+ if (this.isOwnInfoState(id, 'coordinator_check')) {
37
59
  // Fix 1: Z2M erwartet JSON-Objekt {} nicht leeren String ''
38
60
  return { topic: 'bridge/request/coordinator_check', payload: {} };
39
61
  }
40
62
 
63
+ if (this.isOwnInfoState(id, 'permit_join')) {
64
+ return PermitJoinController.createRequest(state.val);
65
+ }
66
+
41
67
  const ieee_address = splitedID[2];
42
68
  const stateName = splitedID[3];
43
69
 
@@ -51,6 +77,17 @@ class Z2mController {
51
77
  return;
52
78
  }
53
79
 
80
+ // Issue #706: Durch die Wildcard-Subscription erhalten wir nicht mehr nur
81
+ // die schreibbaren States, sondern alle. Ein (z.B. per Script gesetzter)
82
+ // Wert auf einem read-only State darf deshalb nicht als Kommando an
83
+ // Zigbee2MQTT gehen.
84
+ if (deviceState.write !== true) {
85
+ this.adapter.log.debug(
86
+ `${device.ieee_address} state: ${stateName} is not writable, skipping`
87
+ );
88
+ return;
89
+ }
90
+
54
91
  let stateVal = state.val;
55
92
  if (deviceState.setter) {
56
93
  // Fix 3: setter kann crashen (z.B. ungültiger Farbwert) → try/catch
package/main.js CHANGED
@@ -14,6 +14,7 @@ const DeviceController = require('./lib/deviceController').DeviceController;
14
14
  const StatesController = require('./lib/statesController').StatesController;
15
15
  const WebsocketController = require('./lib/websocketController').WebsocketController;
16
16
  const MqttServerController = require('./lib/mqttServerController').MqttServerController;
17
+ const PermitJoinController = require('./lib/permitJoinController').PermitJoinController;
17
18
 
18
19
  class Zigbee2mqtt extends core.Adapter {
19
20
  /**
@@ -39,6 +40,7 @@ class Zigbee2mqtt extends core.Adapter {
39
40
  this.z2mController = null;
40
41
  this.websocketController = null;
41
42
  this.mqttServerController = null;
43
+ this.permitJoinController = null;
42
44
  this.messageParseMutex = Promise.resolve();
43
45
  this.mqttReconnectAttempts = 0;
44
46
  // Fallback: Wenn nach dem Verbindungsaufbau kein bridge/devices eintrifft
@@ -87,6 +89,9 @@ class Zigbee2mqtt extends core.Adapter {
87
89
  this.createCache
88
90
  );
89
91
  this.z2mController = new Z2mController(this, this.deviceCache, this.groupCache, this.logCustomizations);
92
+ this.permitJoinController = new PermitJoinController(this);
93
+ // Ein beim letzten Lauf offenes Anlernen gilt bis zum ersten bridge/info als geschlossen
94
+ await this.closePermitJoin('adapter restarted');
90
95
 
91
96
  adapterInfo(this.config, this.log);
92
97
 
@@ -205,6 +210,7 @@ class Zigbee2mqtt extends core.Adapter {
205
210
  await this.setStateChangedAsync('info.connection', false, true).catch((e) =>
206
211
  this.log.error(`MQTT offline setStateChangedAsync error: ${e}`)
207
212
  );
213
+ await this.closePermitJoin('connection to Zigbee2MQTT lost');
208
214
  try {
209
215
  if (this.statesController) {
210
216
  await this.statesController.setAllAvailableToFalse();
@@ -219,6 +225,7 @@ class Zigbee2mqtt extends core.Adapter {
219
225
  await this.setStateChangedAsync('info.connection', false, true).catch((e) =>
220
226
  this.log.error(`MQTT close setStateChangedAsync error: ${e}`)
221
227
  );
228
+ await this.closePermitJoin('connection to Zigbee2MQTT lost');
222
229
  });
223
230
 
224
231
  this.mqttClient.on('error', (err) => {
@@ -316,6 +323,85 @@ class Zigbee2mqtt extends core.Adapter {
316
323
  this.scheduleDeviceReloadFallback(`runtime:${trigger}`, 2500, true);
317
324
  }
318
325
 
326
+ /**
327
+ * Führt fn in derselben Warteschlange (Mutex) wie messageParse aus, damit es sich nicht
328
+ * mit einer gerade laufenden Nachricht verzahnt. Nie aus messageParse heraus aufrufen
329
+ * (würde auf sich selbst warten).
330
+ *
331
+ * @param {() => Promise<void>} fn Die auszuführende Funktion
332
+ */
333
+ async runSerialized(fn) {
334
+ const prev = this.messageParseMutex;
335
+ const run = (async () => {
336
+ try {
337
+ await prev;
338
+ } catch {
339
+ // ignore
340
+ }
341
+ await fn();
342
+ })();
343
+ // vor dem ersten await eingereiht; die Warteschlange läuft auch weiter, wenn fn wirft
344
+ this.messageParseMutex = run.catch(() => {});
345
+ await run;
346
+ }
347
+
348
+ /**
349
+ * Meldet das Anlernen (permit_join) als geschlossen, z.B. wenn Zigbee2MQTT nicht mehr
350
+ * erreichbar ist. Läuft im Mutex von messageParse: ein bridge/info davor ist dann ganz
351
+ * verarbeitet, eines danach öffnet erst wieder nach bridge/state "online".
352
+ * Fehler werden nur geloggt, damit der aufrufende Ablauf weiterläuft.
353
+ *
354
+ * @param {string} reason Grund für info.pairing_message
355
+ */
356
+ async closePermitJoin(reason) {
357
+ const controller = this.permitJoinController;
358
+ if (!controller) {
359
+ return;
360
+ }
361
+ await this.runSerialized(async () => {
362
+ try {
363
+ await controller.close(reason);
364
+ } catch (e) {
365
+ this.log.error(`closePermitJoin error: ${e && e.message ? e.message : String(e)}`);
366
+ }
367
+ });
368
+ }
369
+
370
+ /**
371
+ * Gibt bridge/state an das Anlernen weiter. Nur aus messageParse aufrufen (hält den Mutex schon).
372
+ * Fehler werden nur geloggt.
373
+ *
374
+ * @param {boolean} online true, wenn Zigbee2MQTT "online" meldet
375
+ */
376
+ async permitJoinBridgeState(online) {
377
+ if (!this.permitJoinController) {
378
+ return;
379
+ }
380
+ try {
381
+ await this.permitJoinController.onBridgeState(online);
382
+ } catch (e) {
383
+ this.log.error(`permit_join bridge/state error: ${e && e.message ? e.message : String(e)}`);
384
+ }
385
+ }
386
+
387
+ /**
388
+ * Eine Nachricht an Zigbee2MQTT konnte nicht gesendet werden. Betrifft sie permit_join,
389
+ * wird der Schalter auf den letzten bekannten Zustand zurückgesetzt und der Grund gemeldet.
390
+ *
391
+ * @param {{topic: string}} message Die nicht gesendete Z2M-Nachricht
392
+ * @param {string} reason Grund für info.pairing_message
393
+ */
394
+ async reportSendFailure(message, reason) {
395
+ if (!this.permitJoinController || !message || message.topic !== 'bridge/request/permit_join') {
396
+ return;
397
+ }
398
+ try {
399
+ await this.permitJoinController.onRequestFailed(reason);
400
+ } catch (e) {
401
+ this.log.error(`reportSendFailure error: ${e && e.message ? e.message : String(e)}`);
402
+ }
403
+ }
404
+
319
405
  /**
320
406
  * Lädt die Geräteliste einmalig nach, falls nach dem Verbindungsaufbau
321
407
  * (MQTT-connect ODER WebSocket-open) innerhalb von 5s kein bridge/devices
@@ -496,6 +582,9 @@ class Zigbee2mqtt extends core.Adapter {
496
582
  break;
497
583
  }
498
584
  case 'bridge/info':
585
+ if (this.permitJoinController) {
586
+ await this.permitJoinController.onBridgeInfo(messageObj.payload);
587
+ }
499
588
  if (this.showInfo && messageObj.payload) {
500
589
  await zigbee2mqttInfo(messageObj.payload, this.log);
501
590
  if (messageObj.payload.config && messageObj.payload.version) {
@@ -509,6 +598,8 @@ class Zigbee2mqtt extends core.Adapter {
509
598
  ? messageObj.payload.state
510
599
  : messageObj.payload;
511
600
  if (bridgeState !== 'online') {
601
+ // zuerst: ein Fehler in setAllAvailableToFalse darf das Schließen nicht überspringen
602
+ await this.permitJoinBridgeState(false);
512
603
  await this.statesController.setAllAvailableToFalse();
513
604
  this.showInfo = true;
514
605
  // Fix #692: nach einem Bridge-Offline-Event (z.B. Reconnect) den
@@ -520,6 +611,9 @@ class Zigbee2mqtt extends core.Adapter {
520
611
  this.lastGroupsJson = null;
521
612
  }
522
613
  await this.setStateChangedAsync('info.connection', bridgeState === 'online', true);
614
+ if (bridgeState === 'online') {
615
+ await this.permitJoinBridgeState(true);
616
+ }
523
617
  break;
524
618
  }
525
619
  case 'bridge/devices':
@@ -580,7 +674,15 @@ class Zigbee2mqtt extends core.Adapter {
580
674
  }
581
675
  break;
582
676
  }
677
+ case 'bridge/response/permit_join':
678
+ if (this.permitJoinController) {
679
+ await this.permitJoinController.onPermitJoinResponse(messageObj.payload);
680
+ }
681
+ break;
583
682
  case 'bridge/event': {
683
+ if (this.permitJoinController) {
684
+ await this.permitJoinController.onBridgeEvent(messageObj.payload);
685
+ }
584
686
  const evType = messageObj.payload && messageObj.payload.type;
585
687
  const evData = messageObj.payload && messageObj.payload.data;
586
688
  if (evType === 'device_announce' && evData && evData.friendly_name) {
@@ -605,7 +707,6 @@ class Zigbee2mqtt extends core.Adapter {
605
707
  case 'bridge/response/device/configure':
606
708
  case 'bridge/response/device/remove':
607
709
  case 'bridge/response/device/options':
608
- case 'bridge/response/permit_join':
609
710
  case 'bridge/response/networkmap':
610
711
  case 'bridge/response/options':
611
712
  case 'bridge/response/restart':
@@ -840,6 +941,10 @@ class Zigbee2mqtt extends core.Adapter {
840
941
  } catch (e) {
841
942
  this.log.error(`[onUnload] Fehler beim Zurücksetzen der States-Timer: ${e.message}`);
842
943
  }
944
+ await this.closePermitJoin('adapter stopped');
945
+ if (this.permitJoinController) {
946
+ this.permitJoinController.allTimerClear();
947
+ }
843
948
 
844
949
  this.setState('info.connection', false, true);
845
950
 
@@ -855,6 +960,22 @@ class Zigbee2mqtt extends core.Adapter {
855
960
  }
856
961
  }
857
962
 
963
+ /**
964
+ * Prüft exakt, ob die State-ID ein info-State dieses Adapters ist.
965
+ *
966
+ * Bewusst kein loses `endsWith('info.<name>')`: seit der Wildcard-Subscription
967
+ * (siehe StatesController.subscribeWritableStates) erreichen uns alle
968
+ * State-Changes des eigenen Namespace – ein Geräte-State, der zufällig auf
969
+ * "info.<name>" endet, darf nicht als Adapter-Kommando gelten.
970
+ *
971
+ * @param {string} id Vollständige State-ID
972
+ * @param {string} name Name des info-States, z.B. "logfilter"
973
+ * @returns {boolean} true wenn die ID exakt auf diesen info-State zeigt
974
+ */
975
+ isOwnInfoState(id, name) {
976
+ return id === `${this.namespace}.info.${name}`;
977
+ }
978
+
858
979
  /**
859
980
  * Reagiert auf Änderungen von ioBroker-States.
860
981
  * Wandelt den State-Change in eine Zigbee2MQTT-Nachricht um und sendet sie.
@@ -864,12 +985,12 @@ class Zigbee2mqtt extends core.Adapter {
864
985
  */
865
986
  async onStateChange(id, state) {
866
987
  if (state && state.ack === false) {
867
- if (id.endsWith('info.debugmessages')) {
988
+ if (this.isOwnInfoState(id, 'debugmessages')) {
868
989
  this.logCustomizations.debugDevices = state.val != null ? String(state.val) : '';
869
990
  await this.setState(id, state.val, true).catch(e => this.log.error(`[stateChange] Fehler beim Setzen von ${id}: ${e.message}`));
870
991
  return;
871
992
  }
872
- if (id.endsWith('info.logfilter')) {
993
+ if (this.isOwnInfoState(id, 'logfilter')) {
873
994
  this.logCustomizations.logfilter = state.val != null
874
995
  ? String(state.val).split(';').filter((x) => x)
875
996
  : [];
@@ -887,13 +1008,26 @@ class Zigbee2mqtt extends core.Adapter {
887
1008
  return;
888
1009
  }
889
1010
 
1011
+ // Ohne Zigbee2MQTT online käme keine Antwort: sofort ablehnen statt beim unbestätigten Wunsch zu bleiben
1012
+ if (
1013
+ message.topic === 'bridge/request/permit_join' &&
1014
+ this.permitJoinController &&
1015
+ this.permitJoinController.bridgeOnline !== true
1016
+ ) {
1017
+ this.log.warn(`Cannot send permit_join, Zigbee2MQTT is offline. (${id})`);
1018
+ await this.reportSendFailure(message, 'Zigbee2MQTT is offline');
1019
+ return;
1020
+ }
1021
+
890
1022
  if (['exmqtt', 'intmqtt'].includes(this.config.connectionType)) {
891
1023
  if (!this.mqttClient || !this.mqttClient.connected) {
892
1024
  this.log.warn(`Cannot publish state, MQTT client not connected. (${id})`);
1025
+ await this.reportSendFailure(message, 'no connection to Zigbee2MQTT');
893
1026
  return;
894
1027
  }
895
1028
  if (!this.config.baseTopic) {
896
1029
  this.log.error('baseTopic is not configured – cannot publish state!');
1030
+ await this.reportSendFailure(message, 'baseTopic is not configured');
897
1031
  return;
898
1032
  }
899
1033
  try {
@@ -903,18 +1037,24 @@ class Zigbee2mqtt extends core.Adapter {
903
1037
  (err) => {
904
1038
  if (err) {
905
1039
  this.log.error(`MQTT publish error for ${id}: ${err && err.message ? err.message : String(err)}`);
1040
+ this.reportSendFailure(message, 'MQTT publish error');
906
1041
  }
907
1042
  }
908
1043
  );
909
1044
  } catch (e) {
910
1045
  this.log.error(`MQTT publish exception for ${id}: ${e}`);
1046
+ await this.reportSendFailure(message, 'MQTT publish error');
911
1047
  }
912
1048
  } else if (this.config.connectionType === 'ws') {
913
1049
  if (!this.websocketController) {
914
1050
  this.log.warn(`Cannot send state, WebSocket not initialized. (${id})`);
1051
+ await this.reportSendFailure(message, 'no connection to Zigbee2MQTT');
915
1052
  return;
916
1053
  }
917
- this.websocketController.send(JSON.stringify({ topic: message.topic, payload: message.payload }));
1054
+ const sent = this.websocketController.send(JSON.stringify({ topic: message.topic, payload: message.payload }));
1055
+ if (!sent) {
1056
+ await this.reportSendFailure(message, 'no connection to Zigbee2MQTT');
1057
+ }
918
1058
  }
919
1059
  }
920
1060
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "iobroker.zigbee2mqtt",
3
- "version": "3.2.10",
3
+ "version": "3.2.12",
4
4
  "description": "Zigbee2MQTT adapter for ioBroker",
5
5
  "author": {
6
6
  "name": "Dennis Rathjen and Arthur Rupp",
@@ -28,11 +28,11 @@
28
28
  "@iobroker/dm-utils": "^3.2.1",
29
29
  "aedes": "^0.51.3",
30
30
  "aedes-persistence": "^11.0.0",
31
- "axios": "^1.20.0",
32
- "mqtt": "^5.16.0",
33
- "node-schedule": "^2.1.1",
31
+ "axios": "^1.21.1",
32
+ "mqtt": "^5.16.1",
33
+ "node-schedule": "^2.1.2",
34
34
  "sharp": "^0.35.5",
35
- "ws": "^8.22.0"
35
+ "ws": "^8.22.2"
36
36
  },
37
37
  "devDependencies": {
38
38
  "@alcalzone/release-script": "^5.2.1",
@@ -41,7 +41,7 @@
41
41
  "@alcalzone/release-script-plugin-manual-review": "^5.2.0",
42
42
  "@iobroker/adapter-dev": "^1.5.0",
43
43
  "@iobroker/eslint-config": "^2.3.4",
44
- "@iobroker/testing": "^6.3.0",
44
+ "@iobroker/testing": "^6.3.2",
45
45
  "@tsconfig/node22": "^22.0.6",
46
46
  "@types/node": "^25.9.9",
47
47
  "@types/node-schedule": "^2.1.8",