Compare commits

..
132 Commits
Author SHA1 Message Date
Koen Kanters 23805c25af 1.12.1 2020-04-08 17:54:22 +02:00
Koen Kanters 0cffae8118 Undev 2020-04-08 17:54:17 +02:00
Koen Kanters 864e8b26d5 Update converters. 2020-04-06 21:39:06 +02:00
Koen Kanters ad48ea2af6 Update herdsman. 2020-04-06 19:14:55 +02:00
ghostcodeandKoen Kanters 418b3d1e5d Action and click trigger for multiple endpoints and 511.344 / ZG2819S support (#3289)
* Home Assistant support for ZG2819S/511.344

* Added 'homeassistant_legacy_triggers' support for devices with multiple endpoints

* Changed code style to pass lint test

* Reverted fix for the action and click trigger to send an empty message for devices with multiple endpoints

* Home Assistant support for the updated ZG2819S converter

* Update homeassistant.js

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-04-05 21:53:18 +02:00
Koen Kanters 4970d1a927 Update herdsman. 2020-04-05 21:32:24 +02:00
Koen Kanters e71485cd50 Refactor 2020-04-05 20:36:09 +02:00
Koen Kanters 552eec7baa Isolate legacy MQTT log. #3281 2020-04-05 18:36:08 +02:00
Koen Kanters 9df1589361 Move stateChange event to event bus. 2020-04-05 15:48:23 +02:00
Koen Kanters 1e6f99d88f Don't cache properties which start with action_ 2020-04-05 15:41:48 +02:00
Koen Kanters 4fa9aaa0b2 Refactor 2020-04-05 15:41:24 +02:00
Koen Kanters 3ef7555ca2 Refactor 2020-04-05 00:05:05 +02:00
Koen Kanters e0076367d3 Start on legacy api isolation. https://github.com/Koenkk/zigbee2mqtt/issues/3281 2020-04-04 22:47:23 +02:00
Koen Kanters 903cec5760 Allow to disable log rotation. #3280 2020-04-04 19:46:43 +02:00
Koen Kanters 1d9d63062a Add missing devices to configuration. #3263 2020-04-04 19:15:24 +02:00
Jorge Schrauwen 1e28c4285b entityPublish now passes in meta.mapped as an array for groups (#3283) 2020-04-04 18:59:14 +02:00
Koen Kanters 98cf258489 Update converters. 2020-04-03 21:38:43 +02:00
Koen Kanters b15e4d1ad9 Update converters. 2020-04-03 19:19:52 +02:00
Kiall Mac Innes 1abb5b6a48 Fix conflict between illuminance and illuminance_lux (#3275)
* Fix conflict between illuminance and illuminance_lux

On certain devices, e.g. GZCGQ01LM, 9290012607, 9290019758, TERNCY-PP01 etc, both
cfg.sensor_illuminance and cfg.sensor_illuminance_lux are applied. As both of these
had the same object_id, only one would show in Home Assistant. Oddly, a mix of both
would apply - e.g. I would get the illuminance value, with the illuminance_lux unit
of 'lx'.

* Add a test for duplicated type/object_id in HA discovery configs
2020-04-03 11:12:58 +02:00
Koen Kanters 496c5329a2 Update converters. 2020-04-02 18:15:10 +02:00
Koen Kanters 3e1db1787d ZM-CSW032-D doesn't support reporting. https://github.com/Koenkk/zigbee2mqtt/issues/3216 2020-04-02 18:11:49 +02:00
Daniel ZegarraandKoen Kanters 86c3ce3705 Added HA config for radiator valve Siterwell GS361 (#3259)
* Added HA config for radiator valve Siterwell GS361

* Updated payload and state keywords for mqtt msgs

* Update homeassistant.js

* Update homeassistant.js

* Update homeassistant.js

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-04-02 14:29:39 +02:00
Koen Kanters da01a504e7 Update herdsman 2020-04-01 22:36:14 +02:00
Koen Kanters 379847d6d0 Update herdsman and converters. 2020-04-01 21:52:35 +02:00
presslab-us 5952a2a12a Fix definition of Nyce NCZ-3011-HA (#3267) 2020-04-01 21:42:48 +02:00
Koen Kanters f95eb4527a Only setup supported color capabilities. https://github.com/Koenkk/zigbee2mqtt/issues/3260 2020-04-01 20:33:04 +02:00
Koen Kanters defe6a5ec1 Update herdsman. 2020-03-31 21:36:19 +02:00
Koen Kanters 5b34e14a62 Update converters. 2020-03-31 19:59:12 +02:00
presslab-usandKoen Kanters 87d6587779 Support Orvibo RL804QZB (#3252)
Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-03-31 19:01:24 +02:00
presslab-usandKoen Kanters 92b6510175 Support Leviton Omnistat2 thermostat (#3249)
* Support Leviton Omnistat2 thermostat

* Update homeassistant.js

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-03-31 18:53:51 +02:00
Koen Kanters d6fccbd83e Fix tests. 2020-03-31 18:18:15 +02:00
Koen Kanters eeb85cf096 Update herdsman and converters. 2020-03-30 21:56:34 +02:00
Koen Kanters 7131c05255 DeviceReport: don't crash on binds to non-existing entities. #3245 2020-03-30 19:50:35 +02:00
danieledwardgeorgehitchcock 1ca34536de Added device support for Hue Beyond suspension light (#3246) 2020-03-30 19:45:08 +02:00
presslab-us 7e45ab05cf Fix colortemp ability for Paulmann RGBW Light (#3239) 2020-03-30 19:02:25 +02:00
Koen Kanters 545eca6708 Update converters. 2020-03-29 21:36:59 +02:00
presslab-usandKoen Kanters 6b01418a00 Support Centralite thermostat 3157100 (#3234)
Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-03-29 21:22:48 +02:00
presslab-usandKoen Kanters 3bd1f4dc4a Fix power reporting of Centralite 4257050-RZHAC (#3236)
Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-03-29 21:14:48 +02:00
presslab-us 00f0381d62 Support Iris hose faucet water timer 27087-03 (#3230) 2020-03-29 20:28:54 +02:00
Koen Kanters 3c9639048e Remove battery_low for HS1CG-E. https://github.com/Koenkk/zigbee2mqtt/issues/3041 2020-03-29 20:19:13 +02:00
Koen Kanters 78c7024980 Update herdsman. 2020-03-29 19:40:33 +02:00
Koen Kanters fb4d86cef5 Allow to change non-setted options via device_options. #3215 2020-03-28 19:48:05 +01:00
Koen Kanters e49b733fae Cover position for ZM-CSW032-D. https://github.com/Koenkk/zigbee2mqtt/issues/3216 2020-03-28 19:30:27 +01:00
Koen Kanters 5092a12298 Change unit of Home Assistant sensor_energy to kWh. https://github.com/Koenkk/zigbee-herdsman-converters/issues/974 2020-03-28 19:26:02 +01:00
presslab-us 15ee48c318 Support Iris smart button 3460-L (#3214) 2020-03-28 19:12:49 +01:00
Koen Kanters ac7ac1a464 Update converters. 2020-03-27 20:44:10 +01:00
presslab-usandKoen Kanters d73bcf3520 Support Sylvania iQBR30 (#3205)
* Support Sylvania iQBR30

* Update homeassistant.js

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-03-27 17:45:34 +01:00
Koen Kanters a444a01fa7 Update converters. 2020-03-26 22:24:22 +01:00
presslab-usandKoen Kanters f7b2dff37e Support Centralite Night Light Repeater (#3203)
* Support Centralite Night Light Repeater

* Update homeassistant.js

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-03-26 22:15:22 +01:00
presslab-us 676e7e08c6 Support wallyHOME Multi-Sensor (#3202) 2020-03-26 22:09:59 +01:00
Koen Kanters 1c8ba3d28e Mock water_leak value for Home Assistant when it's not available. #3146 2020-03-26 22:01:05 +01:00
presslab-us 4ce9370cc0 Add humidity support for SmartThings (Centralite) 3310-S (#3197) 2020-03-26 21:28:27 +01:00
Koen Kanters a7e38b6bb0 Update zigbee-herdsman. https://github.com/Koenkk/zigbee2mqtt/issues/3111 2020-03-26 20:20:59 +01:00
Koen Kanters 4fe23842cf Don't allow non existing entities on availability_blacklist or availability_whitelist. #3191 2020-03-25 20:46:20 +01:00
Koen Kanters a307747d8c Fix typo. 2020-03-25 20:05:18 +01:00
Koen Kanters 5cd1af569e Fix crash when removing device from group which has no devices in settings. #3185 2020-03-23 22:24:35 +01:00
Nico87LBS dfc897af1a Add Hue Impress outdoor Pedestal (#3186) 2020-03-23 21:51:07 +01:00
Koen Kanters a3b285d1ac Don't allow MQTT wildcard (# or +) in friendly_name. #3175 2020-03-23 19:59:49 +01:00
Koen Kanters 06c792f493 Update herdsman and converters. 2020-03-23 19:42:06 +01:00
Koen Kanters d52d520da8 Update herdsman. 2020-03-22 20:46:39 +01:00
Nico87LBS 5461b3c3f8 Added Hue Econic Outdoor Pedestal (#3174) 2020-03-22 16:36:14 +01:00
Koen Kanters 78c17f0a61 Update converters. 2020-03-21 21:59:10 +01:00
Jorge Schrauwen e226cd229e #3159 Fix incorrect unbind message (#3172) 2020-03-21 21:33:00 +01:00
Addison Lynch 2f557bd397 Add 75541 (#3167) 2020-03-21 15:37:43 +01:00
Koen Kanters ed37570ef0 Update converters. 2020-03-20 19:46:57 +01:00
Koen Kanters 6cc2689593 Log error when there is nothing to bind. #3159 2020-03-20 19:00:00 +01:00
Koen Kanters 92d8eb2b6b Fix unsupported device warnings when device is still being interviewed. #3158 2020-03-20 18:04:28 +01:00
Koen Kanters a30abba973 Make sure that there is always an update_available value for Home Assistant. https://github.com/Koenkk/zigbee2mqtt/issues/3146 2020-03-20 17:50:28 +01:00
Koen Kanters ac8a84feb2 Update converters. 2020-03-19 23:04:39 +01:00
Koen Kanters e3fafcdfed Update herdsman. 2020-03-19 19:39:36 +01:00
Koen Kanters 6b9baf0114 Allow to specify adapter type. https://github.com/Koenkk/zigbee-herdsman/issues/72 2020-03-19 19:34:11 +01:00
Koen Kanters 9b80b6785d Update converters. 2020-03-18 22:50:45 +01:00
Koen Kanters 73dab78c37 Promote to dev 2020-03-18 19:03:33 +01:00
Koen Kanters 840b9d966c 1.12.0 2020-03-18 19:01:45 +01:00
Koen Kanters d514c0b3c1 Undev 2020-03-18 19:01:41 +01:00
Koen Kanters dc856ff8bf Update herdsman and converters. 2020-03-17 18:31:50 +01:00
Koen Kanters 11ee61fb1c Update converters. 2020-03-16 20:20:00 +01:00
r1cht3r 43a2aa27cd changing 3323-G cfg.binary_sensor_contact to cfg.binary_sensor_occupancy (#3137) 2020-03-16 20:07:53 +01:00
Filip CornelissenandKoen Kanters 43c7ce8e8a add support for ROB_200-007-0 (#3125)
* add support for ROB_200-007-0

* Fix automatically discovery for Home assistant for ROB_200-007-0

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-03-15 22:42:39 +01:00
Koen Kanters 27b3fd2f03 Update converters. 2020-03-15 22:26:03 +01:00
Koen Kanters 66b68da318 Add vendor and description to 'zigbee2mqtt/bridge/config/devices'. #3133 2020-03-15 17:04:10 +01:00
Koen Kanters db57829068 Update converters. 2020-03-15 16:58:48 +01:00
Koen Kanters 15bef07328 Fix LifeControl_Door_Sensor Home Assistant discovery. #3108 2020-03-15 15:25:28 +01:00
Koen Kanters 4d3bbce687 Implement lightWithPostfix Home Assistant configuration. #3003 2020-03-15 09:38:39 +01:00
Koen Kanters cb87b31cdd Update herdsman. 2020-03-14 15:08:00 +01:00
Koen Kanters cee146b062 Update converters. 2020-03-13 19:24:20 +01:00
Kryzek cde5c9696d Update homeassistant.js (#3121)
Related to https://github.com/Koenkk/zigbee-herdsman-converters/pull/1063
2020-03-13 19:20:38 +01:00
Koen Kanters 882c725b13 Update converters. 2020-03-13 18:39:40 +01:00
Dustin SallingsandKoen Kanters 97a4b6b539 Add support for expiring retained messages. (#3082)
* Add support for expiring retained messages.

For most of my environmental monitoring use cases, I want the readings
retained so I can pick them up from clients at any time, but if the
sensor (or zigbee2mqtt) fails, I want the readings to go away so I can
tell the difference between a stale reading and a missing reading.

This is easily accomplished in MQTTv5 using the "message expiry
interval" property.  To add that to zigbee2mqtt, I added a 'version'
option to the mqtt section so I can specify to connect with version 5
and added a 'retention' property to devices allowing me to specify how
long items should be retained.

e.g.

    mqtt:
      base_topic: site/zigbee2mqtt
      server: 'mqtt://myserver'
      user: zigbee
      version: 5
    serial:
      port: /dev/ttyACM0
    devices:
      '0x00358d00022308da':
        friendly_name: someroom
        retain: true
        retention: 900

* Also get from deviceOptions

* Update settings.js

* Update controller.js

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-03-12 20:25:37 +01:00
Koen Kanters f1a685bea2 Reduce MQTT subscriptions in deviceBind. https://github.com/Koenkk/zigbee2mqtt/issues/3102 2020-03-11 21:30:01 +01:00
Koen Kanters a17d96c14a Revert "Reduce MQTT subscriptions. #3102"
This reverts commit 82080e3d22.
2020-03-11 21:24:59 +01:00
Koen Kanters 9b592d4546 Refuse to start when 'device_options: null' is set. #3107 2020-03-11 20:18:27 +01:00
Koen Kanters 444850f1bc Update converters. 2020-03-11 20:11:47 +01:00
Koen Kanters 82080e3d22 Reduce MQTT subscriptions. #3102 2020-03-11 19:02:24 +01:00
b59d761ca6 publish announces to log topic (#3101)
* publish announces to log topic

* publish announces to log topic #test fix

* Update controller.js

* Update controller.test.js

* Update deviceAvailability.test.js

Co-authored-by: Andrey Sergeew <avsergeev@neoflex.ru>
Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-03-11 18:21:06 +01:00
Koen Kanters 785079a712 Update herdsman. 2020-03-10 21:30:12 +01:00
Koen Kanters 59281fe1c2 Update herdsman. https://github.com/Koenkk/zigbee2mqtt/issues/2693 2020-03-10 20:29:46 +01:00
Koen Kanters ab85577132 Wait 30 seconds before publishing device states. https://github.com/Koenkk/zigbee2mqtt/issues/105 2020-03-10 19:32:44 +01:00
Koen Kanters da8b8aa373 Fix command_on_template for lightWithPostfix. https://github.com/Koenkk/zigbee2mqtt/issues/3003#issuecomment-596868209 2020-03-10 19:28:19 +01:00
Koen Kanters 052ccfa242 Update converters. 2020-03-10 18:40:16 +01:00
Koen Kanters 8e9729cbbd Update herdsman and converters. 2020-03-09 20:01:51 +01:00
netadmindaveandKoen Kanters 3f7d383ead added config for Third Reality Switch 3RSS007Z (#3089)
* added config for Third Reality Switch 3RSS007Z

* Update homeassistant.js

* Update homeassistant.js

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-03-09 18:59:48 +01:00
Koen Kanters b92e3c31d1 Update converters. 2020-03-09 18:09:15 +01:00
Koen Kanters 4d54e5038b Refuse to start when friendly_name ends with /DIGIT. #2645 2020-03-07 23:06:22 +01:00
Koen Kanters 407d329d4f Update herdsman and converters. 2020-03-06 23:34:36 +01:00
Koen Kanters 34b3e66fa5 Add l5 till l8 to postfixes. https://github.com/Koenkk/zigbee-herdsman-converters/pull/1041 2020-03-06 23:18:50 +01:00
Kiall Mac Innes 67b4bcf815 Update HA Discovery Info on Rename (#3040)
* Update HA Discovery Info on Rename

Update HA discovery info when a device is renamed. Adds a new deviceRenamed
event to the event bus, allowing the HA extension to react to the rename

Fixes #2440

* Handle Groups correctly wrt HA discovery data refresh

* Cleanup group handling

* Cleanup group handling
2020-03-04 12:55:08 +01:00
Koen Kanters 3b60a907c8 Fix error on OTA update message without mapped device. 2020-03-03 21:19:00 +01:00
Koen Kanters 2d10c15a94 Update herdsman and converters. 2020-03-03 20:33:10 +01:00
Jorge Schrauwen b17b9c76ef #3009 filtered_attributes should also work in device_options (#3057) 2020-03-03 18:30:54 +01:00
Magnus PernemarkandKoen Kanters 2454136b9b Added MQTT logging to TouchLink Reset process (#3053)
* MQTT logging for TouchLink reset process

* Changed status to be in meta

* Update bridgeConfig.js

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-03-03 18:22:28 +01:00
Koen Kanters dc8b6c5294 Update converters. 2020-03-02 21:11:54 +01:00
Jorge Schrauwen 658cc21b4d #3009 allow filtering of mqtt topics and payloads (#3037)
* Allow filtering of attributes in mqtt json payload or published attributes

* Add test for mqtt_attribute_filter

Just doing attribute_and_json should be fine as the code changes are run before this. Doing this tests lets us varify both json or seperate topic get properly filtered.

* Add test for mqtt_attribute_filter on group

* Rename mqtt_attribute_filter to filtered_attributes
2020-03-02 20:08:51 +01:00
Koen Kanters 68750fade0 Fix tests on node 12. https://github.com/Koenkk/zigbee2mqtt/issues/3031 2020-03-02 19:11:43 +01:00
Koen Kanters ed34422640 Merge branch 'master' into dev 2020-03-02 19:07:49 +01:00
Koen Kanters e140cf5de3 Add branch switcher. 2020-03-02 19:07:38 +01:00
Koen Kanters 43b744987b Add AV2010/32 Home Assistant discovery. #3038 2020-03-01 16:03:08 +01:00
Koen Kanters 9f1b8cf214 Allow to disable homeassistant legacy triggers. #3033 2020-03-01 15:55:20 +01:00
Koen Kanters ed75c85b69 Implement Home Assistant MQTT device trigger. #3033 2020-02-29 18:07:15 +01:00
Koen Kanters 2eb6f075dc Update converters. https://github.com/Koenkk/zigbee2mqtt/issues/3024 2020-02-29 13:53:35 +01:00
Koen Kanters a16e3542c0 Update herdsman. #3019 2020-02-29 12:43:53 +01:00
Koen Kanters dd3678f84b TEMP: disable OTA response. https://github.com/Koenkk/zigbee2mqtt/issues/3019 2020-02-28 23:52:30 +01:00
Koen Kanters a40ad0c52f Respond with ABORT when device checks for OTA. https://github.com/Koenkk/zigbee2mqtt/issues/3019 2020-02-28 23:42:59 +01:00
Koen Kanters f6aba5f64a Respond with image not available when OTA is requested but we don't support it. #3019 2020-02-28 23:30:33 +01:00
Koen Kanters 8f8180f84d Update converters and herdsman. 2020-02-28 23:27:12 +01:00
Cedric Girard 4803be2df9 Add necessary changes for NPM publishing (#3021) 2020-02-28 21:59:01 +01:00
Koen Kanters 05766fa39a Update dependencies. https://github.com/Koenkk/zigbee2mqtt/issues/3007 2020-02-28 20:56:32 +01:00
Koen Kanters 342d4c17b9 Fix debounce, debounce_ignore, retain and qos in device_options not honored. #3004 2020-02-27 21:06:27 +01:00
Christian Scheffler 69c477da7d added mqtt log events group_added and group_removed (#3016) 2020-02-27 21:03:56 +01:00
Koen Kanters 63be685201 Fix OTA update start on check with / as base_topic prefix. #3010 2020-02-27 20:33:04 +01:00
Koen Kanters 5c0bb33c1b Discover Home Assistant temperature sensor for QBKG12LM. https://github.com/Koenkk/zigbee-herdsman-converters/issues/1020 2020-02-26 22:02:04 +01:00
Koen Kanters 0036176098 Promote to dev. 2020-02-26 18:28:22 +01:00
40 changed files with 3526 additions and 2027 deletions
+1
View File
@@ -0,0 +1 @@
preferredBranch: dev
+25
View File
@@ -0,0 +1,25 @@
#tests
test
coverage
#build tools
.travis.yml
.jenkins.yml
.codeclimate.yml
.github
azure-pipelines.yaml
#linters
.jscsrc
.jshintrc
.eslintrc*
.dockerignore
.eslintignore
#editor settings
.vscode
#src
docs
docker
images
+3
View File
@@ -29,6 +29,9 @@
<a href="https://www.codacy.com/manual/Koenkk/zigbee2mqtt?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=Koenkk/zigbee2mqtt&amp;utm_campaign=Badge_Grade">
<img src="https://api.codacy.com/project/badge/Grade/24f1e0fe39f04daa810e8a1416693d3f">
</a>
<a href="https://www.npmjs.com/package/zigbee2mqtt">
<img src="https://img.shields.io/npm/v/zigbee2mqtt">
</a>
</div>
<h1>Zigbee2mqtt 🌉 🐝</h1>
<p>
+9 -1
View File
@@ -14,7 +14,7 @@ steps:
# Prepare
- task: NodeTool@0
inputs:
versionSpec: '10.x'
versionSpec: '12.x'
displayName: 'Install Node.js'
- bash: npm ci
displayName: 'Install dependencies'
@@ -25,6 +25,14 @@ steps:
- bash: npm run eslint
displayName: 'Lint'
# NPM
- task: Npm@1
inputs:
command: publish
publishEndpoint: npm
displayName: 'Publish to npm'
condition: and(succeeded(), startsWith(variables['Build.SourceBranch'], 'refs/tags/'), ne(variables['Build.Reason'], 'PullRequest'))
# Docker
- task: DockerInstaller@0
displayName: Docker install
+73 -66
View File
@@ -15,7 +15,7 @@ const ExtensionSoftReset = require('./extension/softReset');
const ExtensionHomeAssistant = require('./extension/homeassistant');
const ExtensionDeviceConfigure = require('./extension/deviceConfigure');
const ExtensionDeviceGroupMembership = require('./extension/deviceGroupMembership');
const ExtensionBridgeConfig = require('./extension/bridgeConfig');
const ExtensionBridgeLegacy = require('./extension/bridgeLegacy');
const ExtensionGroups = require('./extension/groups');
const ExtensionDeviceAvailability = require('./extension/deviceAvailability');
const ExtensionDeviceBind = require('./extension/deviceBind');
@@ -28,50 +28,45 @@ class Controller {
this.zigbee = new Zigbee();
this.mqtt = new MQTT();
this.eventBus = new EventBus();
this.state = new State();
this.state = new State(this.eventBus);
this.publishEntityState = this.publishEntityState.bind(this);
this.onZigbeeAdapterDisconnected = this.onZigbeeAdapterDisconnected.bind(this);
// Initialize extensions.
const args = [this.zigbee, this.mqtt, this.state, this.publishEntityState, this.eventBus];
this.extensions = [
new ExtensionEntityPublish(this.zigbee, this.mqtt, this.state, this.publishEntityState, this.eventBus),
new ExtensionDeviceReceive(this.zigbee, this.mqtt, this.state, this.publishEntityState, this.eventBus),
new ExtensionDeviceGroupMembership(
this.zigbee, this.mqtt, this.state, this.publishEntityState, this.eventBus,
),
new ExtensionDeviceConfigure(this.zigbee, this.mqtt, this.state, this.publishEntityState, this.eventBus),
new ExtensionNetworkMap(this.zigbee, this.mqtt, this.state, this.publishEntityState, this.eventBus),
new ExtensionBridgeConfig(this.zigbee, this.mqtt, this.state, this.publishEntityState, this.eventBus),
new ExtensionGroups(this.zigbee, this.mqtt, this.state, this.publishEntityState, this.eventBus),
new ExtensionDeviceBind(this.zigbee, this.mqtt, this.state, this.publishEntityState, this.eventBus),
new ExtensionDeviceEvent(this.zigbee, this.mqtt, this.state, this.publishEntityState, this.eventBus),
new ExtensionOTAUpdate(this.zigbee, this.mqtt, this.state, this.publishEntityState, this.eventBus),
new ExtensionEntityPublish(...args),
new ExtensionDeviceReceive(...args),
new ExtensionDeviceGroupMembership(...args),
new ExtensionDeviceConfigure(...args),
new ExtensionNetworkMap(...args),
new ExtensionGroups(...args),
new ExtensionDeviceBind(...args),
new ExtensionDeviceEvent(...args),
new ExtensionOTAUpdate(...args),
];
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
this.extensions.push(new ExtensionBridgeLegacy(...args));
}
if (settings.get().advanced.report) {
this.extensions.push(new ExtensionDeviceReport(
this.zigbee, this.mqtt, this.state, this.publishEntityState, this.eventBus,
));
this.extensions.push(new ExtensionDeviceReport(...args));
}
if (settings.get().homeassistant) {
this.extensions.push(new ExtensionHomeAssistant(
this.zigbee, this.mqtt, this.state, this.publishEntityState, this.eventBus,
));
this.extensions.push(new ExtensionHomeAssistant(...args));
}
/* istanbul ignore next */
if (settings.get().advanced.soft_reset_timeout !== 0) {
this.extensions.push(new ExtensionSoftReset(
this.zigbee, this.mqtt, this.state, this.publishEntityState, this.eventBus,
));
this.extensions.push(new ExtensionSoftReset(...args));
}
if (settings.get().advanced.availability_timeout) {
this.extensions.push(new ExtensionDeviceAvailability(
this.zigbee, this.mqtt, this.state, this.publishEntityState, this.eventBus,
));
this.extensions.push(new ExtensionDeviceAvailability(...args));
}
}
@@ -114,8 +109,8 @@ class Controller {
logger.info(
(entity.settings ? entity.settings.friendlyName : entity.device.ieeeAddr) +
` (${entity.device.ieeeAddr}): ` +
(entity.mapped ?
`${entity.mapped.model} - ${entity.mapped.vendor} ${entity.mapped.description} ` :
(entity.definition ?
`${entity.definition.model} - ${entity.definition.vendor} ${entity.definition.description} ` :
'Not supported ') +
`(${entity.device.type})`,
);
@@ -143,6 +138,13 @@ class Controller {
}
}
// Add devices which are in database but not in configuration to configuration
for (const device of this.zigbee.getClients()) {
if (!settings.getDevice(device.ieeeAddr)) {
settings.addDevice(device.ieeeAddr);
}
}
// Call extensions
await this.callExtensionMethod('onMQTTConnected', []);
}
@@ -170,13 +172,13 @@ class Controller {
}
async onZigbeeEvent(type, data) {
const entity = this.zigbee.resolveEntity(data.device || data.ieeeAddr);
if (data.device && !entity.settings) {
const resolvedEntity = this.zigbee.resolveEntity(data.device || data.ieeeAddr);
if (data.device && !resolvedEntity.settings) {
// Only deviceLeave doesn't have a device (not interesting to add to settings)
entity.settings = settings.addDevice(data.device.ieeeAddr);
resolvedEntity.settings = settings.addDevice(data.device.ieeeAddr);
}
const name = entity && entity.settings ? entity.settings.friendlyName : null;
const name = resolvedEntity && resolvedEntity.settings ? resolvedEntity.settings.friendlyName : null;
if (type === 'message') {
logger.debug(
@@ -186,34 +188,25 @@ class Controller {
);
} else if (type === 'deviceJoined') {
logger.info(`Device '${name}' joined`);
this.mqtt.log('device_connected', {friendly_name: name});
} else if (type === 'deviceInterview') {
if (data.status === 'successful') {
logger.info(`Successfully interviewed '${name}', device has successfully been paired`);
if (entity.mapped) {
const {vendor, description, model} = entity.mapped;
logger.info(
`Device '${name}' is supported, identified as: ${vendor} ${description} (${model})`,
);
const log = {friendly_name: name, model, vendor, description, supported: true};
this.mqtt.log('pairing', 'interview_successful', log);
if (resolvedEntity.definition) {
const {vendor, description, model} = resolvedEntity.definition;
logger.info(`Device '${name}' is supported, identified as: ${vendor} ${description} (${model})`);
} else {
logger.warn(
`Device '${name}' with Zigbee model '${data.device.modelID}' is NOT supported, ` +
`please follow https://www.zigbee2mqtt.io/how_tos/how_to_support_new_devices.html`,
);
this.mqtt.log('pairing', 'interview_successful', {friendly_name: name, supported: false});
}
} else if (data.status === 'failed') {
logger.error(`Failed to interview '${name}', device has not successfully been paired`);
this.mqtt.log('pairing', 'interview_failed', {friendly_name: name});
} else {
/* istanbul ignore else */
if (data.status === 'started') {
logger.info(`Starting interview of '${name}'`);
this.mqtt.log('pairing', 'interview_started', {friendly_name: name});
}
}
} else if (type === 'deviceAnnounce') {
@@ -222,15 +215,11 @@ class Controller {
/* istanbul ignore else */
if (type === 'deviceLeave') {
logger.warn(`Device '${name || data.ieeeAddr}' left the network`);
this.mqtt.log('device_removed', 'left_network', {friendly_name: name || data.ieeeAddr});
}
}
// Call extensions
this.callExtensionMethod(
'onZigbeeEvent',
[type, data, entity ? entity.mapped : null, entity ? entity.settings : null],
);
this.callExtensionMethod('onZigbeeEvent', [type, data, resolvedEntity]);
}
onMQTTMessage(payload) {
@@ -242,58 +231,76 @@ class Controller {
}
async publishEntityState(IDorName, payload, stateChangeReason=null) {
const entity = this.zigbee.resolveEntity(IDorName);
if (!entity || !entity.settings) {
const resolvedEntity = this.zigbee.resolveEntity(IDorName);
if (!resolvedEntity || !resolvedEntity.settings) {
logger.error(`'${IDorName}' does not exist, skipping publish`);
return;
}
if (entity.type === 'device' && settings.get().advanced.last_seen !== 'disable' && entity.device.lastSeen) {
payload.last_seen = utils.formatDate(entity.device.lastSeen, settings.get().advanced.last_seen);
const isDevice = resolvedEntity.type === 'device';
if (isDevice && settings.get().advanced.last_seen !== 'disable' && resolvedEntity.device.lastSeen) {
payload.last_seen = utils.formatDate(resolvedEntity.device.lastSeen, settings.get().advanced.last_seen);
}
let messagePayload = {...payload};
const currentState = this.state.exists(entity.settings.ID) ? this.state.get(entity.settings.ID) : {};
const currentState = this.state.exists(resolvedEntity.settings.ID) ?
this.state.get(resolvedEntity.settings.ID) : {};
const newState = objectAssignDeep.noMutate(currentState, payload);
// Update state cache with new state.
this.state.set(entity.settings.ID, newState, stateChangeReason);
this.state.set(resolvedEntity.settings.ID, newState, stateChangeReason);
if (settings.get().advanced.cache_state) {
// Add cached state to payload
messagePayload = newState;
}
const deviceOptions = settings.get().device_options;
const options = {
retain: entity.settings.hasOwnProperty('retain') ? entity.settings.retain : false,
qos: entity.settings.hasOwnProperty('qos') ? entity.settings.qos : 0,
retain: utils.getObjectsProperty([resolvedEntity.settings, deviceOptions], 'retain', false),
qos: utils.getObjectsProperty([resolvedEntity.settings, deviceOptions], 'qos', 0),
};
if (entity.type === 'device' && settings.get().mqtt.include_device_information) {
const device = this.zigbee.getDeviceByIeeeAddr(entity.device.ieeeAddr);
const retention = utils.getObjectsProperty([resolvedEntity.settings, deviceOptions], 'retention', false);
if (retention !== false) {
options.properties = {messageExpiryInterval: retention};
}
if (isDevice && settings.get().mqtt.include_device_information) {
const attributes = [
'ieeeAddr', 'networkAddress', 'type', 'manufacturerID', 'manufacturerName', 'powerSource',
'applicationVersion', 'stackVersion', 'zclVersion', 'hardwareVersion', 'dateCode', 'softwareBuildID',
];
messagePayload.device = {
friendlyName: entity.name,
model: entity.mapped ? entity.mapped.model : 'unknown',
friendlyName: resolvedEntity.name,
model: resolvedEntity.definition ? resolvedEntity.definition.model : 'unknown',
};
attributes.forEach((a) => messagePayload.device[a] = device[a]);
attributes.forEach((a) => messagePayload.device[a] = resolvedEntity.device[a]);
}
// filter mqtt message attributes
if (deviceOptions.filtered_attributes) {
deviceOptions.filtered_attributes.forEach((a) => delete messagePayload[a]);
}
if (resolvedEntity.settings.filtered_attributes) {
resolvedEntity.settings.filtered_attributes.forEach((a) => delete messagePayload[a]);
}
this.eventBus.emit('publishEntityState', {payload: messagePayload, entity: resolvedEntity});
if (Object.entries(messagePayload).length) {
if (settings.get().experimental.output === 'attribute_and_json') {
await this.mqtt.publish(entity.name, JSON.stringify(messagePayload), options);
await this.iteratePayloadAttributeOutput(`${entity.name}/`, messagePayload, options);
await this.mqtt.publish(resolvedEntity.name, JSON.stringify(messagePayload), options);
await this.iteratePayloadAttributeOutput(`${resolvedEntity.name}/`, messagePayload, options);
} else if (settings.get().experimental.output === 'json') {
await this.mqtt.publish(entity.name, JSON.stringify(messagePayload), options);
await this.mqtt.publish(resolvedEntity.name, JSON.stringify(messagePayload), options);
} else {
/* istanbul ignore else */
if (settings.get().experimental.output === 'attribute') {
await this.iteratePayloadAttributeOutput(`${entity.name}/`, messagePayload, options);
await this.iteratePayloadAttributeOutput(`${resolvedEntity.name}/`, messagePayload, options);
}
}
}
+4
View File
@@ -3,6 +3,10 @@ const assert = require('assert');
const allowedEvents = [
'deviceRemoved', // Device has been removed
'deviceRenamed', // Device has been renamed
'groupRenamed', // Group has been renamed
'publishEntityState', // Entity state will be published
'stateChange', // Entity changes its state
];
class EventBus extends events.EventEmitter {
+2 -2
View File
@@ -30,10 +30,10 @@ class BaseExtension {
* Is called when a Zigbee message from a device is received.
* @param {string} type Type of the message
* @param {Object} data Data of the message
* @param {Object?} mappedDevice The mapped device
* @param {Object?} resolvedEntity Resolved entity returned from this.zigbee.resolveEntity()
* @param {Object?} settingsDevice Device settings
*/
// onZigbeeEvent(type, data, mappedDevice, settingsDevice) {}
// onZigbeeEvent(type, data, resolvedEntity) {}
/**
* Is called when a MQTT message is received
@@ -9,7 +9,7 @@ const configRegex =
new RegExp(`${settings.get().mqtt.base_topic}/bridge/config/((?:\\w+/get)|(?:\\w+/factory_reset)|(?:\\w+))`);
const allowedLogLevels = ['error', 'warn', 'info', 'debug'];
class BridgeConfig extends BaseExtension {
class BridgeLegacy extends BaseExtension {
constructor(zigbee, mqtt, state, publishEntityState, eventBus) {
super(zigbee, mqtt, state, publishEntityState, eventBus);
@@ -63,7 +63,10 @@ class BridgeConfig extends BaseExtension {
assert(entity, `Entity '${message}' does not exist`);
settings.whitelistDevice(entity.ID);
logger.info(`Whitelisted '${entity.friendlyName}'`);
this.mqtt.log('device_whitelisted', {friendly_name: entity.friendlyName});
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: 'device_whitelisted', message: {friendly_name: entity.friendlyName}}),
);
} catch (error) {
logger.error(`Failed to whitelist '${message}' '${error}'`);
}
@@ -147,9 +150,11 @@ class BridgeConfig extends BaseExtension {
};
if (device.type !== 'Coordinator') {
const mappedDevice = zigbeeHerdsmanConverters.findByZigbeeModel(device.modelID);
const definition = zigbeeHerdsmanConverters.findByZigbeeModel(device.modelID);
const friendlyDevice = settings.getDevice(device.ieeeAddr);
payload.model = mappedDevice ? mappedDevice.model : device.modelID;
payload.model = definition ? definition.model : device.modelID;
payload.vendor = definition ? definition.vendor : '-';
payload.description = definition ? definition.description : '-';
payload.friendly_name = friendlyDevice ? friendlyDevice.friendly_name : device.ieeeAddr;
payload.manufacturerID = device.manufacturerID;
payload.manufacturerName = device.manufacturerName;
@@ -172,16 +177,18 @@ class BridgeConfig extends BaseExtension {
if (topic.split('/').pop() == 'get') {
this.mqtt.publish(`bridge/config/devices`, JSON.stringify(devices), {});
} else {
this.mqtt.log('devices', devices);
this.mqtt.publish('bridge/log', JSON.stringify({type: 'devices', message: devices}));
}
}
groups(topic, message) {
this.mqtt.log('groups', settings.getGroups().map((g) => {
const payload = settings.getGroups().map((g) => {
const group = {...g};
delete group.friendlyName;
return group;
}));
});
this.mqtt.publish('bridge/log', JSON.stringify({type: 'groups', message: payload}));
}
rename(topic, message) {
@@ -218,7 +225,14 @@ class BridgeConfig extends BaseExtension {
const isGroup = settings.getGroup(from) !== null;
settings.changeFriendlyName(from, to);
logger.info(`Successfully renamed - ${from} to ${to} `);
this.mqtt.log(`${isGroup ? 'group' : 'device'}_renamed`, {from, to});
const entity = this.zigbee.resolveEntity(to);
const eventData = isGroup ? {group: entity.group} : {device: entity.device};
this.eventBus.emit(`${isGroup ? 'group' : 'device'}Renamed`, eventData);
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `${isGroup ? 'group' : 'device'}_renamed`, message: {from, to}}),
);
} catch (error) {
logger.error(`Failed to rename - ${from} to ${to}`);
}
@@ -249,6 +263,7 @@ class BridgeConfig extends BaseExtension {
const group = settings.addGroup(name, id);
this.zigbee.createGroup(group.ID);
this.mqtt.publish('bridge/log', JSON.stringify({type: `group_added`, message: name}));
logger.info(`Added group '${name}'`);
}
@@ -258,6 +273,7 @@ class BridgeConfig extends BaseExtension {
assert(entity && entity.type === 'group', `Group '${message}' does not exist`);
settings.removeGroup(message);
entity.group.removeFromDatabase();
this.mqtt.publish('bridge/log', JSON.stringify({type: `group_removed`, message}));
logger.info(`Removed group '${name}'`);
}
@@ -284,7 +300,7 @@ class BridgeConfig extends BaseExtension {
if (!entity) {
logger.error(`Cannot ${lookup[action][2]}, device '${message}' does not exist`);
this.mqtt.log(`device_${lookup[action][0]}_failed`, message);
this.mqtt.publish('bridge/log', JSON.stringify({type: `device_${lookup[action][0]}_failed`, message}));
return;
}
@@ -299,7 +315,7 @@ class BridgeConfig extends BaseExtension {
this.state.remove(entity.settings.ID);
logger.info(`Successfully ${lookup[action][0]} ${entity.settings.friendlyName}`);
this.mqtt.log(`device_${lookup[action][0]}`, message);
this.mqtt.publish('bridge/log', JSON.stringify({type: `device_${lookup[action][0]}`, message}));
};
try {
@@ -316,7 +332,7 @@ class BridgeConfig extends BaseExtension {
// eslint-disable-next-line
logger.error(`See https://www.zigbee2mqtt.io/information/mqtt_topics_and_message_structure.html#zigbee2mqttbridgeconfigremove for more info`);
this.mqtt.log(`device_${lookup[action][0]}_failed`, message);
this.mqtt.publish('bridge/log', JSON.stringify({type: `device_${lookup[action][0]}_failed`, message}));
}
if (action === 'ban') {
@@ -361,22 +377,86 @@ class BridgeConfig extends BaseExtension {
await this.mqtt.publish(topic, JSON.stringify(payload), {retain: true, qos: 0});
}
onZigbeeEvent(type, data, mappedDevice, settingsDevice) {
onZigbeeEvent(type, data, resolvedEntity) {
if (type === 'deviceJoined' && resolvedEntity) {
this.lastJoinedDeviceName = resolvedEntity.name;
}
if (type === 'deviceJoined') {
this.lastJoinedDeviceName = settingsDevice.friendlyName;
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `device_connected`, message: {friendly_name: resolvedEntity.name}}),
);
} else if (type === 'deviceInterview') {
if (data.status === 'successful') {
if (resolvedEntity.definition) {
const {vendor, description, model} = resolvedEntity.definition;
const log = {friendly_name: resolvedEntity.name, model, vendor, description, supported: true};
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `pairing`, message: 'interview_successful', meta: log}),
);
} else {
const meta = {friendly_name: resolvedEntity.name, supported: false};
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `pairing`, message: 'interview_successful', meta}),
);
}
} else if (data.status === 'failed') {
const meta = {friendly_name: resolvedEntity.name};
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `pairing`, message: 'interview_failed', meta}),
);
} else {
/* istanbul ignore else */
if (data.status === 'started') {
const meta = {friendly_name: resolvedEntity.name};
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `pairing`, message: 'interview_started', meta}),
);
}
}
} else if (type === 'deviceAnnounce') {
const meta = {friendly_name: resolvedEntity.name};
this.mqtt.publish('bridge/log', JSON.stringify({type: `device_announced`, message: 'announce', meta}));
} else {
/* istanbul ignore else */
if (type === 'deviceLeave') {
const name = resolvedEntity ? resolvedEntity.name : data.ieeeAddr;
const meta = {friendly_name: name};
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `device_removed`, message: 'left_network', meta}),
);
}
}
}
async touchlinkFactoryReset() {
logger.info('Starting touchlink factory reset...');
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `touchlink`, message: 'reset_started', meta: {status: 'started'}}),
);
const result = await this.zigbee.touchlinkFactoryReset();
if (result) {
logger.info('Successfully factory reset device through Touchlink');
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `touchlink`, message: 'reset_success', meta: {status: 'success'}}),
);
} else {
logger.warn('Failed to factory reset device through Touchlink');
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `touchlink`, message: 'reset_failed', meta: {status: 'failed'}}),
);
}
}
}
module.exports = BridgeConfig;
module.exports = BridgeLegacy;
+5 -5
View File
@@ -44,7 +44,7 @@ class DeviceAvailability extends BaseExtension {
const ieeeAddr = device.ieeeAddr;
const deviceSettings = settings.getDevice(ieeeAddr);
const name = deviceSettings ? deviceSettings.friendly_name : null;
const name = deviceSettings.friendly_name;
// Whitelist is not empty and device is in it, enable availability
if (this.whitelist.length > 0) {
@@ -144,13 +144,13 @@ class DeviceAvailability extends BaseExtension {
async onReconnect(device) {
if (device && device.modelID) {
const mappedDevice = zigbeeHerdsmanConverters.findByZigbeeModel(device.modelID);
const definition = zigbeeHerdsmanConverters.findByZigbeeModel(device.modelID);
if (mappedDevice) {
if (definition) {
const used = [];
try {
for (const key of toZigbeeCandidates) {
const converter = mappedDevice.toZigbee.find((tz) => tz.key.includes(key));
const converter = definition.toZigbee.find((tz) => tz.key.includes(key));
if (converter && !used.includes(converter)) {
await converter.convertGet(device.endpoints[0], key, {});
used.push(converter);
@@ -180,7 +180,7 @@ class DeviceAvailability extends BaseExtension {
}
}
onZigbeeEvent(type, data, mappedDevice, settingsDevice) {
onZigbeeEvent(type, data, resolvedEntity) {
const device = data.device;
if (!device) {
return;
+35 -12
View File
@@ -11,10 +11,8 @@ const defaultBindGroup = {type: 'group_number', ID: 901};
class DeviceBind extends BaseExtension {
onMQTTConnected() {
for (let step = 1; step < 20; step++) {
this.mqtt.subscribe(`${settings.get().mqtt.base_topic}/bridge/bind${'/+'.repeat(step)}`);
this.mqtt.subscribe(`${settings.get().mqtt.base_topic}/bridge/unbind${'/+'.repeat(step)}`);
}
this.mqtt.subscribe(`${settings.get().mqtt.base_topic}/bridge/bind/#`);
this.mqtt.subscribe(`${settings.get().mqtt.base_topic}/bridge/unbind/#`);
}
async onMQTTMessage(topic, message) {
@@ -36,6 +34,7 @@ class DeviceBind extends BaseExtension {
const sourceName = source.settings.friendlyName;
const targetName = targetKey === 'default_bind_group' ? targetKey : target.settings.friendlyName;
let attemptedToBindSomething = false;
// Find which clusters are supported by both the source and target.
// Groups are assumed to support all clusters.
@@ -45,6 +44,7 @@ class DeviceBind extends BaseExtension {
if (source.endpoint.supportsOutputCluster(cluster) && targetValid) {
logger.debug(`${type}ing cluster '${cluster}' from '${sourceName}' to '${targetName}'`);
attemptedToBindSomething = true;
try {
let bindTarget = null;
if (target.type === 'group') bindTarget = target.group;
@@ -61,22 +61,45 @@ class DeviceBind extends BaseExtension {
`Successfully ${type === 'bind' ? 'bound' : 'unbound'} cluster '${cluster}' from ` +
`'${sourceName}' to '${targetName}'`,
);
this.mqtt.log(
`device_${type}`,
{from: sourceName, to: targetName, cluster},
);
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const message = {from: sourceName, to: targetName, cluster};
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `device_${type}`, message}),
);
}
} catch (error) {
logger.error(
`Failed to ${type} cluster '${cluster}' from '${sourceName}' to ` +
`'${targetName}' (${error})`,
);
this.mqtt.log(
`device_${type}_failed`,
{from: sourceName, to: targetName, cluster},
);
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const message = {from: sourceName, to: targetName, cluster};
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `device_${type}_failed`, message}),
);
}
}
}
}
if (!attemptedToBindSomething) {
logger.error(`Nothing to ${type} from '${sourceName}' to '${targetName}'`);
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const message = {from: sourceName, to: targetName};
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `device_${type}_failed`, message}),
);
}
}
}
}
+24 -27
View File
@@ -1,6 +1,5 @@
const settings = require('../util/settings');
const logger = require('../util/logger');
const zigbeeHerdsmanConverters = require('zigbee-herdsman-converters');
const BaseExtension = require('./baseExtension');
class DeviceConfigure extends BaseExtension {
@@ -12,18 +11,18 @@ class DeviceConfigure extends BaseExtension {
this.topic = `${settings.get().mqtt.base_topic}/bridge/configure`;
}
shouldConfigure(device, mappedDevice) {
if (!device || !mappedDevice || !mappedDevice.configure) {
shouldConfigure(resolvedEntity) {
if (!resolvedEntity || !resolvedEntity.definition || !resolvedEntity.definition.configure) {
return false;
}
if (device.meta &&
device.meta.hasOwnProperty('configured') &&
device.meta.configured === mappedDevice.meta.configureKey) {
if (resolvedEntity.device.meta &&
resolvedEntity.device.meta.hasOwnProperty('configured') &&
resolvedEntity.device.meta.configured === resolvedEntity.definition.meta.configureKey) {
return false;
}
if (device.interviewing === true) {
if (resolvedEntity.device.interviewing === true) {
return false;
}
@@ -39,34 +38,32 @@ class DeviceConfigure extends BaseExtension {
return;
}
const entity = this.zigbee.resolveEntity(message);
if (!entity || entity.type !== 'device') {
const resolvedEntity = this.zigbee.resolveEntity(message);
if (!resolvedEntity || resolvedEntity.type !== 'device') {
logger.error(`Device '${message}' does not exist`);
return;
}
const mappedDevice = zigbeeHerdsmanConverters.findByZigbeeModel(entity.device.modelID);
if (!mappedDevice.configure) {
logger.warn(`Skipping configure of '${entity.name}', device does not require this.`);
if (!resolvedEntity.definition || !resolvedEntity.definition.configure) {
logger.warn(`Skipping configure of '${resolvedEntity.name}', device does not require this.`);
return;
}
this.configure(entity.device, mappedDevice, entity.settings, true);
this.configure(resolvedEntity, true);
}
async onZigbeeStarted() {
this.coordinatorEndpoint = this.zigbee.getDevicesByType('Coordinator')[0].getEndpoint(1);
for (const device of this.zigbee.getClients()) {
const mappedDevice = zigbeeHerdsmanConverters.findByZigbeeModel(device.modelID);
const settingsDevice = settings.getDevice(device.ieeeAddr);
if (this.shouldConfigure(device, mappedDevice)) {
await this.configure(device, mappedDevice, settingsDevice);
const resolvedEntity = this.zigbee.resolveEntity(device);
if (this.shouldConfigure(resolvedEntity)) {
await this.configure(resolvedEntity);
}
}
}
onZigbeeEvent(type, data, mappedDevice, settingsDevice) {
onZigbeeEvent(type, data, resolvedEntity) {
const device = data.device;
if (type === 'deviceJoined' && device.meta.hasOwnProperty('configured')) {
@@ -74,12 +71,13 @@ class DeviceConfigure extends BaseExtension {
device.save();
}
if (this.shouldConfigure(device, mappedDevice)) {
this.configure(device, mappedDevice, settingsDevice);
if (this.shouldConfigure(resolvedEntity)) {
this.configure(resolvedEntity);
}
}
async configure(device, mappedDevice, settingsDevice, force=false) {
async configure(resolvedEntity, force=false) {
const device = resolvedEntity.device;
if (this.configuring.has(device.ieeeAddr) || (this.attempts[device.ieeeAddr] >= 3 && !force)) {
return false;
}
@@ -90,16 +88,15 @@ class DeviceConfigure extends BaseExtension {
this.attempts[device.ieeeAddr] = 0;
}
logger.info(`Configuring '${settingsDevice.friendlyName}'`);
logger.info(`Configuring '${resolvedEntity.name}'`);
try {
await mappedDevice.configure(device, this.coordinatorEndpoint);
logger.info(`Successfully configured '${settingsDevice.friendlyName}'`);
// eslint-disable-next-line
device.meta.configured = mappedDevice.meta.configureKey;
await resolvedEntity.definition.configure(device, this.coordinatorEndpoint);
logger.info(`Successfully configured '${resolvedEntity.name}'`);
device.meta.configured = resolvedEntity.definition.meta.configureKey;
device.save();
} catch (error) {
logger.error(
`Failed to configure '${settingsDevice.friendlyName}', ` +
`Failed to configure '${resolvedEntity.name}', ` +
`attempt ${this.attempts[device.ieeeAddr] + 1} (${error.stack})`,
);
this.attempts[device.ieeeAddr]++;
+8 -8
View File
@@ -8,9 +8,9 @@ class DeviceEvent extends BaseExtension {
}
}
onZigbeeEvent(type, data, mappedDevice, settingsDevice) {
if (data.device) {
this.callOnEvent(data.device, type, data, mappedDevice);
onZigbeeEvent(type, data, resolvedEntity) {
if (data.device && resolvedEntity.definition) {
this.callOnEvent(data.device, type, data, resolvedEntity.definition);
}
}
@@ -20,15 +20,15 @@ class DeviceEvent extends BaseExtension {
}
}
callOnEvent(device, type, data, mappedDevice) {
callOnEvent(device, type, data, definition) {
zigbeeHerdsmanConverters.onEvent(type, data, device);
if (!mappedDevice) {
mappedDevice = zigbeeHerdsmanConverters.findByZigbeeModel(device.modelID);
if (!definition) {
definition = zigbeeHerdsmanConverters.findByZigbeeModel(device.modelID);
}
if (mappedDevice && mappedDevice.onEvent) {
mappedDevice.onEvent(type, data, device);
if (definition && definition.onEvent) {
definition.onEvent(type, data, device);
}
}
}
+15 -17
View File
@@ -54,8 +54,8 @@ class DeviceReceive extends BaseExtension {
return result;
}
canHandleEvent(type, data, mappedDevice) {
if (type !== 'message') {
canHandleEvent(type, data, resolvedEntity) {
if (type !== 'message' || !resolvedEntity) {
return false;
}
@@ -83,12 +83,12 @@ class DeviceReceive extends BaseExtension {
return false;
}
if (data.device.modelID === null && data.device.interviewing) {
if (!data.device.modelID && data.device.interviewing) {
logger.debug(`Skipping message, modelID is undefined and still interviewing`);
return false;
}
if (!mappedDevice) {
if (!resolvedEntity.definition) {
logger.warn(`Received message from unsupported device with Zigbee model '${data.device.modelID}'`);
logger.warn(`Please see: https://www.zigbee2mqtt.io/how_tos/how_to_support_new_devices.html.`);
return false;
@@ -97,12 +97,12 @@ class DeviceReceive extends BaseExtension {
return true;
}
onZigbeeEvent(type, data, mappedDevice, settingsDevice) {
if (!this.canHandleEvent(type, data, mappedDevice)) {
onZigbeeEvent(type, data, resolvedEntity) {
if (!this.canHandleEvent(type, data, resolvedEntity)) {
return;
}
const converters = mappedDevice.fromZigbee.filter((c) => {
const converters = resolvedEntity.definition.fromZigbee.filter((c) => {
const type = Array.isArray(c.type) ? c.type.includes(data.type) : c.type === data.type;
return c.cluster === data.cluster && type;
});
@@ -110,12 +110,15 @@ class DeviceReceive extends BaseExtension {
// Check if there is an available converter
if (!converters.length) {
logger.debug(
`No converter available for '${mappedDevice.model}' with cluster '${data.cluster}' ` +
`No converter available for '${resolvedEntity.definition.model}' with cluster '${data.cluster}' ` +
`and type '${data.type}' and data '${JSON.stringify(data.data)}'`,
);
return;
}
const debounce = resolvedEntity.settings.debounce || settings.get().device_options.debounce;
const debounceIgnore = resolvedEntity.settings.debounce_ignore || settings.get().device_options.debounce_ignore;
// Convert this Zigbee message to a MQTT message.
// Get payload for the message.
// - If a payload is returned publish it to the MQTT broker
@@ -137,17 +140,12 @@ class DeviceReceive extends BaseExtension {
}
// Check if we have to debounce
if (settingsDevice && settingsDevice.hasOwnProperty('debounce')) {
this.publishDebounce(
data.device.ieeeAddr,
payload,
settingsDevice.debounce,
settingsDevice.debounce_ignore,
);
if (debounce) {
this.publishDebounce(data.device.ieeeAddr, payload, debounce, debounceIgnore);
} else {
this.publishEntityState(data.device.ieeeAddr, payload);
if (settings.get().homeassistant) {
if (settings.get().homeassistant && settings.get().advanced.homeassistant_legacy_triggers) {
/**
* Publish an empty value for click and action payload, in this way Home Assistant
* can use Home Assistant entities in automations.
@@ -168,7 +166,7 @@ class DeviceReceive extends BaseExtension {
let payload = {};
converters.forEach((converter) => {
const options = {...settings.get().device_options, ...settings.getDevice(data.device.ieeeAddr)};
const converted = converter.convert(mappedDevice, data, publish, options, meta);
const converted = converter.convert(resolvedEntity.definition, data, publish, options, meta);
if (converted) {
payload = {...payload, ...converted};
}
+58 -21
View File
@@ -1,7 +1,5 @@
const zigbeeHerdsmanConverters = require('zigbee-herdsman-converters');
const logger = require('../util/logger');
const CC2530Router = zigbeeHerdsmanConverters.devices.find((d) => d.model === 'CC2530.ROUTER');
const BASICZBR3 = zigbeeHerdsmanConverters.devices.find((d) => d.model === 'BASICZBR3');
const ZNLDP12LM = zigbeeHerdsmanConverters.devices.find((d) => d.model === 'ZNLDP12LM');
const utils = require('../util/utils');
const BaseExtension = require('./baseExtension');
@@ -12,10 +10,26 @@ const defaultConfiguration = {
minimumReportInterval: 3, maximumReportInterval: 300, reportableChange: 1,
};
const devicesNotSupportingReporting = [CC2530Router, BASICZBR3];
const devicesNotSupportingReporting = [
zigbeeHerdsmanConverters.devices.find((d) => d.model === 'CC2530.ROUTER'),
zigbeeHerdsmanConverters.devices.find((d) => d.model === 'BASICZBR3'),
zigbeeHerdsmanConverters.devices.find((d) => d.model === 'ZM-CSW032-D'),
];
const reportKey = 1;
const getColorCapabilities = async (endpoint) => {
if (endpoint.getClusterAttributeValue('lightingColorCtrl', 'colorCapabilities') === undefined) {
await endpoint.read('lightingColorCtrl', ['colorCapabilities']);
}
const value = endpoint.getClusterAttributeValue('lightingColorCtrl', 'colorCapabilities');
return {
colorTemperature: (value & 1<<4) > 0,
colorXY: (value & 1<<3) > 0,
};
};
const clusters = {
'genOnOff': [
{attribute: 'onOff', ...defaultConfiguration, minimumReportInterval: 0, reportableChange: 0},
@@ -24,9 +38,18 @@ const clusters = {
{attribute: 'currentLevel', ...defaultConfiguration},
],
'lightingColorCtrl': [
{attribute: 'colorTemperature', ...defaultConfiguration},
{attribute: 'currentX', ...defaultConfiguration},
{attribute: 'currentY', ...defaultConfiguration},
{
attribute: 'colorTemperature', ...defaultConfiguration,
condition: async (endpoint) => (await getColorCapabilities(endpoint)).colorTemperature,
},
{
attribute: 'currentX', ...defaultConfiguration,
condition: async (endpoint) => (await getColorCapabilities(endpoint)).colorXY,
},
{
attribute: 'currentY', ...defaultConfiguration,
condition: async (endpoint) => (await getColorCapabilities(endpoint)).colorXY,
},
],
'closuresWindowCovering': [
{attribute: 'currentPositionLiftPercentage', ...defaultConfiguration},
@@ -84,8 +107,8 @@ class DeviceReport extends BaseExtension {
this.pollDebouncers = {};
}
shouldIgnoreClusterForDevice(cluster, mappedDevice) {
if (mappedDevice === ZNLDP12LM && cluster === 'closuresWindowCovering') {
shouldIgnoreClusterForDevice(cluster, definition) {
if (definition === ZNLDP12LM && cluster === 'closuresWindowCovering') {
// Device announces it but doesn't support it
// https://github.com/Koenkk/zigbee2mqtt/issues/2611
return true;
@@ -94,17 +117,28 @@ class DeviceReport extends BaseExtension {
return false;
}
async setupReporting(device, mappedDevice) {
async setupReporting(resolvedEntity) {
const {device, definition} = resolvedEntity;
if (this.configuring.has(device.ieeeAddr) || this.failed.has(device.ieeeAddr)) return;
this.configuring.add(device.ieeeAddr);
try {
for (const ep of device.endpoints) {
for (const [cluster, configuration] of Object.entries(clusters)) {
if (ep.supportsInputCluster(cluster) && !this.shouldIgnoreClusterForDevice(cluster, mappedDevice)) {
if (ep.supportsInputCluster(cluster) && !this.shouldIgnoreClusterForDevice(cluster, definition)) {
logger.debug(`Setup reporting for '${device.ieeeAddr}' - ${ep.ID} - ${cluster}`);
const items = [];
for (const entry of configuration) {
if (!entry.hasOwnProperty('condition') || (await entry.condition(ep))) {
items.push({...entry});
delete items[items.length - 1].condition;
}
}
await ep.bind(cluster, this.coordinatorEndpoint);
await ep.configureReporting(cluster, configuration);
await ep.configureReporting(cluster, items);
logger.info(
`Successfully setup reporting for '${device.ieeeAddr}' - ${ep.ID} - ${cluster}`,
);
@@ -126,9 +160,11 @@ class DeviceReport extends BaseExtension {
this.configuring.delete(device.ieeeAddr);
}
shouldSetupReporting(mappedDevice, device, messageType) {
if (!device || !mappedDevice) return false;
shouldSetupReporting(resolvedEntity, messageType) {
if (!resolvedEntity || !resolvedEntity.device || !resolvedEntity.definition ||
messageType === 'deviceLeave') return false;
const {device, definition} = resolvedEntity;
// Handle messages of type endDeviceAnnce and devIncoming.
// This message is typically send when a device comes online after being powered off
// Ikea TRADFRI tend to forget their reporting after powered off.
@@ -139,7 +175,7 @@ class DeviceReport extends BaseExtension {
if (device.meta.hasOwnProperty('reporting') && device.meta.reporting === reportKey) return false;
if (!utils.isRouter(device) || utils.isBatteryPowered(device)) return false;
// Gledopto devices don't support reporting.
if (devicesNotSupportingReporting.includes(mappedDevice) || mappedDevice.vendor === 'Gledopto') return false;
if (devicesNotSupportingReporting.includes(definition) || definition.vendor === 'Gledopto') return false;
return true;
}
@@ -147,16 +183,16 @@ class DeviceReport extends BaseExtension {
this.coordinatorEndpoint = this.zigbee.getDevicesByType('Coordinator')[0].getEndpoint(1);
for (const device of this.zigbee.getClients()) {
const mappedDevice = zigbeeHerdsmanConverters.findByZigbeeModel(device.modelID);
if (this.shouldSetupReporting(mappedDevice, device, null)) {
this.setupReporting(device, mappedDevice);
const resolvedEntity = this.zigbee.resolveEntity(device);
if (this.shouldSetupReporting(resolvedEntity, null)) {
this.setupReporting(resolvedEntity);
}
}
}
onZigbeeEvent(type, data, mappedDevice, settingsDevice) {
if (this.shouldSetupReporting(mappedDevice, data.device, type)) {
this.setupReporting(data.device, mappedDevice);
onZigbeeEvent(type, data, resolvedEntity) {
if (this.shouldSetupReporting(resolvedEntity, type)) {
this.setupReporting(resolvedEntity);
}
if (type === 'message') {
@@ -182,7 +218,8 @@ class DeviceReport extends BaseExtension {
let toPoll = [];
// Add bound devices
toPoll = toPoll.concat([].concat(...message.device.endpoints.map((e) => e.binds.map((e) => e))));
toPoll = toPoll.concat([].concat(...message.device.endpoints.map((e) =>
e.binds.map((e) => e).filter((e) => e.target))));
toPoll = toPoll.filter((e) => e.target.constructor.name === 'Endpoint');
toPoll = toPoll.filter((e) => e.target.getDevice().type !== 'Coordinator');
toPoll = toPoll.map((e) => e.target);
+31 -11
View File
@@ -6,7 +6,7 @@ const utils = require('../util/utils');
const assert = require('assert');
const BaseExtension = require('./baseExtension');
const postfixes = utils.getPostfixes();
const postfixes = utils.getEndpointNames();
const topicRegex = new RegExp(`^(.+?)(?:/(${postfixes.join('|')}))?/(get|set)(?:/(.+))?`);
const groupConverters = [
@@ -59,7 +59,15 @@ class EntityPublish extends BaseExtension {
const entity = this.zigbee.resolveEntity(entityName);
if (!entity) {
this.mqtt.log('entity_not_found', {friendly_name: entityName});
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const message = {friendly_name: entityName};
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `entity_not_found`, message}),
);
}
logger.error(`Entity '${entityName}' is unknown`);
return;
}
@@ -74,22 +82,22 @@ class EntityPublish extends BaseExtension {
assert(entity.type === 'device' || entity.type === 'group');
if (entity.type === 'device') {
// Map device to a model
if (!entity.mapped) {
if (!entity.definition) {
logger.warn(`Device with modelID '${entity.device.modelID}' is not supported.`);
logger.warn(`Please see: https://www.zigbee2mqtt.io/how_tos/how_to_support_new_devices.html`);
return;
}
device = entity.device;
mapped = entity.mapped;
mapped = entity.definition;
target = entity.endpoint;
converters = entity.mapped.toZigbee;
options = entity.mapped.meta && entity.mapped.meta.options ? entity.mapped.meta.options : {};
options = {...options, ...entity.settings};
converters = entity.definition.toZigbee;
options = entity.settings;
} else {
converters = groupConverters;
target = entity.group;
options = entity.settings;
mapped = entity.group.members.map((e) => zigbeeHerdsmanConverters.findByZigbeeModel(e.getDevice().modelID));
}
// Convert the MQTT message to a Zigbee message.
@@ -136,7 +144,7 @@ class EntityPublish extends BaseExtension {
if (entity.type === 'device' && key.includes('_')) {
const underscoreIndex = key.lastIndexOf('_');
const possiblePostfix = key.substring(underscoreIndex + 1, key.length);
if (utils.getPostfixes().includes(possiblePostfix)) {
if (utils.getEndpointNames().includes(possiblePostfix)) {
postfix = possiblePostfix;
key = key.substring(0, underscoreIndex);
const device = target.getDevice();
@@ -175,8 +183,12 @@ class EntityPublish extends BaseExtension {
const msg = result.state;
if (postfix) {
msg[`state_${postfix}`] = msg.state;
delete msg.state;
for (const key of ['state', 'brightness']) {
if (msg.hasOwnProperty(key)) {
msg[`${key}_${postfix}`] = msg[key];
delete msg[key];
}
}
}
this.publishEntityState(entity.settings.ID, msg);
@@ -207,7 +219,15 @@ class EntityPublish extends BaseExtension {
`Publish '${topic.type}' '${key}' to '${entity.name}' failed: '${error}'`;
logger.error(message);
logger.debug(error.stack);
this.mqtt.log('zigbee_publish_error', message, {friendly_name: entity.name});
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const meta = {friendly_name: entity.name};
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `zigbee_publish_error`, message, meta}),
);
}
}
usedConverters.push(converter);
+59 -14
View File
@@ -1,6 +1,8 @@
const settings = require('../util/settings');
const logger = require('../util/logger');
const BaseExtension = require('./baseExtension');
const utils = require('../util/utils');
const postfixes = utils.getEndpointNames();
const topicRegex = new RegExp(`^${settings.get().mqtt.base_topic}/bridge/group/(.+)/(remove|add|remove_all)$`);
const topicRegexRemoveAll = new RegExp(`^${settings.get().mqtt.base_topic}/bridge/group/remove_all$`);
@@ -24,7 +26,7 @@ class Groups extends BaseExtension {
async onZigbeeStarted() {
await this.syncGroupsWithSettings();
this.state.on('stateChange', this.onStateChange);
this.eventBus.on('stateChange', this.onStateChange);
}
async syncGroupsWithSettings() {
@@ -142,9 +144,16 @@ class Groups extends BaseExtension {
if (!group || group.type !== 'group') {
logger.error(`Group '${topicMatch[1]}' does not exist`);
this.mqtt.log(
`device_group_${type}_failed`,
{friendly_name: message, group: topicMatch[1], error: 'group doesn\'t exists'});
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const payload = {friendly_name: message, group: topicMatch[1], error: 'group doesn\'t exists'};
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `device_group_${type}_failed`, message: payload}),
);
}
return;
}
} else if (topic.match(topicRegexRemoveAll)) {
@@ -156,9 +165,16 @@ class Groups extends BaseExtension {
const entity = this.zigbee.resolveEntity(message);
if (!entity || !entity.type === 'device') {
logger.error(`Device '${message}' does not exist`);
this.mqtt.log(
`device_group_${type}_failed`,
{friendly_name: message, group: topicMatch[1], error: 'entity doesn\'t exists'});
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const payload = {friendly_name: message, group: topicMatch[1], error: 'entity doesn\'t exists'};
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `device_group_${type}_failed`, message: payload}),
);
}
return;
}
@@ -167,12 +183,17 @@ class Groups extends BaseExtension {
`${entity.name}/${entity.endpoint.ID}`,
];
if (entity.endpointName) {
keys.push(`${entity.device.ieeeAddr}/${entity.endpointName}`);
keys.push(`${entity.name}/${entity.endpointName}`);
const definition = entity.definition;
const endpoints = definition && definition.endpoint ? definition.endpoint(entity.device) : null;
const endpointName = endpoints ? Object.entries(endpoints).find((e) => e[1] === entity.endpoint.ID)[0] : null;
if (endpointName) {
keys.push(`${entity.device.ieeeAddr}/${endpointName}`);
keys.push(`${entity.name}/${endpointName}`);
}
if (entity.isDefaultEndpoint) {
const hasEndpointName = postfixes.find((p) => message.endsWith(`/${p}`));
if (!hasEndpointName) {
keys.push(entity.name);
keys.push(entity.device.ieeeAddr);
}
@@ -181,18 +202,42 @@ class Groups extends BaseExtension {
logger.info(`Adding '${entity.name}' to '${group.name}'`);
await entity.endpoint.addToGroup(group.group);
settings.addDeviceToGroup(group.settings.ID, keys);
this.mqtt.log('device_group_add', {friendly_name: entity.name, group: group.name});
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const payload = {friendly_name: entity.name, group: group.name};
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `device_group_add`, message: payload}),
);
}
} else if (type === 'remove') {
logger.info(`Removing '${entity.name}' from '${group.name}'`);
await entity.endpoint.removeFromGroup(group.group);
settings.removeDeviceFromGroup(group.settings.ID, keys);
this.mqtt.log('device_group_remove', {friendly_name: entity.name, group: group.name});
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const payload = {friendly_name: entity.name, group: group.name};
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `device_group_remove`, message: payload}),
);
}
} else { // remove_all
logger.info(`Removing '${entity.name}' from all groups`);
await entity.endpoint.removeFromAllGroups();
for (const settingsGroup of settings.getGroups()) {
settings.removeDeviceFromGroup(settingsGroup.ID, keys);
this.mqtt.log('device_group_remove_all', {friendly_name: entity.name});
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const payload = {friendly_name: entity.name};
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `device_group_remove_all`, message: payload}),
);
}
}
}
}
+423 -33
View File
@@ -3,6 +3,7 @@ const settings = require('../util/settings');
const logger = require('../util/logger');
const zigbee2mqttVersion = require('../../package.json').version;
const BaseExtension = require('./baseExtension');
const objectAssignDeep = require(`object-assign-deep`);
const cfg = {
// Binary sensor
@@ -16,6 +17,15 @@ const cfg = {
device_class: 'motion',
},
},
'binary_sensor_sos': {
type: 'binary_sensor',
object_id: 'sos',
discovery_payload: {
payload_on: true,
payload_off: false,
value_template: '{{ value_json.sos }}',
},
},
'binary_sensor_presence': {
type: 'binary_sensor',
object_id: 'presence',
@@ -147,7 +157,7 @@ const cfg = {
},
'sensor_illuminance_lux': {
type: 'sensor',
object_id: 'illuminance',
object_id: 'illuminance_lux',
discovery_payload: {
unit_of_measurement: 'lx',
device_class: 'illuminance',
@@ -203,7 +213,7 @@ const cfg = {
object_id: 'power',
discovery_payload: {
unit_of_measurement: 'W',
icon: 'mdi:factory',
icon: 'mdi:flash',
value_template: '{{ value_json.power }}',
},
},
@@ -212,7 +222,7 @@ const cfg = {
object_id: 'current',
discovery_payload: {
unit_of_measurement: 'A',
icon: 'mdi:power-plug',
icon: 'mdi:current-ac',
value_template: '{{ value_json.current }}',
},
},
@@ -221,10 +231,55 @@ const cfg = {
object_id: 'voltage',
discovery_payload: {
unit_of_measurement: 'V',
icon: 'mdi:flash',
icon: 'mdi:alpha-v',
value_template: '{{ value_json.voltage }}',
},
},
'sensor_current_phase_b': {
type: 'sensor',
object_id: 'current_phase_b',
discovery_payload: {
unit_of_measurement: 'A',
icon: 'mdi:current-ac',
value_template: '{{ value_json.current_phase_b }}',
},
},
'sensor_voltage_phase_b': {
type: 'sensor',
object_id: 'voltage_phase_b',
discovery_payload: {
unit_of_measurement: 'V',
icon: 'mdi:alpha-v',
value_template: '{{ value_json.voltage_phase_b }}',
},
},
'sensor_current_phase_c': {
type: 'sensor',
object_id: 'current_phase_c',
discovery_payload: {
unit_of_measurement: 'A',
icon: 'mdi:current-ac',
value_template: '{{ value_json.current_phase_c }}',
},
},
'sensor_voltage_phase_c': {
type: 'sensor',
object_id: 'voltage_phase_c',
discovery_payload: {
unit_of_measurement: 'V',
icon: 'mdi:alpha-v',
value_template: '{{ value_json.voltage_phase_c }}',
},
},
'sensor_energy': {
type: 'sensor',
object_id: 'energy',
discovery_payload: {
unit_of_measurement: 'kWh',
icon: 'mdi:power-plug',
value_template: '{{ value_json.energy }}',
},
},
'sensor_action': {
type: 'sensor',
object_id: 'action',
@@ -233,6 +288,14 @@ const cfg = {
value_template: '{{ value_json.action }}',
},
},
'sensor_action_color': {
type: 'sensor',
object_id: 'action_color',
discovery_payload: {
value_template: '{{ value_json.action_color }}',
icon: 'mdi:palette',
},
},
'sensor_brightness': {
type: 'sensor',
object_id: 'brightness',
@@ -405,6 +468,35 @@ const cfg = {
command_topic: true,
},
},
'switch_window_detection': {
type: 'switch',
object_id: 'window_detection',
discovery_payload: {
state_topic: true,
command_topic: true,
command_topic_postfix: 'window_detection',
payload_off: 'OFF',
payload_on: 'ON',
state_off: 'OFF',
state_on: 'ON',
value_template: '{{ value_json.window_detection }}',
icon: 'mdi:window-open-variant',
},
},
'switch_valve_detection': {
type: 'switch',
object_id: 'valve_detection',
discovery_payload: {
state_topic: true,
command_topic: true,
command_topic_postfix: 'valve_detection',
payload_off: 'OFF',
payload_on: 'ON',
state_off: 'OFF',
state_on: 'ON',
value_template: '{{ value_json.valve_detection }}',
},
},
// Cover
'cover': {
@@ -466,6 +558,20 @@ const cfg = {
value_template: '{{ value_json.keypad_lockout }}',
},
},
'lock_child_lock': {
type: 'lock',
object_id: 'child_lock',
discovery_payload: {
state_topic: true,
command_topic: true,
command_topic_postfix: 'child_lock',
payload_lock: 'LOCK',
payload_unlock: 'UNLOCK',
state_locked: 'LOCKED',
state_unlocked: 'UNLOCKED',
value_template: '{{ value_json.child_lock }}',
},
},
// Thermostat/HVAC
'thermostat': (minTemp=7, maxTemp=30, temperatureStateProperty='occupied_heating_setpoint', tempStep=1) => {
@@ -491,6 +597,39 @@ const cfg = {
},
};
},
'thermostat_heatcool': /* istanbul ignore next */ (minTemp=7, maxTemp=30, tempStep=0.5, fanModes=[]) => {
return {
type: 'climate',
object_id: 'climate',
discovery_payload: {
state_topic: false,
unit_of_measurement: '°C',
min_temp: `${minTemp}`,
max_temp: `${maxTemp}`,
modes: ['off', 'auto', 'heat', 'cool'],
mode_state_topic: true,
mode_state_template: '{{ value_json.system_mode }}',
mode_command_topic: true,
current_temperature_topic: true,
current_temperature_template: '{{ value_json.local_temperature }}',
temperature_low_state_topic: true,
temperature_low_state_template: `{{ value_json.occupied_heating_setpoint }}`,
temperature_high_state_topic: true,
temperature_high_state_template: `{{ value_json.occupied_cooling_setpoint }}`,
temperature_low_command_topic: 'occupied_heating_setpoint',
temperature_high_command_topic: 'occupied_cooling_setpoint',
temp_step: tempStep,
action_topic: true,
action_template:
'{% set values = {\'idle\':\'off\',\'heat\':\'heating\',\'cool\':\'cooling\',\'fan only\':\'fan\'}'+
' %}{{ values[value_json.running_state] }}',
fan_modes: fanModes,
fan_mode_command_topic: true,
fan_mode_state_topic: true,
fan_mode_state_template: '{{ value_json.fan_mode }}',
},
};
},
// Fan
'fan': {
@@ -507,6 +646,22 @@ const cfg = {
speeds: ['off', 'low', 'medium', 'high', 'on', 'auto', 'smart'],
},
},
// Trigger
'trigger_action': {
type: 'device_automation',
discovery_payload: {
automation_type: 'trigger',
type: 'action',
},
},
'trigger_click': {
type: 'device_automation',
discovery_payload: {
automation_type: 'trigger',
type: 'click',
},
},
};
const switchWithPostfix = (postfix) => {
@@ -523,6 +678,14 @@ const switchWithPostfix = (postfix) => {
};
};
const lightWithPostfix = (configType, postfix) => {
const config = objectAssignDeep.noMutate(cfg[configType]);
config['object_id'] = `light_${postfix}`;
config['discovery_payload']['command_topic_prefix'] = postfix;
config['discovery_payload']['state_topic_postfix'] = postfix;
return config;
};
// Map homeassitant configurations to devices.
const mapping = {
'WXKG01LM': [cfg.sensor_click, cfg.sensor_battery],
@@ -577,6 +740,7 @@ const mapping = {
'73739': [cfg.light_brightness_colortemp_colorxy],
'72569': [cfg.light_brightness_colortemp],
'72567': [cfg.light_brightness_colortemp],
'75541': [cfg.light_brightness_colortemp_colorxy],
'22670': [cfg.light_brightness],
'ICTC-G-1': [cfg.sensor_brightness, cfg.sensor_battery, cfg.sensor_action],
'ICPSHC24-30EU-IL-1': [cfg.light_brightness],
@@ -605,7 +769,10 @@ const mapping = {
'SL 110 W': [cfg.light_brightness],
'AA68199': [cfg.light_brightness_colortemp],
'QBKG11LM': [cfg.switch, cfg.sensor_power, cfg.sensor_click],
'QBKG12LM': [switchWithPostfix('left'), switchWithPostfix('right'), cfg.sensor_power, cfg.sensor_click],
'QBKG12LM': [
switchWithPostfix('left'), switchWithPostfix('right'), cfg.sensor_power, cfg.sensor_click,
cfg.sensor_temperature,
],
'K2RGBW01': [cfg.light_brightness_colortemp_colorxy],
'9290011370': [cfg.light_brightness],
'DNCKATSW001': [cfg.switch],
@@ -685,7 +852,7 @@ const mapping = {
'4058075816794': [cfg.light_brightness_colortemp],
'4052899926158': [cfg.light_brightness],
'4058075036185': [cfg.light_brightness_colortemp_colorxy],
'50049': [cfg.light_brightness_colorxy],
'50049': [cfg.light_brightness_colortemp_colorxy],
'915005733701': [cfg.light_brightness_colortemp_colorxy],
'RB 285 C': [cfg.light_brightness_colortemp_colorxy],
'3216331P5': [cfg.light_brightness_colortemp],
@@ -737,7 +904,7 @@ const mapping = {
'D1531': [cfg.light_brightness],
'D1532': [cfg.light_brightness],
'D1533': [cfg.light_brightness],
'AV2010/32': [],
'AV2010/32': [cfg.thermostat(7, 30, 'occupied_heating_setpoint', 0.5), cfg.sensor_battery],
'HGZB-07A': [cfg.light_brightness_colortemp_colorxy],
'E1524/E1810': [cfg.sensor_action, cfg.sensor_battery],
'GL-C-006': [cfg.light_brightness_colortemp],
@@ -774,6 +941,7 @@ const mapping = {
'E1746': [],
'LED1836G9': [cfg.light_brightness],
'YRD426NRSC': [cfg.lock, cfg.sensor_battery],
'YRD246HA20BP': [cfg.lock, cfg.sensor_battery],
'E1743': [cfg.sensor_click, cfg.sensor_battery],
'LED1732G11': [cfg.light_brightness_colortemp],
'LED1736G9': [cfg.light_brightness_colortemp],
@@ -849,11 +1017,15 @@ const mapping = {
'HGZB-01A': [cfg.switch],
'HGZB-02A': [cfg.light_brightness],
'MCT-350 SMA': [cfg.binary_sensor_contact],
'3310-S': [cfg.sensor_temperature, cfg.sensor_battery],
'3310-S': [cfg.sensor_temperature, cfg.sensor_humidity, cfg.sensor_battery],
'IM6001-WLP01': [
cfg.sensor_temperature, cfg.binary_sensor_water_leak,
cfg.sensor_battery,
],
'WTR-UK-V2': [
cfg.sensor_temperature, cfg.binary_sensor_water_leak,
cfg.sensor_battery,
],
'3315-S': [
cfg.sensor_temperature, cfg.binary_sensor_water_leak,
cfg.sensor_battery,
@@ -900,6 +1072,7 @@ const mapping = {
'YMF40': [cfg.lock, cfg.sensor_battery],
'V3-BTZB': [cfg.lock],
'3RSS008Z': [cfg.switch, cfg.sensor_battery],
'3RSS007Z': [cfg.switch],
'99432': [cfg.fan, cfg.light_brightness],
'511.10': [cfg.light_brightness],
'IM6001-MPP01': [
@@ -908,7 +1081,7 @@ const mapping = {
'HLC821-Z-SC': [cfg.light_brightness],
'RS 228 T': [cfg.light_brightness_colortemp],
'67200BL': [cfg.switch],
'2430-100': [cfg.sensor_action],
'InstaRemote': [cfg.sensor_action],
'100.425.90': [cfg.switch],
'74580': [cfg.light_brightness],
'HS1CA-E': [
@@ -937,9 +1110,7 @@ const mapping = {
switchWithPostfix('bottom_left'), switchWithPostfix('bottom_right'), switchWithPostfix('center'),
switchWithPostfix('top_left'), switchWithPostfix('top_right'),
],
'NCZ-3011-HA': [
cfg.binary_sensor_occupancy, cfg.sensor_humidity, cfg.sensor_temperature,
],
'NCZ-3011-HA': [cfg.binary_sensor_contact, cfg.sensor_battery],
'MEAZON_BIZY_PLUG': [cfg.sensor_power, cfg.switch, cfg.sensor_temperature],
'MEAZON_DINRAIL': [cfg.sensor_power, cfg.switch, cfg.sensor_temperature],
'HS1CA-M': [cfg.binary_sensor_carbon_monoxide, cfg.binary_sensor_battery_low],
@@ -994,7 +1165,7 @@ const mapping = {
'2AJZ4KPKEY': [cfg.sensor_click, cfg.sensor_battery],
'2AJZ4KPFT': [cfg.sensor_temperature, cfg.sensor_humidity, cfg.sensor_battery],
'TT001ZAV20': [cfg.sensor_temperature, cfg.sensor_humidity, cfg.sensor_battery],
'ZM-CSW002-D': [switchWithPostfix('l1'), switchWithPostfix('l2'), cfg.sensor_power],
'TS0002': [switchWithPostfix('l1'), switchWithPostfix('l2')],
'LVS-SN10ZW': [cfg.sensor_battery, cfg.binary_sensor_occupancy],
'LVS-ZB15R': [cfg.switch],
'TH1123ZB': [
@@ -1041,7 +1212,7 @@ const mapping = {
'9290018187B': [cfg.light_brightness_colortemp_colorxy],
'1741830P7': [cfg.light_brightness_colortemp_colorxy],
'Z3-1BRL': [cfg.sensor_action, cfg.sensor_brightness],
'HSIO18008': [cfg.binary_sensor_gas, cfg.binary_sensor_battery_low],
'HS1CG-E': [cfg.binary_sensor_gas],
'LED1842G3': [cfg.light_brightness],
'SR-ZG9001K4-DIM2': [cfg.sensor_battery, cfg.sensor_click],
'ICZB-IW11SW': [cfg.switch],
@@ -1053,7 +1224,7 @@ const mapping = {
'2AJZ4KPDR': [cfg.sensor_battery, cfg.binary_sensor_contact, cfg.binary_sensor_battery_low],
'6717-84': [cfg.switch],
'ICZB-KPD18S': [cfg.sensor_battery, cfg.sensor_click, cfg.sensor_action],
'100.469.65': [cfg.light_brightness_colortemp],
'8195-55': [cfg.light_brightness_colortemp],
'E1757': [cfg.cover_position, cfg.sensor_battery],
'E1926': [cfg.cover_position, cfg.sensor_battery],
'LWG004': [cfg.light_brightness],
@@ -1079,7 +1250,7 @@ const mapping = {
'929002241201': [cfg.light_brightness],
'YRD210-HA-605': [cfg.lock, cfg.sensor_battery],
'YRD220/240 TSDB': [cfg.lock, cfg.sensor_battery],
'ZM-CSW032-D': [cfg.cover],
'ZM-CSW032-D': [cfg.cover_position],
'LH-32ZB': [cfg.sensor_humidity, cfg.sensor_temperature, cfg.sensor_battery],
'511.201': [cfg.light_brightness],
'ZNCLDJ12LM': [cfg.cover_position],
@@ -1138,9 +1309,10 @@ const mapping = {
'8718699693985': [cfg.sensor_action, cfg.sensor_battery],
'GL-D-004ZS': [cfg.light_brightness_colortemp_colorxy],
'AC10787': [cfg.light_brightness_colortemp],
'F-APP-UK-V2': [cfg.switch],
'S9TSZGB': [cfg.sensor_action],
'SP-EUC01': [cfg.switch],
'F-APP-UK-V2': [cfg.switch, cfg.sensor_power],
'S9TSZGB_3': [cfg.sensor_action],
'S9TSZGB_1': [cfg.sensor_action],
'SP-EUC01': [cfg.switch, cfg.sensor_power],
'511.012': [cfg.light_brightness],
'GL-S-008Z': [cfg.light_brightness_colortemp_colorxy],
'TZSW22FW-L4': [switchWithPostfix('top'), switchWithPostfix('bottom')],
@@ -1200,6 +1372,8 @@ const mapping = {
'GZCGQ01LM': [cfg.sensor_battery, cfg.sensor_illuminance, cfg.sensor_illuminance_lux],
'9290018215': [cfg.light_brightness],
'1743230P7': [cfg.light_brightness_colortemp_colorxy],
'1744130P7': [cfg.light_brightness_colortemp_colorxy],
'1743130P7': [cfg.light_brightness_colortemp_colorxy],
'100.110.51': [cfg.light_brightness_colortemp],
'ZL1000100-CCT-US-V1A02': [cfg.light_brightness],
'HGZB-DLC4-N12B': [cfg.light_brightness_colortemp_colorxy],
@@ -1214,7 +1388,7 @@ const mapping = {
switchWithPostfix('l1'), switchWithPostfix('l2'),
switchWithPostfix('l3'), switchWithPostfix('l4'),
],
'STS-WTR-250': [cfg.binary_sensor_water_leak, cfg.sensor_battery],
'STS-WTR-250': [cfg.binary_sensor_water_leak, cfg.sensor_battery, cfg.sensor_temperature],
'ZG2835RAC': [cfg.light_brightness],
'BW-IS2': [cfg.binary_sensor_contact, cfg.sensor_battery],
'BW-IS3': [cfg.binary_sensor_occupancy],
@@ -1255,6 +1429,85 @@ const mapping = {
'73743': [cfg.sensor_action, cfg.sensor_battery],
'C4': [cfg.sensor_action],
'GL-D-003ZS': [cfg.light_brightness_colortemp_colorxy],
'66492-001': [cfg.lock, cfg.sensor_battery],
'798.09': [cfg.light_brightness_colortemp_colorxy],
'U202DST600ZB': [lightWithPostfix('light_brightness', 'l1'), lightWithPostfix('light_brightness', 'l2')],
'SM10ZW': [cfg.binary_sensor_contact, cfg.sensor_battery],
'ICZB-R11D': [cfg.light_brightness],
'SW2500ZB': [cfg.switch],
'4512703': [cfg.sensor_action, cfg.sensor_battery],
'4512702': [cfg.sensor_action, cfg.sensor_battery],
'4090331P9': [cfg.light_brightness_colortemp_colorxy],
'HS1EB': [cfg.sensor_click],
'HS2SW1A-N': [cfg.switch],
'HS2SW2A-N': [switchWithPostfix('left'), switchWithPostfix('right')],
'HS2SW3A-N': [switchWithPostfix('left'), switchWithPostfix('right'), switchWithPostfix('center')],
'LifeControl_Leak_Sensor': [cfg.binary_sensor_water_leak, cfg.sensor_battery],
'LifeControl_Door_Sensor': [cfg.binary_sensor_contact, cfg.sensor_battery],
'LifeControl_RGB_Led': [cfg.light_brightness_colortemp_colorxy],
'3323-G': [cfg.binary_sensor_contact, cfg.sensor_temperature, cfg.binary_sensor_battery_low],
'ZL1000400-CCT-EU-2-V1A02': [cfg.light_brightness_colortemp],
'ROB_200-007-0': [cfg.sensor_action, cfg.sensor_battery],
'PM-S140-ZB': [cfg.switch],
'PM-S240-ZB': [switchWithPostfix('top'), switchWithPostfix('bottom')],
'PM-S340-ZB': [switchWithPostfix('top'), switchWithPostfix('center'), switchWithPostfix('bottom')],
'U201DST600ZB': [cfg.light_brightness],
'U201SRY2KWZB': [cfg.switch],
'U202SRY2KWZB': [switchWithPostfix('l1'), switchWithPostfix('l2')],
'93999': [cfg.light_brightness],
'GS361A-H04': [
cfg.lock_child_lock,
cfg.switch_window_detection,
cfg.switch_valve_detection,
cfg.thermostat(5, 30, 'current_heating_setpoint', 0.5),
cfg.sensor_battery,
],
'HLC614-ZLL': [switchWithPostfix('l1'), switchWithPostfix('l2'), switchWithPostfix('l3')],
'EMIZB-132': [
cfg.sensor_power, cfg.sensor_voltage, cfg.sensor_current, cfg.sensor_energy, cfg.sensor_current_phase_b,
cfg.sensor_current_phase_c, cfg.sensor_voltage_phase_b, cfg.sensor_voltage_phase_c,
],
'S9ZGBRC01': [cfg.sensor_action, cfg.sensor_battery],
'511.557': [cfg.sensor_action],
'RL804CZB': [cfg.light_brightness_colortemp_colorxy],
'3420-G': [cfg.light_brightness],
'U02I007C.01': [
cfg.sensor_action, cfg.binary_sensor_contact, cfg.binary_sensor_water_leak,
cfg.sensor_temperature, cfg.sensor_humidity, cfg.sensor_battery,
],
'4080248P9': [cfg.light_brightness_colortemp_colorxy],
'4080148P9': [cfg.light_brightness_colortemp_colorxy],
'4058075148338': [cfg.light_brightness_colortemp],
'484719': [cfg.light_brightness],
'SEB01ZB': [cfg.binary_sensor_sos, cfg.sensor_battery],
'SBM01ZB': [cfg.binary_sensor_occupancy, cfg.sensor_battery],
'STH01ZB': [cfg.sensor_temperature, cfg.sensor_humidity, cfg.sensor_battery],
'SSA01ZB': [cfg.binary_sensor_smoke, cfg.sensor_battery],
'SCA01ZB': [cfg.binary_sensor_carbon_monoxide, cfg.sensor_battery],
'SGA01ZB': [cfg.binary_sensor_gas, cfg.sensor_battery],
'SWA01ZB': [cfg.binary_sensor_water_leak, cfg.sensor_battery],
'SDM01ZB': [cfg.binary_sensor_contact, cfg.sensor_battery],
'SFS01ZB': [cfg.switch],
'SLS301ZB_2': [switchWithPostfix('left'), switchWithPostfix('right')],
'SLS301ZB_3': [switchWithPostfix('left'), switchWithPostfix('right'), switchWithPostfix('center')],
'SSS401ZB': [cfg.switch, cfg.sensor_action],
'E12-N1E': [cfg.light_brightness_colortemp_colorxy],
'4040B': [cfg.sensor_power, switchWithPostfix('l1'), switchWithPostfix('l2')],
'3460-L': [cfg.sensor_action, cfg.sensor_temperature, cfg.sensor_battery],
'3157100': [cfg.thermostat_heatcool(10, 30, 1, ['auto', 'on']), cfg.sensor_battery],
'4257050-RZHAC': [cfg.switch, cfg.sensor_power],
'27087-03': [cfg.switch, cfg.sensor_battery],
'99140-002': [cfg.lock, cfg.sensor_battery],
'4512706': [cfg.sensor_battery, cfg.sensor_action],
'GL-S-004ZS': [cfg.light_brightness_colortemp_colorxy],
'7121131PU': [cfg.light_brightness_colortemp_colorxy],
'RL804QZB': [switchWithPostfix('l1'), switchWithPostfix('l2'), switchWithPostfix('l3')],
'RC-2000WH': [cfg.thermostat_heatcool(10, 30, 1, ['auto', 'on', 'smart'])],
'TH1300ZB': [cfg.thermostat()],
'SP 220': [cfg.switch],
'511.040': [cfg.light_brightness_colortemp_colorxy],
'511.344': [cfg.sensor_battery, cfg.sensor_action, cfg.sensor_action_color],
'SMSZB-120': [cfg.binary_sensor_smoke, cfg.sensor_temperature, cfg.sensor_battery],
};
Object.keys(mapping).forEach((key) => {
@@ -1270,6 +1523,7 @@ class HomeAssistant extends BaseExtension {
// A map of all discoverd devices
this.discovered = {};
this.discoveredTriggers = {};
if (!settings.get().advanced.cache_state) {
logger.warn('In order for HomeAssistant integration to work properly set `cache_state: true');
@@ -1283,6 +1537,8 @@ class HomeAssistant extends BaseExtension {
this.statusTopic = settings.get().advanced.homeassistant_status_topic;
this.eventBus.on('deviceRemoved', (data) => this.onDeviceRemoved(data.device));
this.eventBus.on('publishEntityState', (data) => this.onPublishEntityState(data));
this.eventBus.on('deviceRenamed', (data) => this.onDeviceRenamed(data.device));
}
onDeviceRemoved(device) {
@@ -1296,6 +1552,103 @@ class HomeAssistant extends BaseExtension {
}
}
async onPublishEntityState(data) {
/**
* In case we deal with a lightWithPostfix configuration Zigbee2mqtt publishes
* e.g. {state_l1: ON, brightness_l1: 250} to zigbee2mqtt/mydevice.
* As the Home Assistant MQTT JSON light cannot be configured to use state_l1/brightness_l1
* as the state variables, the state topic is set to zigbee2mqtt/mydevice/l1.
* Here we retrieve all the attributes with the _l1 values and republish them on
* zigbee2mqtt/mydevice/l1.
*/
if (data.entity.definition && mapping[data.entity.definition.model]) {
for (const config of mapping[data.entity.definition.model]) {
const match = /light_(.*)/.exec(config['object_id']);
if (match) {
const postfix = match[1];
const posfixRegExp = new RegExp(`(.*)_${postfix}`);
const payload = {};
for (const key of Object.keys(data.payload)) {
const keyMatch = posfixRegExp.exec(key);
if (keyMatch) {
payload[keyMatch[1]] = data.payload[key];
}
}
await this.mqtt.publish(
`${data.entity.name}/${postfix}`, JSON.stringify(payload), {},
);
}
}
}
/**
* Implements the MQTT device trigger (https://www.home-assistant.io/integrations/device_trigger.mqtt/)
* The MQTT device trigger does not support JSON parsing, so it cannot listen to zigbee2mqtt/my_device
* Whenever a device publish an {action: *} we discover an MQTT device trigger sensor
* and republish it to zigbee2mqtt/my_devic/action
*/
const key = ['action', 'click'].find((k) => data.payload.hasOwnProperty(k) && data.payload[k] !== '');
if (data.entity.definition && key) {
const device = data.entity.device;
if (!this.discoveredTriggers[device.ieeeAddr]) {
this.discoveredTriggers[device.ieeeAddr] = new Set();
}
const value = data.payload[key];
const discoveredKey = `${key}_${value}`;
if (!this.discoveredTriggers[device.ieeeAddr].has(discoveredKey)) {
const config = cfg[`trigger_${key}`];
config.object_id = `${key}_${value}`;
const topic = this.getDiscoveryTopic(config, device);
const payload = {
...config.discovery_payload,
subtype: value,
payload: value,
topic: `${settings.get().mqtt.base_topic}/${data.entity.name}/${key}`,
device: this.getDevicePayload(data.entity.settings, data.entity.definition),
};
await this.mqtt.publish(topic, JSON.stringify(payload), {retain: true, qos: 0}, this.discoveryTopic);
this.discoveredTriggers[device.ieeeAddr].add(discoveredKey);
}
await this.mqtt.publish(`${data.entity.name}/${key}`, value, {});
}
/**
* Publish a value for update_available (if not there yet) to prevent Home Assistant generating warnings of
* this value not being available.
*/
const mockedValues = [
{
property: 'update_available',
condition: data.entity.device && data.entity.definition && data.entity.definition.hasOwnProperty('ota'),
value: false,
},
{
property: 'water_leak',
condition: data.entity.device && data.entity.definition &&
mapping[data.entity.definition.model].includes(cfg.binary_sensor_water_leak),
value: false,
},
];
for (const entry of mockedValues) {
if (entry.condition && !data.payload.hasOwnProperty(entry.property)) {
logger.debug(`Mocking '${entry.property}' value for Home Assistant`);
this.publishEntityState(data.entity.device.ieeeAddr, {[entry.property]: entry.value});
}
}
}
onDeviceRenamed(device) {
const mappedModel = zigbeeHerdsmanConverters.findByZigbeeModel(device.modelID);
logger.info(`Refreshing Home Assistant discovery topic for '${device.ieeeAddr}'`);
this.discover(device, mappedModel, true);
}
async onMQTTConnected() {
this.mqtt.subscribe(this.statusTopic);
@@ -1309,10 +1662,15 @@ class HomeAssistant extends BaseExtension {
}
getConfigs(mappedModel) {
const configs = mapping[mappedModel.model].slice();
let configs = mapping[mappedModel.model].slice();
if (mappedModel.hasOwnProperty('ota')) {
configs.push(cfg.binary_sensor_update_available);
}
if (!settings.get().advanced.homeassistant_legacy_triggers) {
configs = configs.filter((c) => c !== cfg.sensor_action && c !== cfg.sensor_click);
}
return configs;
}
@@ -1332,7 +1690,11 @@ class HomeAssistant extends BaseExtension {
this.getConfigs(mappedModel).forEach((config) => {
const topic = this.getDiscoveryTopic(config, device);
const payload = {...config.discovery_payload};
const stateTopic = `${settings.get().mqtt.base_topic}/${entity.friendlyName}`;
let stateTopic = `${settings.get().mqtt.base_topic}/${entity.friendlyName}`;
if (payload.state_topic_postfix) {
stateTopic += `/${payload.state_topic_postfix}`;
delete payload.state_topic_postfix;
}
if (!payload.hasOwnProperty('state_topic') || payload.state_topic) {
payload.state_topic = stateTopic;
@@ -1360,13 +1722,7 @@ class HomeAssistant extends BaseExtension {
payload.unique_id = `${entity.ID}_${config.object_id}_${settings.get().mqtt.base_topic}`;
// Attributes for device registry
payload.device = {
identifiers: [`zigbee2mqtt_${entity.ID}`],
name: entity.friendlyName,
sw_version: `Zigbee2mqtt ${zigbee2mqttVersion}`,
model: `${mappedModel.description} (${mappedModel.model})`,
manufacturer: mappedModel.vendor,
};
payload.device = this.getDevicePayload(entity, mappedModel);
// Set availability payload
// When using availability_timeout each device has it's own availability topic.
@@ -1428,6 +1784,14 @@ class HomeAssistant extends BaseExtension {
payload.temperature_state_topic = stateTopic;
}
if (payload.temperature_low_state_topic) {
payload.temperature_low_state_topic = stateTopic;
}
if (payload.temperature_high_state_topic) {
payload.temperature_high_state_topic = stateTopic;
}
if (payload.speed_state_topic) {
payload.speed_state_topic = stateTopic;
}
@@ -1436,6 +1800,22 @@ class HomeAssistant extends BaseExtension {
payload.temperature_command_topic = `${stateTopic}/set/${payload.temperature_command_topic}`;
}
if (payload.temperature_low_command_topic) {
payload.temperature_low_command_topic = `${stateTopic}/set/${payload.temperature_low_command_topic}`;
}
if (payload.temperature_high_command_topic) {
payload.temperature_high_command_topic = `${stateTopic}/set/${payload.temperature_high_command_topic}`;
}
if (payload.fan_mode_state_topic) {
payload.fan_mode_state_topic = stateTopic;
}
if (payload.fan_mode_command_topic) {
payload.fan_mode_command_topic = `${stateTopic}/set/fan_mode`;
}
if (payload.speed_command_topic) {
payload.speed_command_topic = `${stateTopic}/set/fan_mode`;
}
@@ -1488,17 +1868,27 @@ class HomeAssistant extends BaseExtension {
}
clearTimeout(timer);
}, 20000);
}, 30000);
}
}
onZigbeeEvent(type, data, mappedDevice, settingsDevice) {
onZigbeeEvent(type, data, resolvedEntity) {
const device = data.device;
if (device && mappedDevice) {
this.discover(device, mappedDevice);
if (device && resolvedEntity && resolvedEntity.definition) {
this.discover(device, resolvedEntity.definition);
}
}
getDevicePayload(entity, mappedModel) {
return {
identifiers: [`zigbee2mqtt_${entity.ID}`],
name: entity.friendlyName,
sw_version: `Zigbee2mqtt ${zigbee2mqttVersion}`,
model: `${mappedModel.description} (${mappedModel.model})`,
manufacturer: mappedModel.vendor,
};
}
getDiscoveryTopic(config, device) {
return `${config.type}/${device.ieeeAddr}/${config.object_id}/config`;
}
+103 -29
View File
@@ -17,25 +17,42 @@ class OTAUpdate extends BaseExtension {
this.mqtt.subscribe(`${settings.get().mqtt.base_topic}/bridge/ota_update/update`);
}
async onZigbeeEvent(type, data, mappedDevice, settingsDevice) {
if (data.type !== 'commandQueryNextImageRequest' || !mappedDevice.hasOwnProperty('ota')) return;
async onZigbeeEvent(type, data, resolvedEntity) {
if (data.type !== 'commandQueryNextImageRequest' || !resolvedEntity || !resolvedEntity.definition) return;
// When a device does a next image request, it will usually do it a few times after each other
// with only 10 - 60 seconds inbetween. It doesn' make sense to check for a new update
// each time.
const check = this.lastChecked.hasOwnProperty(data.device.ieeeAddr) ?
(Date.now() - this.lastChecked[data.device.ieeeAddr]) > MINUTES_10 : true;
if (!check || this.inProgress.has(data.device.ieeeAddr)) return;
const supportsOTA = resolvedEntity.definition.hasOwnProperty('ota');
if (supportsOTA) {
// When a device does a next image request, it will usually do it a few times after each other
// with only 10 - 60 seconds inbetween. It doesn' make sense to check for a new update
// each time.
const check = this.lastChecked.hasOwnProperty(data.device.ieeeAddr) ?
(Date.now() - this.lastChecked[data.device.ieeeAddr]) > MINUTES_10 : true;
if (!check || this.inProgress.has(data.device.ieeeAddr)) return;
this.lastChecked[data.device.ieeeAddr] = Date.now();
const available = await mappedDevice.ota.isUpdateAvailable(data.device, logger, data.data);
this.publishEntityState(data.device.ieeeAddr, {update_available: available});
this.lastChecked[data.device.ieeeAddr] = Date.now();
const available = await resolvedEntity.definition.ota.isUpdateAvailable(data.device, logger, data.data);
this.publishEntityState(data.device.ieeeAddr, {update_available: available});
if (available) {
const message = `Update available for '${settingsDevice.friendly_name}'`;
logger.info(message);
this.mqtt.log('ota_update', message, {status: 'available', device: settingsDevice.friendly_name});
if (available) {
const message = `Update available for '${resolvedEntity.settings.friendly_name}'`;
logger.info(message);
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const meta = {status: 'available', device: resolvedEntity.settings.friendly_name};
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `ota_update`, message, meta}),
);
}
}
}
// Respond to the OTA request:
// - In case we don't support OTA: respond with NO_IMAGE_AVAILABLE (0x98) (so the client stops requesting OTAs)
// - In case we do support OTA: respond with ABORT (0x95) as we don't want to update now.
const endpoint = data.device.endpoints.find((e) => e.supportsOutputCluster('genOta'));
await endpoint.commandResponse('genOta', 'queryNextImageResponse', {status: supportsOTA ? 0x95 : 0x98});
}
async readSoftwareBuildIDAndDateCode(device, update) {
@@ -62,10 +79,19 @@ class OTAUpdate extends BaseExtension {
const device = this.zigbee.resolveEntity(message);
assert(device != null && device.type === 'device', 'Device not found or not a device');
if (!device.mapped || !device.mapped.ota) {
if (!device.definition || !device.definition.ota) {
const message = `Device '${device.name}' does not support OTA updates`;
logger.error(message);
this.mqtt.log('ota_update', message, {status: `not_supported`, device: device.name});
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const meta = {status: `not_supported`, device: device.name};
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `ota_update`, message, meta}),
);
}
return;
}
@@ -75,29 +101,63 @@ class OTAUpdate extends BaseExtension {
}
this.inProgress.add(device.device.ieeeAddr);
const type = topic.split('/')[3];
const type = topic.substring(settings.get().mqtt.base_topic.length).split('/')[3];
if (type === 'check') {
const message = `Checking if update available for '${device.name}'`;
logger.info(message);
this.mqtt.log('ota_update', message, {status: `checking_if_available`, device: device.name});
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const meta = {status: `checking_if_available`, device: device.name};
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `ota_update`, message, meta}),
);
}
try {
const available = await device.mapped.ota.isUpdateAvailable(device.device, logger);
const available = await device.definition.ota.isUpdateAvailable(device.device, logger);
const message=(available ?
`Update available for '${device.name}'` : `No update available for '${device.name}'`);
logger.info(message);
const meta = {status: available ? 'available' : 'not_available', device: device.name};
this.mqtt.log('ota_update', message, meta);
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const meta = {status: available ? 'available' : 'not_available', device: device.name};
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `ota_update`, message, meta}),
);
}
this.publishEntityState(device.device.ieeeAddr, {update_available: available});
this.lastChecked[device.device.ieeeAddr] = Date.now();
} catch (error) {
const message = `Failed to check if update available for '${device.name}' (${error.message})`;
logger.error(message);
this.mqtt.log('ota_update', message, {status: `check_failed`, device: device.name});
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const meta = {status: `check_failed`, device: device.name};
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `ota_update`, message, meta}),
);
}
}
} else { // type === 'update'
const message = `Updating '${device.name}' to latest firmware`;
logger.info(message);
this.mqtt.log('ota_update', message, {status: `update_in_progress`, device: device.name});
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const meta = {status: `update_in_progress`, device: device.name};
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `ota_update`, message, meta}),
);
}
try {
const onProgress = (progress, remaining) => {
let message = `Update of '${device.name}' at ${progress}%`;
@@ -106,22 +166,36 @@ class OTAUpdate extends BaseExtension {
}
logger.info(message);
this.mqtt.log('ota_update', message, {status: `update_progress`, device: device.name, progress});
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const meta = {status: `update_progress`, device: device.name, progress};
this.mqtt.publish('bridge/log', JSON.stringify({type: `ota_update`, message, meta}));
}
};
const from_ = await this.readSoftwareBuildIDAndDateCode(device.device, false);
await device.mapped.ota.updateToLatest(device.device, logger, onProgress);
await device.definition.ota.updateToLatest(device.device, logger, onProgress);
const to = await this.readSoftwareBuildIDAndDateCode(device.device, true);
const [fromS, toS] = [JSON.stringify(from_), JSON.stringify(to)];
const message = `Finished update of '${device.name}'` + (to ? `, from '${fromS}' to '${toS}'` : ``);
logger.info(message);
const meta = {status: `update_succeeded`, device: device.name, from: from_, to};
this.mqtt.log('ota_update', message, meta);
this.publishEntityState(device.device.ieeeAddr, {update_available: false});
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const meta = {status: `update_succeeded`, device: device.name, from: from_, to};
this.mqtt.publish('bridge/log', JSON.stringify({type: `ota_update`, message, meta}));
}
} catch (error) {
const message = `Update of '${device.name}' failed (${error.message})`;
logger.error(message);
this.mqtt.log('ota_update', message, {status: `update_failed`, device: device.name});
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const meta = {status: `update_failed`, device: device.name};
this.mqtt.publish('bridge/log', JSON.stringify({type: `ota_update`, message, meta}));
}
}
}
+4 -10
View File
@@ -22,6 +22,10 @@ class MQTT extends events.EventEmitter {
},
};
if (mqttSettings.version) {
options.protocolVersion = mqttSettings.version;
}
if (mqttSettings.keepalive) {
logger.debug(`Using MQTT keepalive: ${mqttSettings.keepalive}`);
options.keepalive = mqttSettings.keepalive;
@@ -107,16 +111,6 @@ class MQTT extends events.EventEmitter {
this.client.publish(topic, payload, options, () => resolve());
});
}
log(type, message, meta=null) {
const payload = {type, message};
if (meta) {
payload.meta = meta;
}
this.publish('bridge/log', JSON.stringify(payload), {retain: false});
}
}
module.exports = MQTT;
+10 -11
View File
@@ -2,23 +2,21 @@ const logger = require('./util/logger');
const data = require('./util/data');
const fs = require('fs');
const objectAssignDeep = require('object-assign-deep');
const events = require('events');
const saveInterval = 1000 * 60 * 5; // 5 minutes
const dontCacheProperties = [
'action', 'button', 'button_left', 'button_right', 'click', 'forgotten', 'keyerror',
'step_size', 'transition_time', 'action_color_temperature', 'action_color',
'action_group', 'group_list', 'group_capacity', 'no_occupancy_since',
'action', 'action_.*', 'button', 'button_left', 'button_right', 'click', 'forgotten', 'keyerror',
'step_size', 'transition_time', 'group_list', 'group_capacity', 'no_occupancy_since',
'step_mode', 'transition_time', 'duration', 'elapsed', 'from_side', 'to_side',
];
class State extends events.EventEmitter {
constructor() {
super();
class State {
constructor(eventBus) {
this.state = {};
this.file = data.joinPath('state.json');
this.timer = null;
this.eventBus = eventBus;
}
start() {
@@ -70,17 +68,18 @@ class State extends events.EventEmitter {
set(ID, state, reason=null) {
const toState = objectAssignDeep.noMutate(state);
dontCacheProperties.forEach((property) => {
if (toState.hasOwnProperty(property)) {
for (const property of Object.keys(toState)) {
if (dontCacheProperties.find((p) => property.match(p))) {
delete toState[property];
}
});
}
const fromState = this.state[ID];
this.state[ID] = toState;
this.emit('stateChange', {ID, from: fromState, to: toState, reason});
this.eventBus.emit('stateChange', {ID, from: fromState, to: toState, reason});
}
remove(ID) {
+20 -15
View File
@@ -54,22 +54,27 @@ const transportsToUse = [
// Add file logger when enabled
// NOTE: the initiation of the logger, even when not added as transport tries to create the logging directory
const transportFileOptions = {
filename: path.join(directory, logFilename),
json: false,
level,
format: winston.format.combine(
winston.format.timestamp({format: timestampFormat}),
winston.format.printf(/* istanbul ignore next */(info) => {
const {timestamp, level, message} = info;
return `${levelWithCompensatedLength[level]} ${timestamp.split('.')[0]}: ${message}`;
}),
),
};
if (settings.get().advanced.log_rotation) {
transportFileOptions.tailable = true;
transportFileOptions.maxFiles = 3; // Keep last 3 files
transportFileOptions.maxsize = 10000000; // 10MB
}
if (output.includes('file')) {
transportsToUse.push(new winston.transports.File({
filename: path.join(directory, logFilename),
json: false,
level,
tailable: true,
maxFiles: 3, // Keep last 3 files
maxsize: 10000000, // 10MB
format: winston.format.combine(
winston.format.timestamp({format: timestampFormat}),
winston.format.printf(/* istanbul ignore next */(info) => {
const {timestamp, level, message} = info;
return `${levelWithCompensatedLength[level]} ${timestamp.split('.')[0]}: ${message}`;
}),
),
}));
transportsToUse.push(new winston.transports.File(transportFileOptions));
}
// Create logger
+51 -11
View File
@@ -43,6 +43,8 @@ const defaults = {
output: 'json',
},
advanced: {
legacy_api: true,
log_rotation: true,
log_output: ['console', 'file'],
log_directory: path.join(data.getPath(), 'log', '%TIMESTAMP%'),
log_file: 'log.txt',
@@ -53,6 +55,7 @@ const defaults = {
channel: 11,
baudrate: 115200,
rtscts: true,
adapter_concurrent: null,
// Availability timeout in seconds, disabled by default.
availability_timeout: 0,
@@ -104,6 +107,13 @@ const defaults = {
*/
homeassistant_status_topic: 'hass/status',
/**
* Home Assistant legacy triggers, when enabled:
* - Zigbee2mqt will send an empty 'action' or 'click' after one has been send
* - A 'sensor_action' and 'sensor_click' will be discoverd
*/
homeassistant_legacy_triggers: true,
/**
* Configurable timestampFormat
* https://github.com/Koenkk/zigbee2mqtt/commit/44db557a0c83f419d66755d14e460cd78bd6204e
@@ -115,6 +125,7 @@ const defaults = {
const schema = {
type: 'object',
properties: {
device_options: {type: 'object'},
homeassistant: {type: 'boolean'},
permit_join: {type: 'boolean'},
mqtt: {
@@ -131,6 +142,7 @@ const schema = {
client_id: {type: 'string'},
reject_unauthorized: {type: 'boolean'},
include_device_information: {type: 'boolean'},
version: {type: 'number'},
},
required: ['base_topic', 'server'],
},
@@ -139,6 +151,7 @@ const schema = {
properties: {
port: {type: ['string', 'null']},
disable_led: {type: 'boolean'},
adapter: {type: 'string', enum: ['deconz', 'zstack']},
},
},
ban: {type: 'array', items: {type: 'string'}},
@@ -152,10 +165,12 @@ const schema = {
advanced: {
type: 'object',
properties: {
legacy_api: {type: 'boolean'},
pan_id: {type: 'number'},
ext_pan_id: {type: 'array', items: {type: 'number'}},
channel: {type: 'number', minimum: 11, maximum: 26},
cache_state: {type: 'boolean'},
log_rotation: {type: 'boolean'},
log_level: {type: 'string', enum: ['info', 'warn', 'error', 'debug']},
log_output: {type: 'array', items: {type: 'string'}},
log_directory: {type: 'string'},
@@ -173,6 +188,7 @@ const schema = {
homeassistant_discovery_topic: {type: 'string'},
homeassistant_status_topic: {type: 'string'},
timestamp_format: {type: 'string'},
adapter_concurrent: {type: 'number'},
},
},
map_options: {
@@ -224,7 +240,9 @@ const schema = {
properties: {
friendly_name: {type: 'string'},
retain: {type: 'boolean'},
retention: {type: 'number'},
qos: {type: 'number'},
filtered_attributes: {type: 'array', items: {type: 'string'}},
},
required: ['friendly_name'],
},
@@ -244,6 +262,7 @@ const schema = {
devices: {type: 'array', items: {type: 'string'}},
optimistic: {type: 'boolean'},
qos: {type: 'number'},
filtered_attributes: {type: 'array', items: {type: 'string'}},
},
required: ['friendly_name'],
},
@@ -291,17 +310,42 @@ function write() {
function validate() {
const validate = ajv.compile(schema);
const valid = validate(_settings);
const postfixes = utils.getPostfixes();
const postfixes = utils.getEndpointNames();
// Verify that all friendly names are unique
const names = [];
const check = (name) => {
if (names.includes(name)) throw new Error(`Duplicate friendly_name '${name}' found`);
if (postfixes.includes(name)) throw new Error(`Following friendly_name are not allowed: '${postfixes}'`);
if (name.match(/.*\/\d*$/)) throw new Error(`Friendly name cannot end with a "/DIGIT" ('${name}')`);
if (name.includes('#') || name.includes('+')) {
throw new Error(`MQTT wildcard (+ and #) not allowed in friendly_name ('${name}')`);
}
names.push(name);
};
Object.values(_settingsWithDefaults.devices).forEach((d) => check(d.friendly_name));
Object.values(_settingsWithDefaults.groups).forEach((g) => check(g.friendly_name));
const settingsWithDefaults = getWithDefaults();
Object.values(settingsWithDefaults.devices).forEach((d) => check(d.friendly_name));
Object.values(settingsWithDefaults.groups).forEach((g) => check(g.friendly_name));
if (settingsWithDefaults.mqtt.version !== 5) {
for (const device of Object.values(settingsWithDefaults.devices)) {
if (device.retention) {
throw new Error('MQTT retention requires protocol version 5');
}
}
}
const checkAvailabilityList = (list, type) => {
list.forEach((e) => {
if (!getEntity(e)) {
throw new Error(`Non-existing entity '${e}' specified in '${type}'`);
}
});
};
checkAvailabilityList(settingsWithDefaults.advanced.availability_blacklist, 'availability_blacklist');
checkAvailabilityList(settingsWithDefaults.advanced.availability_whitelist, 'availability_whitelist');
return !valid ? validate.errors.map((v) => `${v.dataPath.substring(1)} ${v.message}`) : null;
}
@@ -566,6 +610,9 @@ function removeDeviceFromGroup(groupIDorName, keys) {
const groupID = getGroupThrowIfNotExists(groupIDorName).ID;
const settings = get();
const group = settings.groups[groupID];
if (!group.devices) {
group.devices = [];
}
const key = groupHasDevice(group, keys);
if (key) {
@@ -584,14 +631,7 @@ function removeGroup(groupIDorName) {
function changeDeviceOptions(IDorName, newOptions) {
const device = getDeviceThrowIfNotExists(IDorName);
const settings = get();
const currentOptions = settings.devices[device.ID];
Object.keys(currentOptions).forEach((key) => {
if (newOptions[key]) {
currentOptions[key] = newOptions[key];
}
});
objectAssignDeep(settings.devices[device.ID], newOptions);
write();
}
+15 -3
View File
@@ -27,10 +27,11 @@ function toLocalISOString(dDate) {
':' + pad(tzOffset % 60);
}
const postfixes = [
'left', 'right', 'center', 'bottom_left', 'bottom_right', 'l1', 'l2', 'l3', 'l4', 'default',
const endpointNames = [
'left', 'right', 'center', 'bottom_left', 'bottom_right', 'default',
'top_left', 'top_right', 'white', 'rgb', 'system', 'top', 'bottom', 'center_left', 'center_right',
'ep1', 'ep2', 'row_1', 'row_2', 'row_3', 'row_4', 'relay',
'l1', 'l2', 'l3', 'l4', 'l5', 'l6', 'l7', 'l8',
];
function flatten(arr) {
@@ -108,12 +109,23 @@ function equalsPartial(object, expected) {
return true;
}
function getObjectsProperty(objects, key, defaultValue) {
for (const object of objects) {
if (object.hasOwnProperty(key)) {
return object[key];
}
}
return defaultValue;
}
module.exports = {
millisecondsToSeconds: (milliseconds) => milliseconds / 1000,
secondsToMilliseconds: (seconds) => seconds * 1000,
getZigbee2mqttVersion,
objectHasProperties,
getPostfixes: () => postfixes,
getObjectsProperty,
getEndpointNames: () => endpointNames,
isXiaomiDevice: (device) => {
return device.modelID !== 'lumi.router' && xiaomiManufacturerID.includes(device.manufacturerID) &&
(!device.manufacturerName || !device.manufacturerName.startsWith('Trust'));
+34 -22
View File
@@ -8,7 +8,7 @@ const events = require('events');
const objectAssignDeep = require('object-assign-deep');
const zigbeeHerdsmanConverters = require('zigbee-herdsman-converters');
const postfixes = utils.getPostfixes();
const endpointNames = utils.getEndpointNames();
const keyEndpointByNumber = new RegExp(`.*/([0-9]*)$`);
const herdsmanSettings = {
@@ -25,6 +25,10 @@ const herdsmanSettings = {
baudRate: settings.get().advanced.baudrate,
rtscts: settings.get().advanced.rtscts,
path: settings.get().serial.port,
adapter: settings.get().serial.adapter,
},
adapter: {
concurrent: settings.get().advanced.adapter_concurrent,
},
};
@@ -127,6 +131,17 @@ class Zigbee extends events.EventEmitter {
return this.herdsman.getDevicesByType(type);
}
/**
* @param {string} key
* @return {object} {
* type: device | coordinator
* device|group: zigbee-herdsman entity
* endpoint: selected endpoint (only if type === device)
* settings: from configuration.yaml
* name: name of the entity
* definition: zigbee-herdsman-converters definition (only if type === device)
* }
*/
resolveEntity(key) {
assert(
typeof key === 'string' || typeof key === 'number' ||
@@ -149,13 +164,13 @@ class Zigbee extends events.EventEmitter {
};
}
let postfix = postfixes.find((p) => key.endsWith(`/${p}`));
const postfixByNumber = key.match(keyEndpointByNumber);
if (!postfix && postfixByNumber) {
postfix = Number(postfixByNumber[1]);
let endpointKey = endpointNames.find((p) => key.endsWith(`/${p}`));
const endpointByNumber = key.match(keyEndpointByNumber);
if (!endpointKey && endpointByNumber) {
endpointKey = Number(endpointByNumber[1]);
}
if (postfix) {
key = key.replace(`/${postfix}`, '');
if (endpointKey) {
key = key.replace(`/${endpointKey}`, '');
}
const entity = settings.getEntity(key);
@@ -167,19 +182,17 @@ class Zigbee extends events.EventEmitter {
return null;
}
const mapped = zigbeeHerdsmanConverters.findByZigbeeModel(device.modelID);
const endpoints = mapped && mapped.endpoint ? mapped.endpoint(device) : null;
let isDefaultEndpoint = true;
const definition = zigbeeHerdsmanConverters.findByZigbeeModel(device.modelID);
const endpoints = definition && definition.endpoint ? definition.endpoint(device) : null;
let endpoint;
if (postfix) {
isDefaultEndpoint = false;
if (postfixByNumber) {
endpoint = device.getEndpoint(postfix);
if (endpointKey) {
if (endpointByNumber) {
endpoint = device.getEndpoint(endpointKey);
} else {
assert(mapped != null, `Postfix '${postfix}' is given but device is unsupported`);
assert(endpoints != null, `Postfix '${postfix}' is given but device defines no endpoints`);
const endpointID = endpoints[postfix];
assert(endpointID, `Postfix '${postfix}' is given but device has no such endpoint`);
assert(definition != null, `Endpoint name '${endpointKey}' is given but device is unsupported`);
assert(endpoints != null, `Endpoint name '${endpointKey}' is given but no endpoints defined`);
const endpointID = endpoints[endpointKey];
assert(endpointID, `Endpoint name '${endpointKey}' is given but device has no such endpoint`);
endpoint = device.getEndpoint(endpointID);
}
} else if (endpoints && endpoints['default']) {
@@ -188,10 +201,8 @@ class Zigbee extends events.EventEmitter {
endpoint = device.endpoints[0];
}
const endpointName = endpoints ? Object.entries(endpoints).find((e) => e[1] === endpoint.ID)[0] : null;
return {
type: 'device', device, settings: entity, mapped, endpoint, name: entity.friendlyName,
isDefaultEndpoint, endpointName,
type: 'device', device, endpoint, settings: entity, name: entity.friendlyName, definition,
};
} else {
let group = this.getGroupByID(entity.ID);
@@ -203,9 +214,10 @@ class Zigbee extends events.EventEmitter {
return {
type: 'device',
device: key,
endpoint: key.endpoints[0],
settings: setting,
mapped: zigbeeHerdsmanConverters.findByZigbeeModel(key.modelID),
name: setting ? setting.friendlyName : (key.type === 'Coordinator' ? 'Coordinator' : key.ieeeAddr),
definition: zigbeeHerdsmanConverters.findByZigbeeModel(key.modelID),
};
}
}
+1819 -1656
View File
File diff suppressed because it is too large Load Diff
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "zigbee2mqtt",
"version": "1.11.0",
"version": "1.12.1",
"description": "Zigbee to MQTT bridge using Zigbee-herdsman",
"main": "index.js",
"repository": {
@@ -45,8 +45,8 @@
"rimraf": "*",
"semver": "*",
"winston": "*",
"zigbee-herdsman": "0.12.55",
"zigbee-herdsman-converters": "12.0.32"
"zigbee-herdsman": "0.12.76",
"zigbee-herdsman-converters": "12.0.69"
},
"devDependencies": {
"eslint": "*",
@@ -9,7 +9,7 @@ const Controller = require('../lib/controller');
const flushPromises = () => new Promise(setImmediate);
describe('Bridge config', () => {
describe('Bridge legacy', () => {
let controller;
beforeAll(async () => {
@@ -100,6 +100,21 @@ describe('Bridge config', () => {
expect(settings.getDevice('bulb_color')).toStrictEqual(
{"ID": "0x000b57fffec6a5b3", "friendlyName": "bulb_color", "friendly_name": "bulb_color", "retain": true}
);
MQTT.events.message('zigbee2mqtt/bridge/config/device_options', JSON.stringify({friendly_name: 'bulb_color', options: {random_setting: true}}));
await flushPromises();
expect(settings.getDevice('bulb_color')).toStrictEqual(
{"ID": "0x000b57fffec6a5b3", "friendlyName": "bulb_color", "friendly_name": "bulb_color", "random_setting": true, "retain": true}
);
MQTT.events.message('zigbee2mqtt/bridge/config/device_options', JSON.stringify({friendly_name: 'bulb_color', options: {options: {random_1: true}}}));
await flushPromises();
expect(settings.getDevice('bulb_color')).toStrictEqual(
{"ID": "0x000b57fffec6a5b3", "friendlyName": "bulb_color", "friendly_name": "bulb_color", "random_setting": true, "retain": true, options: {random_1: true}}
);
MQTT.events.message('zigbee2mqtt/bridge/config/device_options', JSON.stringify({friendly_name: 'bulb_color', options: {options: {random_2: false}}}));
await flushPromises();
expect(settings.getDevice('bulb_color')).toStrictEqual(
{"ID": "0x000b57fffec6a5b3", "friendlyName": "bulb_color", "friendly_name": "bulb_color", "random_setting": true, "retain": true, options: {random_1: true, random_2: false}}
);
});
it('Should allow permit join', async () => {
@@ -161,8 +176,8 @@ describe('Bridge config', () => {
expect(MQTT.publish.mock.calls[0][0]).toStrictEqual('zigbee2mqtt/bridge/config/devices');
const payload = JSON.parse(MQTT.publish.mock.calls[0][1]);
expect(payload.length).toStrictEqual(Object.values(zigbeeHerdsman.devices).length);
expect(payload[0]).toStrictEqual({"ieeeAddr": "0x00124b00120144ae", "type": "Coordinator", "dateCode": "20190425", "friendly_name": "Coordinator", networkAddress: 0, softwareBuildID: "z-Stack", lastSeen: 100});
expect(payload[1]).toStrictEqual({"dateCode": null, "friendly_name": "bulb", "ieeeAddr": "0x000b57fffec6a5b2", "lastSeen": 1000, "manufacturerID": 4476, "model": "LED1545G12", "modelID": "TRADFRI bulb E27 WS opal 980lm", "networkAddress": 40369, "powerSource": "Mains (single phase)", "type": "Router"});
expect(payload[1]).toStrictEqual({"ieeeAddr": "0x00124b00120144ae", "type": "Coordinator", "dateCode": "20190425", "friendly_name": "Coordinator", networkAddress: 0, softwareBuildID: "z-Stack", lastSeen: 100});
expect(payload[2]).toStrictEqual({"dateCode": null, "friendly_name": "bulb", "ieeeAddr": "0x000b57fffec6a5b2", "lastSeen": 1000, "manufacturerID": 4476, "model": "LED1545G12", "modelID": "TRADFRI bulb E27 WS opal 980lm", "networkAddress": 40369, "powerSource": "Mains (single phase)", "type": "Router", "description": "TRADFRI LED bulb E26/E27 980 lumen, dimmable, white spectrum, opal white", "vendor": "IKEA"});
Date.now = now;
});
@@ -248,9 +263,15 @@ describe('Bridge config', () => {
zigbeeHerdsman.createGroup.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/config/add_group', 'new_group');
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/log',
JSON.stringify({type: 'group_added', message: 'new_group'}),
{qos: 0, retain: false},
expect.any(Function)
);
expect(settings.getGroup('new_group')).toStrictEqual({"ID": 3, "friendlyName": "new_group", "friendly_name": "new_group", devices: [], optimistic: true});
expect(zigbeeHerdsman.createGroup).toHaveBeenCalledTimes(1);
expect(zigbeeHerdsman.createGroup).toHaveBeenCalledWith(3)
expect(zigbeeHerdsman.createGroup).toHaveBeenCalledWith(3);
});
it('Should allow to add groups with json', async () => {
@@ -259,7 +280,13 @@ describe('Bridge config', () => {
await flushPromises();
expect(settings.getGroup('new_group')).toStrictEqual({"ID": 3, "friendlyName": "new_group", "friendly_name": "new_group", devices: [], optimistic: true});
expect(zigbeeHerdsman.createGroup).toHaveBeenCalledTimes(1);
expect(zigbeeHerdsman.createGroup).toHaveBeenCalledWith(3)
expect(zigbeeHerdsman.createGroup).toHaveBeenCalledWith(3);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/log',
JSON.stringify({type: 'group_added', message: 'new_group'}),
{qos: 0, retain: false},
expect.any(Function)
);
});
it('Should allow to add groups with json specifying id', async () => {
@@ -268,7 +295,13 @@ describe('Bridge config', () => {
await flushPromises();
expect(settings.getGroup('new_group')).toStrictEqual({"ID": 42, "friendlyName": "new_group", "friendly_name": "new_group", devices: [], optimistic: true});
expect(zigbeeHerdsman.createGroup).toHaveBeenCalledTimes(1);
expect(zigbeeHerdsman.createGroup).toHaveBeenCalledWith(42)
expect(zigbeeHerdsman.createGroup).toHaveBeenCalledWith(42);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/log',
JSON.stringify({type: 'group_added', message: 'new_group'}),
{qos: 0, retain: false},
expect.any(Function)
);
});
it('Should allow to add groups with json specifying only id', async () => {
@@ -286,6 +319,12 @@ describe('Bridge config', () => {
await flushPromises();
expect(settings.getGroup('to_be_removed')).toStrictEqual(null);
expect(group.removeFromDatabase).toHaveBeenCalledTimes(1);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/log',
JSON.stringify({type: 'group_removed', message: 'group_1'}),
{qos: 0, retain: false},
expect.any(Function)
);
});
it('Shouldnt allow add groups without id or friendly_name in json', async () => {
+67 -1
View File
@@ -30,7 +30,7 @@ describe('Controller', () => {
it('Start controller', async () => {
await controller.start();
expect(zigbeeHerdsman.constructor).toHaveBeenCalledWith({"network":{"panID":6754,"extendedPanID":[221,221,221,221,221,221,221,221],"channelList":[11],"networkKey":[1,3,5,7,9,11,13,15,0,2,4,6,8,10,12,13]},"databasePath":path.join(data.mockDir, "database.db"), "databaseBackupPath":path.join(data.mockDir, "database.db.backup"),"backupPath":path.join(data.mockDir, "coordinator_backup.json"),"acceptJoiningDeviceHandler": expect.any(Function),"serialPort":{"baudRate":115200,"rtscts":true,"path":"/dev/dummy"}});
expect(zigbeeHerdsman.constructor).toHaveBeenCalledWith({"network":{"panID":6754,"extendedPanID":[221,221,221,221,221,221,221,221],"channelList":[11],"networkKey":[1,3,5,7,9,11,13,15,0,2,4,6,8,10,12,13]},"databasePath":path.join(data.mockDir, "database.db"), "databaseBackupPath":path.join(data.mockDir, "database.db.backup"),"backupPath":path.join(data.mockDir, "coordinator_backup.json"),"acceptJoiningDeviceHandler": expect.any(Function),adapter: {concurrent: null}, "serialPort":{"baudRate":115200,"rtscts":true,"path":"/dev/dummy"}});
expect(zigbeeHerdsman.start).toHaveBeenCalledTimes(1);
expect(zigbeeHerdsman.setLED).toHaveBeenCalledTimes(0);
expect(zigbeeHerdsman.setTransmitPower).toHaveBeenCalledTimes(0);
@@ -63,6 +63,7 @@ describe('Controller', () => {
user: 'user1',
client_id: 'my_client_id',
reject_unauthorized: false,
version: 5,
}
settings.set(['mqtt'], configuration)
await controller.start();
@@ -78,6 +79,7 @@ describe('Controller', () => {
username: 'user1',
clientId: 'my_client_id',
rejectUnauthorized: false,
protocolVersion: 5,
}
expect(MQTT.connect).toHaveBeenCalledWith("mqtt://localhost", expected);
@@ -240,9 +242,16 @@ describe('Controller', () => {
expect(logger.debug).toHaveBeenCalledWith(`Received Zigbee message from 'bulb', type 'attributeReport', cluster 'genBasic', data '{"modelId":"TRADFRI bulb E27 WS opal 980lm"}' from endpoint 1 with groupID 0`);
});
it('Should add entities which are missing from configuration but are in database to configuration', async () => {
await controller.start();
const device = zigbeeHerdsman.devices.notInSettings;
expect(settings.getDevice(device.ieeeAddr)).not.toBeNull();
});
it('On zigbee event message from unkown device should create it', async () => {
await controller.start();
const device = zigbeeHerdsman.devices.notInSettings;
settings.removeDevice(device.ieeeAddr);
expect(settings.getDevice(device.ieeeAddr)).toBeNull();
const payload = {device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10, groupID: 0, cluster: 'genBasic', data: {modelId: device.modelID}};
await zigbeeHerdsman.events.message(payload);
@@ -360,6 +369,7 @@ describe('Controller', () => {
await zigbeeHerdsman.events.deviceAnnounce(payload);
await flushPromises();
expect(logger.debug).toHaveBeenCalledWith(`Device 'bulb' announced itself`);
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bridge/log', '{"type":"device_announced","message":"announce","meta":{"friendly_name":"bulb"}}', { retain: false, qos: 0}, expect.any(Function));
});
it('On zigbee event device leave (removed from database and settings)', async () => {
@@ -413,6 +423,33 @@ describe('Controller', () => {
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bulb", '{"state":"ON","brightness":200,"color_temp":370,"linkquality":99}', {"qos": 0, "retain": true}, expect.any(Function));
});
it('Publish entity state attribute_json output filtered', async () => {
await controller.start();
settings.set(['experimental', 'output'], 'attribute_and_json');
settings.set(['devices', zigbeeHerdsman.devices.bulb.ieeeAddr, 'filtered_attributes'], ['color_temp', 'linkquality']);
MQTT.publish.mockClear();
await controller.publishEntityState('bulb', {state: 'ON', brightness: 200, color_temp: 370, linkquality: 99});
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(3);
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bulb/state", "ON", {"qos": 0, "retain": true}, expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bulb/brightness", "200", {"qos": 0, "retain": true}, expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bulb", '{"state":"ON","brightness":200}', {"qos": 0, "retain": true}, expect.any(Function));
});
it('Publish entity state attribute_json output filtered (device_options)', async () => {
await controller.start();
settings.set(['experimental', 'output'], 'attribute_and_json');
settings.set(['device_options', 'filtered_attributes'], ['color_temp', 'linkquality']);
MQTT.publish.mockClear();
await controller.publishEntityState('bulb', {state: 'ON', brightness: 200, color_temp: 370, linkquality: 99});
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(3);
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bulb/state", "ON", {"qos": 0, "retain": true}, expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bulb/brightness", "200", {"qos": 0, "retain": true}, expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bulb", '{"state":"ON","brightness":200}', {"qos": 0, "retain": true}, expect.any(Function));
});
it('Publish entity state with device information', async () => {
await controller.start();
settings.set(['mqtt', 'include_device_information'], true);
@@ -427,6 +464,35 @@ describe('Controller', () => {
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/unsupported2', '{"state":"ON","device":{"friendlyName":"unsupported2","model":"unknown","ieeeAddr":"0x0017880104e45529","networkAddress":6536,"type":"EndDevice","manufacturerID":0,"powerSource":"Battery","dateCode":null}}', {"qos": 0, "retain": false}, expect.any(Function));
});
it('Should publish entity state without retain', async () => {
await controller.start();
settings.set(['devices', zigbeeHerdsman.devices.bulb.ieeeAddr, 'retain'], false);
MQTT.publish.mockClear();
await controller.publishEntityState('bulb', {state: 'ON'});
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bulb', '{"state":"ON","brightness":50,"color_temp":370,"linkquality":99}', {"qos": 0, "retain": false}, expect.any(Function));
});
it('Should publish entity state with retain', async () => {
await controller.start();
settings.set(['devices', zigbeeHerdsman.devices.bulb.ieeeAddr, 'retain'], true);
MQTT.publish.mockClear();
await controller.publishEntityState('bulb', {state: 'ON'});
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bulb', '{"state":"ON","brightness":50,"color_temp":370,"linkquality":99}', {"qos": 0, "retain": true}, expect.any(Function));
});
it('Should publish entity state with expiring retention', async () => {
await controller.start();
settings.set(['mqtt', 'version'], 5);
settings.set(['devices', zigbeeHerdsman.devices.bulb.ieeeAddr, 'retain'], true);
settings.set(['devices', zigbeeHerdsman.devices.bulb.ieeeAddr, 'retention'], 37);
MQTT.publish.mockClear();
await controller.publishEntityState('bulb', {state: 'ON'});
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bulb', '{"state":"ON","brightness":50,"color_temp":370,"linkquality":99}', {"qos": 0, "retain": true, "properties": {messageExpiryInterval: 37}}, expect.any(Function));
});
it('Publish entity state no empty messages', async () => {
data.writeEmptyState();
await controller.start();
-1
View File
@@ -280,7 +280,6 @@ describe('Device availability', () => {
expect(device.ping).toHaveBeenCalledTimes(0);
MQTT.publish.mockClear();
await zigbeeHerdsman.events.deviceAnnounce({device});
expect(MQTT.publish).toHaveBeenCalledTimes(0);
});
it('Should not read when device has no modelID and reconnects', async () => {
+13 -5
View File
@@ -30,11 +30,8 @@ describe('Device bind', () => {
MQTT.publish.mockClear();
});
it('Should subscribe to nested topics', async () => {
expect(MQTT.subscribe).toHaveBeenCalledWith('zigbee2mqtt/bridge/bind/+');
expect(MQTT.subscribe).toHaveBeenCalledWith('zigbee2mqtt/bridge/bind/+/+');
expect(MQTT.subscribe).toHaveBeenCalledWith('zigbee2mqtt/bridge/bind/+/+/+');
expect(MQTT.subscribe).toHaveBeenCalledWith('zigbee2mqtt/bridge/bind/+/+/+/+/+');
it('Should subscribe to topics', async () => {
expect(MQTT.subscribe).toHaveBeenCalledWith('zigbee2mqtt/bridge/bind/#');
});
it('Should bind', async () => {
@@ -57,6 +54,17 @@ describe('Device bind', () => {
expect(JSON.parse(MQTT.publish.mock.calls[2][1])).toStrictEqual({type: 'device_bind', message: {from: 'remote', to: 'bulb_color', cluster: 'genLevelCtrl'}});
});
it('Should log error when there is nothing to bind', async () => {
const device = zigbeeHerdsman.devices.bulb_color;
const endpoint = device.getEndpoint(1);
mockClear(device);
logger.error.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/bind/remote', 'button');
await flushPromises();
expect(endpoint.bind).toHaveBeenCalledTimes(0);
expect(logger.error).toHaveBeenCalledWith(`Nothing to bind from 'remote' to 'button'`);
});
it('Should unbind', async () => {
const device = zigbeeHerdsman.devices.remote;
const target = zigbeeHerdsman.devices.bulb_color.getEndpoint(1);
+26
View File
@@ -110,6 +110,32 @@ describe('Device receive', () => {
expect(MQTT.publish.mock.calls[0][2]).toStrictEqual({"qos": 1, "retain": false});
});
it('Should debounce and retain messages when set via device_options', async () => {
jest.useFakeTimers();
const device = zigbeeHerdsman.devices.WSDCGQ11LM;
settings.set(['device_options', 'debounce'], 0.1);
settings.set(['device_options', 'retain'], true);
delete settings.get().devices['0x0017880104e45522']['retain'];
const data1 = {measuredValue: 8}
const payload1 = {data: data1, cluster: 'msTemperatureMeasurement', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload1);
const data2 = {measuredValue: 1}
const payload2 = {data: data2, cluster: 'msRelativeHumidity', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload2);
const data3 = {measuredValue: 2}
const payload3 = {data: data3, cluster: 'msPressureMeasurement', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload3);
await flushPromises();
jest.advanceTimersByTime(50);
expect(MQTT.publish).toHaveBeenCalledTimes(0);
jest.runAllTimers();
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(1);
expect(MQTT.publish.mock.calls[0][0]).toStrictEqual('zigbee2mqtt/weather_sensor');
expect(JSON.parse(MQTT.publish.mock.calls[0][1])).toStrictEqual({temperature: 0.08, humidity: 0.01, pressure: 2, linkquality: 10});
expect(MQTT.publish.mock.calls[0][2]).toStrictEqual({"qos": 1, "retain": true});
});
it('Should debounce messages only with the same payload values for provided debounce_ignore keys', async () => {
jest.useFakeTimers();
const device = zigbeeHerdsman.devices.WSDCGQ11LM;
+36 -5
View File
@@ -22,7 +22,7 @@ const mocksClear = [MQTT.publish, logger.warn, logger.debug, debounce];
describe('Device report', () => {
let controller;
function expectOnOffBrightnessColorReport(endpoint) {
function expectOnOffBrightnessColorReport(endpoint, colorXY) {
const coordinatorEndpoint = zigbeeHerdsman.devices.coordinator.getEndpoint(1);
expect(endpoint.bind).toHaveBeenCalledTimes(3);
expect(endpoint.bind).toHaveBeenCalledWith('genOnOff', coordinatorEndpoint);
@@ -31,7 +31,11 @@ describe('Device report', () => {
expect(endpoint.configureReporting).toHaveBeenCalledTimes(3);
expect(endpoint.configureReporting).toHaveBeenCalledWith('genOnOff', [{"attribute": "onOff", "maximumReportInterval": 300, "minimumReportInterval": 0, "reportableChange": 0}]);
expect(endpoint.configureReporting).toHaveBeenCalledWith('genLevelCtrl', [{"attribute": "currentLevel", "maximumReportInterval": 300, "minimumReportInterval": 3, "reportableChange": 1}]);
expect(endpoint.configureReporting).toHaveBeenCalledWith('lightingColorCtrl', [{"attribute": "colorTemperature", "maximumReportInterval": 300, "minimumReportInterval": 3, "reportableChange": 1}, {"attribute": "currentX", "maximumReportInterval": 300, "minimumReportInterval": 3, "reportableChange": 1}, {"attribute": "currentY", "maximumReportInterval": 300, "minimumReportInterval": 3, "reportableChange": 1}]);
if (colorXY) {
expect(endpoint.configureReporting).toHaveBeenCalledWith('lightingColorCtrl', [{"attribute": "colorTemperature", "maximumReportInterval": 300, "minimumReportInterval": 3, "reportableChange": 1}, {"attribute": "currentX", "maximumReportInterval": 300, "minimumReportInterval": 3, "reportableChange": 1}, {"attribute": "currentY", "maximumReportInterval": 300, "minimumReportInterval": 3, "reportableChange": 1}]);
} else {
expect(endpoint.configureReporting).toHaveBeenCalledWith('lightingColorCtrl', [{"attribute": "colorTemperature", "maximumReportInterval": 300, "minimumReportInterval": 3, "reportableChange": 1}]);
}
}
mockClear = (device) => {
@@ -57,7 +61,7 @@ describe('Device report', () => {
it('Should configure reporting on startup', async () => {
const device = zigbeeHerdsman.devices.bulb_color;
const endpoint = device.getEndpoint(1);
expectOnOffBrightnessColorReport(endpoint);
expectOnOffBrightnessColorReport(endpoint, true);
});
it('Should configure reporting when receicing message from device which has not been setup yet', async () => {
@@ -70,7 +74,7 @@ describe('Device report', () => {
const payload = {data, cluster: 'genOnOff', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expectOnOffBrightnessColorReport(endpoint);
expectOnOffBrightnessColorReport(endpoint, false);
expect(device.save).toHaveBeenCalledTimes(1);
});
@@ -130,7 +134,7 @@ describe('Device report', () => {
const payload = {device};
await zigbeeHerdsman.events.deviceAnnounce(payload);
await flushPromises();
expectOnOffBrightnessColorReport(endpoint);
expectOnOffBrightnessColorReport(endpoint, false);
});
it('Should not configure reporting on device leave', async () => {
@@ -211,4 +215,31 @@ describe('Device report', () => {
expect(endpoint.bind).toHaveBeenCalledWith('lightingColorCtrl', coordinatorEndpoint);
expect(endpoint.configureReporting).toHaveBeenCalledTimes(3);
});
it('Should not setup colorTemperature reporting when bulb does not support it and should read colorCapabilities when its not there yet ', async () => {
const device = zigbeeHerdsman.devices.bulb;
const coordinatorEndpoint = zigbeeHerdsman.devices.coordinator.getEndpoint(1);
const endpoint = device.getEndpoint(1);
delete device.meta.reporting;
mockClear(device);
endpoint.getClusterAttributeValue = jest.fn();
let count = 0;
endpoint.getClusterAttributeValue.mockImplementation((d) => {
count++;
if (count === 1) return undefined;
return 17;
});
const payload = {device};
await zigbeeHerdsman.events.deviceAnnounce(payload);
await flushPromises();
expect(endpoint.bind).toHaveBeenCalledTimes(3);
expect(endpoint.bind).toHaveBeenCalledWith('genOnOff', coordinatorEndpoint);
expect(endpoint.bind).toHaveBeenCalledWith('genLevelCtrl', coordinatorEndpoint);
expect(endpoint.bind).toHaveBeenCalledWith('lightingColorCtrl', coordinatorEndpoint);
expect(endpoint.read).toHaveBeenCalledWith('lightingColorCtrl', ['colorCapabilities'])
expect(endpoint.configureReporting).toHaveBeenCalledWith('lightingColorCtrl', [{"attribute": "colorTemperature", "maximumReportInterval": 300, "minimumReportInterval": 3, "reportableChange": 1}]);
expect(endpoint.configureReporting).toHaveBeenCalledTimes(3);
});
});
+53 -3
View File
@@ -5,7 +5,6 @@ const MQTT = require('./stub/mqtt');
const settings = require('../lib/util/settings');
const Controller = require('../lib/controller');
const flushPromises = () => new Promise(setImmediate);
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const mocksClear = [MQTT.publish, logger.warn, logger.debug];
@@ -30,7 +29,6 @@ describe('Entity publish', () => {
controller = new Controller();
await controller.start();
await flushPromises();
await wait(50);
});
beforeEach(async () => {
@@ -714,7 +712,6 @@ describe('Entity publish', () => {
expect(endpoint.command).toHaveBeenCalledWith("closuresWindowCovering", "stop", {}, {});
});
it('Should turn device on with on/off when transition is provided', async () => {
const device = zigbeeHerdsman.devices.bulb_color;
const endpoint = device.getEndpoint(1);
@@ -780,6 +777,32 @@ describe('Entity publish', () => {
expect(MQTT.publish.mock.calls[2]).toEqual(["zigbee2mqtt/bulb_color", JSON.stringify({state: 'ON', brightness: 200, linkquality: 10}), {"qos": 0, "retain": false}, expect.any(Function)]);
});
it('When device is turned off with transition and turned on WITHOUT transition it should restore the brightness', async () => {
const device = zigbeeHerdsman.devices.bulb_color;
const endpoint = device.getEndpoint(1);
// Set initial brightness in state
await MQTT.events.message('zigbee2mqtt/bulb_color/set', JSON.stringify({brightness: 200}));
await flushPromises();
endpoint.command.mockClear();
MQTT.publish.mockClear();
// Turn off
await MQTT.events.message('zigbee2mqtt/bulb_color/set', JSON.stringify({state: 'OFF', transition: 3}));
await flushPromises();
expect(endpoint.command).toHaveBeenCalledTimes(1);
expect(endpoint.command.mock.calls[0]).toEqual(["genLevelCtrl", "moveToLevelWithOnOff", {level: 0, transtime: 30}, {}]);
expect(MQTT.publish).toHaveBeenCalledTimes(1);
expect(MQTT.publish.mock.calls[0]).toEqual(["zigbee2mqtt/bulb_color", JSON.stringify({state: 'OFF', brightness: 200}), {"qos": 0, "retain": false}, expect.any(Function)]);
// Turn on again
await MQTT.events.message('zigbee2mqtt/bulb_color/set', JSON.stringify({state: 'ON'}));
await flushPromises();
expect(endpoint.command).toHaveBeenCalledTimes(2);
expect(endpoint.command.mock.calls[1]).toEqual(["genLevelCtrl", "moveToLevelWithOnOff", {level: 200, transtime: 0}, {}]);
expect(MQTT.publish).toHaveBeenCalledTimes(2);
expect(MQTT.publish.mock.calls[1]).toEqual(["zigbee2mqtt/bulb_color", JSON.stringify({state: 'ON', brightness: 200}), {"qos": 0, "retain": false}, expect.any(Function)]);
});
it('Home Assistant: should set state', async () => {
settings.set(['homeassistant'], true);
const device = zigbeeHerdsman.devices.bulb_color;
@@ -1001,4 +1024,31 @@ describe('Entity publish', () => {
expect(endpoint.command).toHaveBeenCalledTimes(0);
expect(logger.error).toHaveBeenCalledWith("No converter available for 'get' 'brightness_move' (20)");
});
it('Should restore brightness when its turned off without transition and is turned on with', async () => {
// https://github.com/Koenkk/zigbee-herdsman-converters/issues/1097
const device = zigbeeHerdsman.devices.bulb_color;
const endpoint = device.getEndpoint(1);
endpoint.command.mockClear();
await MQTT.events.message('zigbee2mqtt/bulb_color/set', JSON.stringify({state: 'ON'}));
await flushPromises();
expect(endpoint.command).toHaveBeenCalledTimes(1);
expect(endpoint.command.mock.calls[0]).toEqual(["genOnOff", "on", {}, {}]);
await MQTT.events.message('zigbee2mqtt/bulb_color/set', JSON.stringify({"state": "ON", "brightness": 123}));
await flushPromises();
expect(endpoint.command).toHaveBeenCalledTimes(2);
expect(endpoint.command.mock.calls[1]).toEqual(["genLevelCtrl", "moveToLevelWithOnOff", {level: 123, transtime: 0}, {}]);
await MQTT.events.message('zigbee2mqtt/bulb_color/set', JSON.stringify({"state": "OFF"}));
await flushPromises();
expect(endpoint.command).toHaveBeenCalledTimes(3);
expect(endpoint.command.mock.calls[2]).toEqual(["genOnOff", "off", {}, {}]);
await MQTT.events.message('zigbee2mqtt/bulb_color/set', JSON.stringify({"state": "ON", "transition": 1.0}));
await flushPromises();
expect(endpoint.command).toHaveBeenCalledTimes(4);
expect(endpoint.command.mock.calls[3]).toEqual(["genLevelCtrl", "moveToLevelWithOnOff", {level: 123, transtime: 10}, {}]);
});
});
+21 -4
View File
@@ -14,6 +14,7 @@ describe('Groups', () => {
let controller;
beforeEach(() => {
data.writeEmptyState();
controller = new Controller();
Object.values(zigbeeHerdsman.groups).forEach((g) => g.members = []);
data.writeDefaultConfiguration();
@@ -296,6 +297,23 @@ describe('Groups', () => {
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/group_1", '{"state":"ON"}', {"retain": false, qos: 0}, expect.any(Function));
});
it('Should publish state change of all members when a group changes its state, filtered', async () => {
const device = zigbeeHerdsman.devices.bulb_color;
const endpoint = device.getEndpoint(1);
const group = zigbeeHerdsman.groups.group_1;
group.members.push(endpoint);
settings.set(['groups'], {'1': {friendly_name: 'group_1', retain: false, filtered_attributes: ['brightness'], devices: [device.ieeeAddr]}});
await controller.start();
await flushPromises();
MQTT.publish.mockClear();
await MQTT.events.message('zigbee2mqtt/group_1/set', JSON.stringify({state: 'ON', brightness: 100}));
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(2);
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bulb_color", '{"state":"ON","brightness":100}', {"retain": false, qos: 0}, expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/group_1", '{"state":"ON"}', {"retain": false, qos: 0}, expect.any(Function));
});
it('Shouldnt publish group state change when a group is not optimistic', async () => {
const device = zigbeeHerdsman.devices.bulb_color;
const endpoint = device.getEndpoint(1);
@@ -306,7 +324,6 @@ describe('Groups', () => {
await flushPromises();
MQTT.publish.mockClear();
controller.state.state = {};
const payload = {data: {onOff: 1}, cluster: 'genOnOff', device, endpoint, type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
@@ -410,8 +427,8 @@ describe('Groups', () => {
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(3);
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bulb_color", '{"state":"OFF"}', {"retain": false, qos: 0}, expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bulb", '{"state":"OFF","brightness":50,"color_temp":370,"linkquality":99}', {"retain": true, qos: 0}, expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/group_1", '{"state":"OFF","brightness":50,"color_temp":370}', {"retain": false, qos: 0}, expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bulb", '{"state":"OFF"}', {"retain": true, qos: 0}, expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/group_1", '{"state":"OFF"}', {"retain": false, qos: 0}, expect.any(Function));
});
it('Should publish state change off even when missing current state', async () => {
@@ -440,4 +457,4 @@ describe('Groups', () => {
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bulb_color", '{"state":"OFF"}', {"retain": false, qos: 0}, expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/group_1", '{"state":"OFF"}', {"retain": false, qos: 0}, expect.any(Function));
});
});
});
+222 -2
View File
@@ -32,6 +32,27 @@ describe('HomeAssistant extension', () => {
expect(missing).toHaveLength(0);
});
it('Should not have duplicate type/object_ids in a mapping', () => {
const duplicated = [];
const HomeAssistant = require('../lib/extension/homeassistant');
const ha = new HomeAssistant(null, null, null, null, {on: () => {}});
require('zigbee-herdsman-converters').devices.forEach((d) => {
const mapping = ha._getMapping()[d.model];
const cfg_type_object_ids = [];
mapping.forEach((c) => {
if (cfg_type_object_ids.includes(c['type'] + '/' + c['object_id'])) {
duplicated.push(d.model);
} else {
cfg_type_object_ids.push(c['type'] + '/' + c['object_id']);
}
});
});
expect(duplicated).toHaveLength(0);
});
it('Should discover devices', async () => {
controller = new Controller(false);
await controller.start();
@@ -564,13 +585,13 @@ describe('HomeAssistant extension', () => {
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bulb',
'{"state":"ON","brightness":50,"color_temp":370,"linkquality":99}',
'{"state":"ON","brightness":50,"color_temp":370,"linkquality":99,"update_available":false}',
{ retain: true, qos: 0 },
expect.any(Function)
);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/remote',
'{"brightness":255}',
'{"brightness":255,"update_available":false}',
{ retain: true, qos: 0 },
expect.any(Function)
);
@@ -688,6 +709,40 @@ describe('HomeAssistant extension', () => {
expect(MQTT.publish).toHaveBeenCalledTimes(1);
});
it('Should refresh discovery when device is renamed', async () => {
controller = new Controller(false);
await controller.start();
await flushPromises();
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/config/rename', '{"old": "weather_sensor", "new": "weather_sensor_renamed"}');
await flushPromises();
const payload = {
'unit_of_measurement': '°C',
'device_class': 'temperature',
'value_template': '{{ value_json.temperature }}',
'state_topic': 'zigbee2mqtt/weather_sensor_renamed',
'json_attributes_topic': 'zigbee2mqtt/weather_sensor_renamed',
'name': 'weather_sensor_renamed_temperature',
'unique_id': '0x0017880104e45522_temperature_zigbee2mqtt',
'device': {
'identifiers': ['zigbee2mqtt_0x0017880104e45522'],
'name': 'weather_sensor_renamed',
'sw_version': this.version,
'model': 'Aqara temperature, humidity and pressure sensor (WSDCGQ11LM)',
'manufacturer': 'Xiaomi',
},
'availability_topic': 'zigbee2mqtt/bridge/state',
};
expect(MQTT.publish).toHaveBeenCalledWith(
'homeassistant/sensor/0x0017880104e45522/temperature/config',
JSON.stringify(payload),
{ retain: true, qos: 0 },
expect.any(Function),
);
});
it('Should discover update_available sensor when device supports it', async () => {
controller = new Controller(false);
await controller.start();
@@ -719,4 +774,169 @@ describe('HomeAssistant extension', () => {
expect.any(Function),
);
});
it('Should discover trigger when click is published', async () => {
controller = new Controller(false);
await controller.start();
await flushPromises();
const discovered = MQTT.publish.mock.calls.filter((c) => c[0].includes('0x0017880104e45520')).map((c) => c[0]);
expect(discovered.length).toBe(4);
expect(discovered).toContain('homeassistant/sensor/0x0017880104e45520/click/config');
expect(discovered).toContain('homeassistant/sensor/0x0017880104e45520/action/config');
MQTT.publish.mockClear();
const device = zigbeeHerdsman.devices.WXKG11LM;
const payload = {data: {onOff: 1}, cluster: 'genOnOff', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
const discoverPayload = {
"automation_type":"trigger",
"type":"click",
"subtype":"single",
"payload":"single",
"topic":"zigbee2mqtt/button/click",
"device":{
"identifiers":[
"zigbee2mqtt_0x0017880104e45520"
],
"name":"button",
"sw_version": this.version,
"model":"Aqara wireless switch (WXKG11LM)",
"manufacturer":"Xiaomi"
}
};
expect(MQTT.publish).toHaveBeenCalledWith(
'homeassistant/device_automation/0x0017880104e45520/click_single/config',
JSON.stringify(discoverPayload),
{ retain: true, qos: 0 },
expect.any(Function),
);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/button/click',
'single',
{ retain: false, qos: 0 },
expect.any(Function),
);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/button',
JSON.stringify({click: "single", linkquality: 10}),
{ retain: false, qos: 0 },
expect.any(Function),
);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/button',
JSON.stringify({linkquality: 10, click: ""}),
{ retain: false, qos: 0 },
expect.any(Function),
);
// Should only discover it once
MQTT.publish.mockClear();
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(MQTT.publish).not.toHaveBeenCalledWith(
'homeassistant/device_automation/0x0017880104e45520/click_single/config',
JSON.stringify(discoverPayload),
{ retain: true, qos: 0 },
expect.any(Function),
);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/button/click',
'single',
{ retain: false, qos: 0 },
expect.any(Function),
);
});
it('Should disable Home Assistant legacy triggers', async () => {
settings.set(['advanced', 'homeassistant_legacy_triggers'], false);
controller = new Controller(false);
await controller.start();
await flushPromises();
const discovered = MQTT.publish.mock.calls.filter((c) => c[0].includes('0x0017880104e45520')).map((c) => c[0]);
expect(discovered.length).toBe(2);
expect(discovered).not.toContain('homeassistant/sensor/0x0017880104e45520/click/config');
expect(discovered).not.toContain('homeassistant/sensor/0x0017880104e45520/action/config');
MQTT.publish.mockClear();
const device = zigbeeHerdsman.devices.WXKG11LM;
const payload = {data: {onOff: 1}, cluster: 'genOnOff', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
const discoverPayload = {
"automation_type":"trigger",
"type":"click",
"subtype":"single",
"payload":"single",
"topic":"zigbee2mqtt/button/click",
"device":{
"identifiers":[
"zigbee2mqtt_0x0017880104e45520"
],
"name":"button",
"sw_version": this.version,
"model":"Aqara wireless switch (WXKG11LM)",
"manufacturer":"Xiaomi"
}
};
expect(MQTT.publish).toHaveBeenCalledWith(
'homeassistant/device_automation/0x0017880104e45520/click_single/config',
JSON.stringify(discoverPayload),
{ retain: true, qos: 0 },
expect.any(Function),
);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/button/click',
'single',
{ retain: false, qos: 0 },
expect.any(Function),
);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/button',
JSON.stringify({click: "single", linkquality: 10}),
{ retain: false, qos: 0 },
expect.any(Function),
);
expect(MQTT.publish).toHaveBeenCalledTimes(3);
});
it('Should republish payload to postfix topic with lightWithPostfix config', async () => {
controller = new Controller(false);
await controller.start();
await flushPromises();
MQTT.publish.mockClear();
await MQTT.events.message('zigbee2mqtt/U202DST600ZB/l2/set', JSON.stringify({state: 'ON', brightness: 20}));
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/U202DST600ZB', JSON.stringify({state_l2:"ON", brightness_l2:20}), {"qos": 0, "retain": false}, expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/U202DST600ZB/l2', JSON.stringify({state:"ON", brightness:20}), {"qos": 0, "retain": false}, expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/U202DST600ZB/l1', JSON.stringify({}), {"qos": 0, "retain": false}, expect.any(Function));
});
it('Shouldnt crash in onPublishEntityState on group publish', async () => {
controller = new Controller(false);
await controller.start();
await flushPromises();
logger.error.mockClear();
MQTT.publish.mockClear();
await MQTT.events.message('zigbee2mqtt/group_1/set', JSON.stringify({state: 'ON'}));
await flushPromises();
expect(logger.error).toHaveBeenCalledTimes(0);
});
});
+10
View File
@@ -98,4 +98,14 @@ describe('Logger', () => {
expect(pipes.constructor.name).toBe('Console');
expect(pipes.silent).toBe(true);
});
it('Should allow to disable log rotation', () => {
settings.set(['advanced', 'log_rotation'], false);
const logger = require('../lib/util/logger.js');
const pipes = logger._readableState.pipes;
expect(pipes[1].constructor.name).toBe('File');
expect(pipes[1].maxFiles).toBeNull();
expect(pipes[1].tailable).toBeFalsy();
expect(pipes[1].maxsize).toBeNull();
});
});
+16 -4
View File
@@ -25,7 +25,7 @@ describe('OTA update', () => {
MQTT.publish.mockClear();
});
it('Should subscribe to nested topics', async () => {
it('Should subscribe to topics', async () => {
expect(MQTT.subscribe).toHaveBeenCalledWith('zigbee2mqtt/bridge/ota_update/check');
expect(MQTT.subscribe).toHaveBeenCalledWith('zigbee2mqtt/bridge/ota_update/update');
});
@@ -119,9 +119,9 @@ describe('OTA update', () => {
});
it('Should not check for OTA when device does not support it', async () => {
MQTT.events.message('zigbee2mqtt/bridge/ota_update/check', 'bulb_color_2');
MQTT.events.message('zigbee2mqtt/bridge/ota_update/check', 'ZNLDP12LM');
await flushPromises();
expect(logger.error).toHaveBeenCalledWith(`Device 'bulb_color_2' does not support OTA updates`);
expect(logger.error).toHaveBeenCalledWith(`Device 'ZNLDP12LM' does not support OTA updates`);
});
it('Should refuse to check/update when already in progress', async () => {
@@ -174,7 +174,9 @@ describe('OTA update', () => {
await flushPromises();
expect(mapped.ota.isUpdateAvailable).toHaveBeenCalledTimes(1);
expect(mapped.ota.isUpdateAvailable).toHaveBeenCalledWith(device, logger, {"imageType": 12382});
expect(logger.info).toHaveBeenCalledWith(`Update available for 'bulb'`)
expect(logger.info).toHaveBeenCalledWith(`Update available for 'bulb'`);
expect(device.endpoints[0].commandResponse).toHaveBeenCalledTimes(1);
expect(device.endpoints[0].commandResponse).toHaveBeenCalledWith("genOta", "queryNextImageResponse", {"status": 0x95});
// Should not request again when device asks again after a short time
await zigbeeHerdsman.events.message(payload);
@@ -189,4 +191,14 @@ describe('OTA update', () => {
await flushPromises();
expect(logger.info).not.toHaveBeenCalledWith(`Update available for 'bulb'`)
});
it('Should respond with NO_IMAGE_AVAILABLE when not supporting OTA', async () => {
const device = zigbeeHerdsman.devices.QBKG04LM;
const data = {imageType: 12382};
const payload = {data, cluster: 'genOta', device, endpoint: device.getEndpoint(1), type: 'commandQueryNextImageRequest', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(device.endpoints[0].commandResponse).toHaveBeenCalledTimes(1);
expect(device.endpoints[0].commandResponse).toHaveBeenCalledWith("genOta", "queryNextImageResponse", {"status": 152});
});
});
+75 -1
View File
@@ -434,6 +434,31 @@ describe('Settings', () => {
expect(settings.get().groups).toStrictEqual(expected);
});
it('Shouldnt crash when removing device from group when group has no devices', () => {
write(configurationFile, {
devices: {
'0x123': {
friendly_name: 'bulb',
retain: true,
}
},
groups: {
'1': {
friendly_name: 'test123',
}
}
});
settings.removeDeviceFromGroup('test123', ['0x123']);
const expected = {
'1': {
friendly_name: 'test123',
},
};
expect(settings.get().groups).toStrictEqual(expected);
});
it('Should throw when adding device to non-existing group', () => {
write(configurationFile, {
devices: {
@@ -464,6 +489,31 @@ describe('Settings', () => {
}).toThrow(new Error("Device '0x123' already exists"));
});
it('Should not allow retention configuration without MQTT v5', () => {
write(configurationFile, {
devices: {'0x0017880104e45519': {friendly_name: 'tain', retention: 900}},
});
settings._reRead();
expect(() => {
settings.validate();
}).toThrowError('MQTT retention requires protocol version 5');
});
it('Should not allow non-existing entities in availability blacklist', () => {
write(configurationFile, {
devices: {'0x0017880104e45519': {friendly_name: 'tain'}},
advanced: {availability_blacklist: ['0x0017880104e45519', 'non_existing']},
});
settings._reRead();
expect(() => {
settings.validate();
}).toThrowError(`Non-existing entity 'non_existing' specified in 'availability_blacklist'`);
});
it('Should ban devices', () => {
write(configurationFile, {});
settings.banDevice('0x123');
@@ -512,6 +562,30 @@ describe('Settings', () => {
}).toThrowError(`Duplicate friendly_name 'myname' found`);
});
it('Configuration shouldnt be valid when friendly_name ends with /DIGIT', async () => {
write(configurationFile, {
devices: {'0x0017880104e45519': {friendly_name: 'myname/123', retain: false}},
});
settings._reRead();
expect(() => {
settings.validate();
}).toThrowError(`Friendly name cannot end with a "/DIGIT" ('myname/123')`);
});
it('Configuration shouldnt be valid when friendly_name contains a MQTT wildcard', async () => {
write(configurationFile, {
devices: {'0x0017880104e45519': {friendly_name: 'myname#', retain: false}},
});
settings._reRead();
expect(() => {
settings.validate();
}).toThrowError(`MQTT wildcard (+ and #) not allowed in friendly_name ('myname#')`);
});
it('Configuration shouldnt be valid when friendly_name is a postfix', async () => {
write(configurationFile, {
devices: {'0x0017880104e45519': {friendly_name: 'left', retain: false}},
@@ -521,7 +595,7 @@ describe('Settings', () => {
expect(() => {
settings.validate();
}).toThrowError(`Following friendly_name are not allowed: '${utils.getPostfixes()}'`);
}).toThrowError(`Following friendly_name are not allowed: '${utils.getEndpointNames()}'`);
});
it('Configuration shouldnt be valid when duplicate friendly_name are used', async () => {
+6
View File
@@ -147,6 +147,12 @@ function writeDefaultConfiguration() {
},
'0x0017880104e45526': {
friendly_name: 'GL-S-007ZS',
},
'0x0017880104e43559': {
friendly_name: 'U202DST600ZB'
},
'0x0017880104e44559': {
friendly_name: '3157100_thermostat',
}
},
groups: {
+8 -4
View File
@@ -14,6 +14,7 @@ class Group {
const clusters = {
'genBasic': 0,
'genOta': 25,
'genScenes': 5,
'genOnOff': 6,
'genLevelCtrl': 8,
@@ -29,6 +30,7 @@ class Endpoint {
this.inputClusters = inputClusters;
this.outputClusters = outputClusters;
this.command = jest.fn();
this.commandResponse = jest.fn();
this.read = jest.fn();
this.write = jest.fn();
this.bind = jest.fn();
@@ -98,13 +100,13 @@ class Device {
const returnDevices = [];
const bulb_color = new Device('Router', '0x000b57fffec6a5b3', 40399, 4107, [new Endpoint(1, [0,3,4,5,6,8,768,2821,4096], [5,25,32,4096], '0x000b57fffec6a5b3')], true, "Mains (single phase)", "LLC020");
const bulb_color = new Device('Router', '0x000b57fffec6a5b3', 40399, 4107, [new Endpoint(1, [0,3,4,5,6,8,768,2821,4096], [5,25,32,4096], '0x000b57fffec6a5b3', [], {lightingColorCtrl: {colorCapabilities: 254}})], true, "Mains (single phase)", "LLC020");
const bulb_color_2 = new Device('Router', '0x000b57fffec6a5b4', 401292, 4107, [new Endpoint(1, [0,3,4,5,6,8,768,2821,4096], [5,25,32,4096], '0x000b57fffec6a5b4')], true, "Mains (single phase)", "LLC020");
const bulb_2 = new Device('Router', '0x000b57fffec6a5b7', 40369, 4476, [new Endpoint(1, [0,3,4,5,6,8,768,2821,4096], [5,25,32,4096], '0x000b57fffec6a5b7')], true, "Mains (single phase)", "TRADFRI bulb E27 WS opal 980lm");
const devices = {
'coordinator': new Device('Coordinator', '0x00124b00120144ae', 0, 0, [new Endpoint(1, [], [])], false),
'bulb': new Device('Router', '0x000b57fffec6a5b2', 40369, 4476, [new Endpoint(1, [0,3,4,5,6,8,768,2821,4096], [5,25,32,4096], '0x000b57fffec6a5b2')], true, "Mains (single phase)", "TRADFRI bulb E27 WS opal 980lm"),
'bulb': new Device('Router', '0x000b57fffec6a5b2', 40369, 4476, [new Endpoint(1, [0,3,4,5,6,8,768,2821,4096], [5,25,32,4096], '0x000b57fffec6a5b2', [], {lightingColorCtrl: {colorCapabilities: 17}})], true, "Mains (single phase)", "TRADFRI bulb E27 WS opal 980lm"),
'bulb_color': bulb_color,
'bulb_2': bulb_2,
'bulb_color_2': bulb_color_2,
@@ -119,7 +121,7 @@ const devices = {
'RTCGQ11LM': new Device('EndDevice', '0x0017880104e45523', 6540,4151, [new Endpoint(1, [0], [])], true, "Battery", "lumi.sensor_motion.aq2"),
'ZNCZ02LM': new Device('Router', '0x0017880104e45524', 6540,4151, [new Endpoint(1, [0], [])], true, "Mains (single phase)", "lumi.plug"),
'E1743': new Device('Router', '0x0017880104e45540', 6540,4476, [new Endpoint(1, [0], [])], true, "Mains (single phase)", 'TRADFRI on/off switch'),
'QBKG04LM': new Device('Router', '0x0017880104e45541', 6549,4151, [new Endpoint(1, [0], []), new Endpoint(2, [0, 6], [])], true, "Mains (single phase)", 'lumi.ctrl_neutral1'),
'QBKG04LM': new Device('Router', '0x0017880104e45541', 6549,4151, [new Endpoint(1, [0], [25]), new Endpoint(2, [0, 6], [])], true, "Mains (single phase)", 'lumi.ctrl_neutral1'),
'QBKG03LM':new Device('Router', '0x0017880104e45542', 6540,4151, [new Endpoint(1, [0], [], '0x0017880104e45542'), new Endpoint(2, [0, 6], [], '0x0017880104e45542'), new Endpoint(3, [0, 6], [], '0x0017880104e45542')], true, "Mains (single phase)", 'lumi.ctrl_neutral2'),
'GLEDOPTO1112': new Device('Router', '0x0017880104e45543', 6540, 4151, [new Endpoint(11, [0], [], '0x0017880104e45543'), new Endpoint(13, [0], [], '0x0017880104e45543')], true, "Mains (single phase)", 'GL-C-008'),
'GLEDOPTO111213': new Device('Router', '0x0017880104e45544', 6540,4151, [new Endpoint(11, [0], []), new Endpoint(13, [0], []), new Endpoint(12, [0], [])], true, "Mains (single phase)", 'GL-C-008'),
@@ -137,11 +139,13 @@ const devices = {
'LIVOLO': new Device('Router', '0x0017880104e45560', 6541,4152, [new Endpoint(6, [0, 6], [])], true, "Mains (single phase)", 'TI0001 '),
'tradfri_remote': new Device('EndDevice', '0x90fd9ffffe4b64ae', 33906, 4476, [new Endpoint(1, [0], [0,3,4,6,8,5], '0x90fd9ffffe4b64ae')], true, "Battery", "TRADFRI remote control"),
'roller_shutter': new Device('EndDevice', '0x90fd9ffffe4b64af', 33906, 4476, [new Endpoint(1, [0], [0,3,4,6,8,5], '0x90fd9ffffe4b64af')], true, "Battery", "SCM-R_00.00.03.15TC"),
'ZNLDP12LM': new Device('Router', '0x90fd9ffffe4b64ax', 33901, 4476, [new Endpoint(1, [0,4,3,5,10,258,13,19,6,1,1030,8,768,1027,1029,1026], [0,3,4,6,8,5], '0x90fd9ffffe4b64ax')], true, "Mains (single phase)", "lumi.light.aqcn02"),
'ZNLDP12LM': new Device('Router', '0x90fd9ffffe4b64ax', 33901, 4476, [new Endpoint(1, [0,4,3,5,10,258,13,19,6,1,1030,8,768,1027,1029,1026], [0,3,4,6,8,5], '0x90fd9ffffe4b64ax', [], {lightingColorCtrl: {colorCapabilities: 254}})], true, "Mains (single phase)", "lumi.light.aqcn02"),
'SP600_OLD': new Device('Router', '0x90fd9ffffe4b64aa', 33901, 4476, [new Endpoint(1, [0,4,3,5,10,258,13,19,6,1,1030,8,768,1027,1029,1026], [0,3,4,6,8,5], '0x90fd9ffffe4b64aa', [], {seMetering: {"multiplier":1,"divisor":10000}})], true, "Mains (single phase)", "SP600", false, 'Salus', '20160120'),
'SP600_NEW': new Device('Router', '0x90fd9ffffe4b64ab', 33901, 4476, [new Endpoint(1, [0,4,3,5,10,258,13,19,6,1,1030,8,768,1027,1029,1026], [0,3,4,6,8,5], '0x90fd9ffffe4b64aa', [], {seMetering: {"multiplier":1,"divisor":10000}})], true, "Mains (single phase)", "SP600", false, 'Salus', '20170220'),
'MKS-CM-W5': new Device('Router', '0x90fd9ffffe4b64ac', 33901, 4476, [new Endpoint(1, [0,4,3,5,10,258,13,19,6,1,1030,8,768,1027,1029,1026], [0,3,4,6,8,5], '0x90fd9ffffe4b64aa', [], {})], true, "Mains (single phase)", "qnazj70", false),
'GL-S-007ZS': new Device('Router', '0x0017880104e45526', 6540,4151, [new Endpoint(1, [0], [], '0x0017880104e45526')], true, "Mains (single phase)", 'GL-S-007ZS'),
'U202DST600ZB': new Device('Router', '0x0017880104e43559', 6540,4151, [new Endpoint(10, [0, 6], [], '0x0017880104e43559'), new Endpoint(11, [0, 6], [], '0x0017880104e43559')], true, "Mains (single phase)", 'U202DST600ZB'),
'3157100': new Device('Router', '0x0017880104e44559', 6542,4151, [new Endpoint(1, [], [], '0x0017880104e44559')], true, "Mains (single phase)", '3157100'),
}
const groups = {