Compare commits

...
1452 Commits
Author SHA1 Message Date
Koen Kanters faaf3e488f 1.14.2 2020-07-22 22:17:55 +02:00
Koen Kanters 1aa70cca91 Undev 2020-07-22 22:17:48 +02:00
Koen Kanters 28d48f3d96 Skip message when definition is undefined and still interviewing instead of modelID. https://github.com/Koenkk/zigbee2mqtt/issues/3947 2020-07-22 14:00:27 +02:00
github-actions[bot]github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>Koen Kanters
93cae0b09a Update zigbee-herdsman-converters to 12.0.147
* Update zigbee-herdsman-converters to 12.0.147

* Update homeassistant.js

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-07-22 13:57:11 +02:00
Koen Kanters 6d9affaa49 Revert "Fix device incorrectly identified when still interviewing. #3947"
This reverts commit 1d3a577fc4.
2020-07-22 13:44:56 +02:00
Koen Kanters e06e54321c Revert "Fix device incorrectly identified when still interviewing (attempt 2) #3947"
This reverts commit 2e0b23f97c.
2020-07-22 13:44:47 +02:00
Koen Kanters db748a1333 Implement new api healthcheck. #3281 2020-07-21 21:16:52 +02:00
Koen Kanters 2e0b23f97c Fix device incorrectly identified when still interviewing (attempt 2) #3947 2020-07-21 20:47:05 +02:00
Koen Kanters 1d3a577fc4 Fix device incorrectly identified when still interviewing. #3947 2020-07-21 20:26:07 +02:00
github-actions[bot]github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>Koen Kanters
ad0bbbec97 Update zigbee-herdsman-converters to 12.0.146
* Update zigbee-herdsman-converters to 12.0.146

* Update publish.test.js

* Update homeassistant.js

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-07-20 18:58:17 +02:00
Deadlystrike edcf1edae6 Add support for Embrighten Outlet 43102 (#3939) 2020-07-20 18:05:42 +02:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 57b45f6624 Update zigbee-herdsman-converters to 12.0.141 (#3933)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2020-07-19 02:01:12 +02:00
Koen Kanters 85eb74b546 Merge branch 'master' into dev 2020-07-19 01:54:24 +02:00
Koen Kanters f26791aa2c Reduce days until stale 2020-07-19 01:54:13 +02:00
Koen Kanters 2728508c7f Update naming 2020-07-19 01:53:45 +02:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 292c735ce8 Update dependencies (#3932)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2020-07-19 01:45:07 +02:00
Koen Kanters 3123dd5abb Add update_deps.yml 2020-07-19 01:29:32 +02:00
Koen Kanters 1f39ff6f57 Fix transition from device_options not applied. #3922 2020-07-19 00:04:39 +02:00
Koen Kanters 0e0a364da7 Validate experimental.output settings. #3928 2020-07-18 23:40:23 +02:00
github-actions[bot]andgithub-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> 38bf81ed84 Update zigbee-herdsman to 0.12.108 (#3931)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2020-07-18 23:04:18 +02:00
Koen Kanters 0cc80632da Merge branch 'master' into dev 2020-07-18 23:03:42 +02:00
Koen Kanters d07d90fe33 Fix CI not triggering on automatic PR 2020-07-18 23:03:33 +02:00
Koen Kanters a845d35b8e Update Birth & Will Topic for Home Assistant #3918 2020-07-16 23:16:59 +02:00
github-actions[bot]github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>Koen Kanters
570985b877 Update zigbee-herdsman-converters (#3917)
* Update zigbee-herdsman-converters to 12.0.140

* Update publish.test.js

* Update publish.test.js

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-07-16 22:59:30 +02:00
Koen Kanters 7d2ac63482 Merge branch 'master' into dev 2020-07-16 22:53:42 +02:00
Koen Kanters f8463d9bb0 Fix pr not triggering checks 2020-07-16 22:53:30 +02:00
Artyom DudarevandKoen Kanters 1223a06871 Add support for Lonsonho switches (#3901)
* Add support for Lonsonho switches

* Use cfg.switch for 1 gang switch

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-07-16 22:40:40 +02:00
Hannes GiesenowandKoen Kanters ec688cfa04 Add support for Osram Smart Switch 4x (#3242)
* Add support for Osram Smart Switch 4x

See https://github.com/Koenkk/zigbee-herdsman-converters/pull/1112 for
the converter

* Update homeassistant.js

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-07-16 22:35:16 +02:00
Koen Kanters d140c55252 merge branch 'master' into dev 2020-07-16 22:17:04 +02:00
Koen Kanters 9b382595ea Add ci.yml 2020-07-16 22:16:55 +02:00
Koen Kanters 2de44b3f7d Prevent future merge conflicts on automatic updates. 2020-07-16 21:13:03 +02:00
github-actions[bot]github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>Koen Kanters
9b9eb84f4e Update zigbee-herdsman to 0.12.107 (#3916)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-07-16 21:12:04 +02:00
Mark SnellingandKoen Kanters 64e9d65b07 Added AOne 250w Smart Dimmer Module (#3915)
* Create update_zhc.yml

* Update update_zhc.yml

* Update update_zhc.yml

* Added AOne 250w Smart Dimmer Module

* Delete update_zhc.yml

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-07-16 21:10:05 +02:00
Koen Kanters 237019282d Add update_zh.yml 2020-07-16 21:06:30 +02:00
Koen Kanters 08a6c1a724 Update update_zhc.yml 2020-07-16 21:06:30 +02:00
Koen Kanters f93a1c8e29 Update update_zhc.yml 2020-07-16 21:06:30 +02:00
Koen Kanters ec50d3ec0c Create update_zhc.yml 2020-07-16 21:06:30 +02:00
github-actions[bot]github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>Koen Kanters
f86be3308e Update zigbee-herdsman-converters (#3914)
* Update zigbee-herdsman-converters to 12.0.139

* Update homeassistant.js

* Update homeassistant.js

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-07-16 21:04:47 +02:00
Koen Kanters e6df6c585a Add update_zh.yml 2020-07-16 20:49:04 +02:00
Koen Kanters 900ae813e9 Update update_zhc.yml 2020-07-16 20:32:47 +02:00
Koen Kanters 0a69b98dfb Update update_zhc.yml 2020-07-16 19:40:58 +02:00
Koen Kanters 7a992fa180 Create update_zhc.yml 2020-07-16 19:29:47 +02:00
Koen Kanters 67f02adbd0 Prefer blocklist/passlist over blacklist/whitelist 2020-07-15 23:22:32 +02:00
Koen Kanters ee9aedd0f3 Discover Home Assistant energy sensor for NET2GRID N2G-SP. #3909 2020-07-15 23:17:54 +02:00
Koen Kanters ff1a64b192 Change ID -> id for new api. https://github.com/Koenkk/zigbee2mqtt/issues/3281 2020-07-15 22:16:18 +02:00
Koen Kanters 62b26ab4b9 Fix tests 2020-07-14 22:09:11 +02:00
Koen Kanters c900213218 Update converters 2020-07-14 22:04:33 +02:00
Koen Kanters 8415adc514 Make new api snake case. https://github.com/Koenkk/zigbee2mqtt/issues/3281 2020-07-13 23:00:33 +02:00
Koen Kanters 57a2d435a9 Republish groups on change. https://github.com/Koenkk/zigbee2mqtt/issues/3281 2020-07-13 21:45:44 +02:00
Koen Kanters ff8f16fedb Group MQTT api. https://github.com/Koenkk/zigbee2mqtt/issues/3281 2020-07-12 23:50:15 +02:00
Koen Kanters d81f5575ff Bind for new api. https://github.com/Koenkk/zigbee2mqtt/issues/3281 2020-07-12 21:56:11 +02:00
Koen Kanters d3b7fe222f Update herdsman and converters. 2020-07-12 17:14:56 +02:00
Koen Kanters e7a799d8cc Update converters 2020-07-12 15:42:33 +02:00
Jeremy Rea b76b244af7 Add Home Assistant support for Sinopé water leak detector (#3892) 2020-07-12 15:18:53 +02:00
TheMClaeysandKoen Kanters eac948498a Update homeassistant.js (#3889)
Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-07-12 14:52:30 +02:00
Koen Kanters 11a4759a9a Update converters 2020-07-10 22:09:28 +02:00
Koen Kanters b1a4926a30 Add cache_state_persistent and cache_state_send_on_startup options. #3496 2020-07-10 22:09:16 +02:00
Ryan Kim(True-World) 051d088172 Add PM-B540, TS0115 (#3886)
Support Dawon PM-B540,
UseeLink TS0115(https://ko.aliexpress.com/item/4000108371113.html?spm=a2g0o.productlist.0.0.55f169eaiSgWdl&algo_pvid=a2d855e8-89cc-42ea-ab68-8b04c981c537&algo_expid=a2d855e8-89cc-42ea-ab68-8b04c981c537-1&btsid=0ab6f82c15943852972118657e0a09&ws_ab_test=searchweb0_0,searchweb201602_,searchweb201603_)
TS0115 Model is multi type(EU, US, UK, Universal, Etc.) and 2 type Amp(10A, 16A)
2020-07-10 21:32:54 +02:00
Koen Kanters b4a6c6f0ba Update herdsman and converters 2020-07-09 22:00:17 +02:00
4fbfec3fdb ptvo.switch - updated HA integration settings. (#3880)
* ptvo.switch - updated HA integration settings.

* Update homeassistant.js

Co-authored-by: ptvoinfo <xagga@ya.ru>
Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-07-09 21:10:10 +02:00
krenclandKoen Kanters c72ccf1bd7 added LED controller YSRSAI ZB-CL01 support for hass.io (#3876)
* added LED controller YSRSAI ZB-CL01 support for hass.io

* Update homeassistant.js

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-07-09 20:55:54 +02:00
Koen Kanters 0a84412d75 Implement OTA commands for new api. https://github.com/Koenkk/zigbee2mqtt/issues/3281 2020-07-08 23:23:44 +02:00
Koen Kanters f1c785eedd Implement new api configure. https://github.com/Koenkk/zigbee2mqtt/issues/3281 2020-07-08 21:46:00 +02:00
Koen Kanters ff5d11b50a Update converters 2020-07-07 22:41:16 +02:00
Koen Kanters 903e93845c Update herdsman 2020-07-07 21:27:08 +02:00
Koen Kanters ffa47b79e3 Remove devices from group when removing group. #3861 2020-07-07 21:16:35 +02:00
Koen Kanters 49ebf66b0b Update converters 2020-07-06 23:19:12 +02:00
Pedro Lamas 973f5c5d03 Adds support for Sunricher ZG2835RAC power and energy monitoring in Home Assistant (#3860) 2020-07-06 21:46:07 +02:00
Koen Kanters 22387fd637 Don't provide defaults for rtscts and baudrate (#3854)
* Don't provide defaults for rtscts and baudrate

* Update herdsman
2020-07-06 21:37:58 +02:00
Koen Kanters df5f740518 Update converters 2020-07-04 16:20:15 +02:00
Koen Kanters 8f725d38bd Update converters 2020-07-03 23:00:25 +02:00
Koen Kanters 4900a2501d Support Home Assistant configuration for external converters. https://github.com/Koenkk/zigbee-herdsman-converters/issues/1343 2020-07-03 21:20:22 +02:00
Koen Kanters 1796ba191c Update herdsman and converters 2020-07-01 22:15:02 +02:00
Jiří Furda e8c7314e90 Add support for IMMAX 07115L (#3829) 2020-06-30 17:49:43 +02:00
Koen Kanters 4b75fdb8a3 Dev 2020-06-30 17:40:05 +02:00
Koen Kanters 7e46435d86 1.14.1 2020-06-30 17:38:48 +02:00
Koen Kanters 1133e8e1ab Undev 2020-06-30 17:37:57 +02:00
Koen Kanters a74597ec85 Update converters 2020-06-29 19:52:31 +02:00
Koen Kanters a391f7dcf9 Update converters 2020-06-29 17:01:45 +02:00
Koen Kanters 715e20477d Small cosmetic 2020-06-29 16:17:11 +02:00
John Doe def6bf1d0b Implement external converters (#3810) 2020-06-29 16:16:16 +02:00
Koen Kanters 4b68a482b7 Update herdsman and converters 2020-06-28 18:31:21 +02:00
felixstorm 1b62a3cf06 Fix Reporting for Multi-Endpoint Devices (#3824)
* fix reporting on multi-endpoint devices

* add test
2020-06-28 18:08:37 +02:00
Koen Kanters 27972fb8d4 Provide lx unit for RTCGQ11LM illuminance sensor. #3805 2020-06-24 23:43:24 +02:00
qosmio 1e62021418 Add support for Sylvania Flex XL RGBW Strip (73773) (#3806) 2020-06-24 23:39:09 +02:00
Koen Kanters ade6123ede Home Assistant discover illuminance_lux sensor for RTCGQ11LM. #3805 2020-06-24 23:28:33 +02:00
Thomas Rose 242600f2b6 Added new Innr Outdoor Lights (#3796)
Added support for Innr Outdoor Spot Lights and Outdoor Color LED Strip
2020-06-24 15:30:18 +02:00
Koen Kanters c07c1d5f15 Update herdsman 2020-06-23 11:19:32 +02:00
Koen Kanters fb0f83dee7 Update converters 2020-06-22 15:24:50 +02:00
Koen Kanters 869d6a5234 Fix reporting setup ddosing adapter. #3756 2020-06-21 16:38:23 +02:00
Koen Kanters 48705c9a9e Fix not connecting to MQTT when permit join fails on startup. #3756 2020-06-21 16:36:36 +02:00
Koen Kanters 95208a1a2e Update converters 2020-06-20 16:06:54 +02:00
KrzysztofandKoen Kanters 1dd002e73f HGZB-44 HomeAssistant Autodiscovery support (#3775)
* Add homeassistant autodiscovery support for HGZB-44.

* Fix missing , at end of line

* Update homeassistant.js

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-06-20 14:26:35 +02:00
Andreyanddivanikus 76745ca5c3 ZNCZ04LM extended attributes support (#3761)
* ZNCZ04LM extended attributes support

* Styles fixes

* Style fix

* Tabs

Co-authored-by: divanikus <d1pro@yandex.ru>
2020-06-17 19:54:08 +02:00
zrsmithsonandSmithson, Zachary <zachary.smithson@gtri.gatech.edu> 249bcff7d1 Add support for Ecosmart BR30 CCT Bulb A9BR3065WESDZ02 (#3751)
device similar to Ecosmart A19 CCT bulb

Co-authored-by: Smithson, Zachary <zachary.smithson@gtri.gatech.edu>
2020-06-16 17:05:37 +02:00
Koen Kanters f8d082e18d Networkmap #3281 2020-06-15 20:10:30 +02:00
Koen Kanters 79b4dbd24f Touchlink factory reset #3281 2020-06-15 19:19:57 +02:00
Koen Kanters 62dc88ec87 Republish bridge info on log level changes #3281 2020-06-15 19:06:08 +02:00
Koen Kanters d10c1c2155 Add some config options #3281 2020-06-15 18:58:32 +02:00
Koen Kanters 5027e97bb6 Update converters 2020-06-15 17:42:46 +02:00
Koen Kanters e0f5547160 Update converters 2020-06-14 18:01:25 +02:00
KostaandKonstantin Baumann b42c61d09a use relative timestamps (#3743)
Use relative timestamps for the network map (e.g, `1 hour, 43 minutes ago` or `15 minutes, 10 seconds ago`), since that is easier to understand/decode than the standard ISO timestamps.

This introduces an additional (light weight) dependency to [humanize-duration](https://github.com/EvanHahn/HumanizeDuration.js) which in itself doesn't have any additional dependencies.

Co-authored-by: Konstantin Baumann <konstantin.baumann@autodesk.com>
2020-06-14 17:43:27 +02:00
Koen Kanters c9aa8b24c0 Update converters 2020-06-14 16:27:47 +02:00
KostaandKonstantin Baumann a2ea520b0c add support for plantuml based network graphs (#3742)
Add support for [PlantUML](http://plantuml.com/guide) based network graphs, which can be pasted into [this online editor](https://www.planttext.com/).

The test configuration used for unit testing for example produces this output:

![output.svg](https://www.planttext.com/api/plantuml/svg/j5LTRzem57tVhxYFGSFbEbyG7gOoOBHggrMCQPsg2Zc9KwmwSPeufTjVsyD-qlx20dICZuJni4PHPDdtd7lkyRNpwyTFU7bESyqoNSJopP-PW6KXu3CYRNSwID7cjkEO3jok8_ONrqk4a0DXOBYEvJOWOaBoi0loKJGpLMYHt4-OBtabpNl58qYK_bIagSeq3wzKoENve3AOUcqaICjtWhIBs4NwTZbOHzojH_iLe--qeoZYWSiStzoes2-aNrlZ3igmqNAzHcNu-SMm1vDnR_1XV0wNmy6I68QcsngQRV0w2BA8UTA4KCJnmf4cp6T2SyXJ7kYiY9kWKYPV9esIWJgsCw9cTRh_w8QruyOqK59bntbYBJtnQZovdWafqXpE2WuZ1KQRsYwwU7rM7Lua3ucQ9qTLiDLzTAi2hLKo3LLHUZnzuD-EQs2wRE1EjR0RmLGieFV8CWOhPYYPOIuoBdcUmvn92VbSw606nfURYn6QbrUliN6RcXrle-mWC1qBfuiZn-ltRWTUbcnZjSn-aMiLGyYVHC1pC0RYQmDk-_r55bXbkJDcMgVTLYlLJ-f4995ghLGGd-Ky9D_5lSyv2PJAGf4mhJB2af2im8HIizK0OyLuClxuUJ8SlufZfkqllaXjc_4Dn_f_TTNxjGqsQipQKqZntmehpX8XxohITg4S7RgMwc2UUKooRR8o6SL3FLCBmtfOURhM6hVOIfY5-zQSyYHS_BT-0m00__y30000)

The generated script looks like this:

```
' paste into: https://www.planttext.com/

@startuml
card 0x0017880104e45525 [
0x0017880104e45525
---
0x0017880104e45525 (6536) failed: lqi,routingTable
---
Boef notSupportedModelID
---
1970-01-01T01:00:01+01:00
]

card 0x000b57fffec6a5b2 [
bulb
---
0x000b57fffec6a5b2 (40369)
---
IKEA TRADFRI LED bulb E26/E27 980 lumen, dimmable, white spectrum, opal white (LED1545G12)
---
1970-01-01T01:00:01+01:00
]

card 0x000b57fffec6a5b3 [
bulb_color
---
0x000b57fffec6a5b3 (40399)
---
Philips Hue Go (7146060PH)
---
unknown
]

card 0x0017880104e45521 [
button_double_key
---
0x0017880104e45521 (6538)
---
Xiaomi Aqara double key wireless wall switch (WXKG02LM)
---
1970-01-01T01:00:01+01:00
]

card 0x0017880104e45559 [
cc2530_router
---
0x0017880104e45559 (6540)
---
Custom devices (DiY) [CC2530 router](http://ptvo.info/cc2530-based-zigbee-coordinator-and-router-112/) (CC2530.ROUTER)
---
1970-01-01T01:00:01+01:00
]

card 0x00124b00120144ae [
Coordinator
---
0x00124b00120144ae (0)
---
1970-01-01T01:00:10+01:00
]

0x000b57fffec6a5b3 --> 0x00124b00120144ae: 120
0x000b57fffec6a5b2 --> 0x00124b00120144ae: 92
0x000b57fffec6a5b3 --> 0x000b57fffec6a5b2: 110
0x0017880104e45559 --> 0x000b57fffec6a5b2: 100
0x0017880104e45521 --> 0x0017880104e45559: 130

@enduml
```

Co-authored-by: Konstantin Baumann <konstantin.baumann@autodesk.com>
2020-06-14 15:48:50 +02:00
Koen Kanters 40f026cdf8 Update converters 2020-06-14 14:07:35 +02:00
jd1900andKoen Kanters 67c43fcee3 Add device '412015' from Legrand. DIN power consumption module. (#3739)
* Add device '412015' from Legrand. DIN power consumption module.

Add device '412015' from Legrand. DIN power consumption module. Complementary for this pull request https://github.com/Koenkk/zigbee-herdsman-converters/pull/1313

* Update homeassistant.js

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-06-14 14:01:02 +02:00
AndronicR 1dd3523e64 added for homeassistant (#3737) 2020-06-14 11:00:36 +02:00
Koen Kanters 37122dba79 changeOptions -> options. https://github.com/Koenkk/zigbee2mqtt/issues/3281 2020-06-14 00:28:24 +02:00
Koen Kanters 7f8fbe8b65 Lint 2020-06-13 23:46:04 +02:00
Koen Kanters 3658588618 Add group #3281 2020-06-13 23:42:58 +02:00
Koen Kanters a90ebce677 Change device options. #3181 2020-06-13 23:28:06 +02:00
Koen Kanters 7b3c07dcfe Implement renaming functionallity. https://github.com/Koenkk/zigbee2mqtt/issues/3281 2020-06-13 19:35:09 +02:00
Koen Kanters 16f5812f6c Finish remove api. https://github.com/Koenkk/zigbee2mqtt/issues/3281 2020-06-13 17:22:00 +02:00
Koen Kanters 1eed937c43 Update converters 2020-06-13 15:52:48 +02:00
Gabriele Besta e0a6b7d348 Add possibility to override execution command at runtime (#3722)
* Add possibility to override execution command at runtime

The entrypoint script initialize container data at runtime.
CMD defines the default executable and can be overridden at runtime.

* Set execution permission to entrypoint script

Necessary to prevent run errors, for example in windows env
2020-06-13 13:20:41 +02:00
Koen Kanters 4b845f923e Pass down logger to fromZigbee converters. https://github.com/Koenkk/zigbee-herdsman-converters/pull/1305#pullrequestreview-430027596 2020-06-13 12:55:01 +02:00
Esteban Zapata Rojas 50ba54e99e new device: Auto discovery configuration for RS-23ZBS devices on HA. (#3720) 2020-06-12 22:32:50 +02:00
Koen Kanters c6e76165ff Always convert syslog type to string. https://github.com/Koenkk/zigbee2mqtt/issues/3725 2020-06-12 16:51:49 +02:00
ahaghshenas cecedbd5f8 Update homeassistant.js (#3718) 2020-06-11 21:33:29 +02:00
Koen Kanters c3561640e6 Update converters. 2020-06-10 21:20:43 +02:00
Koen Kanters c3a71ba6a8 Dev 2020-06-10 16:42:53 +02:00
Koen Kanters 9009de24ac 1.14.0 2020-06-10 16:42:27 +02:00
Koen Kanters a5b0c80a2e Undev 2020-06-10 16:42:24 +02:00
Koen Kanters d9391ac685 Update herdsman 2020-06-10 16:41:08 +02:00
Koen Kanters 2bdb0f9ae1 Merge branch 'master' into dev 2020-06-10 16:36:37 +02:00
Koen Kanters 56714d7c5a Update converters. 2020-06-09 19:52:48 +02:00
Koen Kanters 7dee99df52 Add colortemp_move for group. #3705 2020-06-09 19:37:45 +02:00
Koen Kanters e5f9a969ac Discovery Home Assistant battery sensor for Danalock V3. #3702 2020-06-09 19:24:47 +02:00
Koen Kanters 206a45d29a Update converters. 2020-06-07 13:58:28 +02:00
sprockersandKoen Kanters c14e18dabb Adding homeassistant mapping for Hive DWS003 contact sensor (#3682)
Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-06-07 13:25:52 +02:00
sprockers 3566af1b08 Removing illuminance from Hive MOT003 (#3685) 2020-06-07 13:23:45 +02:00
Mark BergsmaandKoen Kanters a7adfebcb3 Add discovery support for the Plugwise Plug 160-01 (#3679)
Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-06-07 11:36:04 +02:00
Koen Kanters f8ea6cb574 Update converters. 2020-06-06 14:45:43 +02:00
Mattia480andKoen Kanters d66e1c322b Add EchoStar SAGE by Hughes Doorbell Sensor (SAGE206612) (#3675)
Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-06-06 14:12:41 +02:00
Koen Kanters 43127e95a9 Fix lint 2020-06-06 13:13:09 +02:00
Koen Kanters 976e802af8 Update converters. 2020-06-06 10:31:50 +02:00
Dominik Röttsches 32b96d1d4c Add homeassistant mapping for Ledvance Z3 Tunable White Panel (#3666)
See https://github.com/Koenkk/zigbee-herdsman-converters/pull/1279
2020-06-06 09:52:58 +02:00
Koen Kanters 7f68fd3fc4 Initial syslog logging. #3647 2020-06-03 20:44:11 +02:00
Koen Kanters 6d9dff8832 Mark node 14 as supported. #3660 2020-06-03 19:37:11 +02:00
Koen Kanters 8dc535e3e3 Update converters 2020-06-02 18:45:29 +02:00
Koen Kanters fda1246fca Attempt to fix lastSeen incorrect leading to incorrect offline state. #3650 2020-06-01 16:38:24 +02:00
Koen Kanters a9b54ad668 Update converters 2020-06-01 16:37:16 +02:00
Koen Kanters c0d4aea5bd Fix lint 2020-05-31 15:02:25 +02:00
Koen Kanters d440de8069 Fix networkmap error when using Gledopto GL-C-008-2ID. #3623 2020-05-30 18:27:25 +02:00
Koen Kanters e4c3ffe38d Update converters 2020-05-30 17:11:54 +02:00
Will UtherandKoen Kanters 7c045af987 Add a brief internal architecture description. (#3639)
* Add Stitchy Dim to list of devices.

* Add an internal architecture paragraph.

Add a README paragraph with a basic architecture description.  This doesn't have a lot of detail, but links to docs with (much) more detail.

* Try to line up with upstream.

* Update README.md

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-05-30 16:03:57 +02:00
Koen Kanters 2cb234c934 Update dependencies. #3616 2020-05-30 16:01:47 +02:00
Crowbar ZandKoen Kanters 51a6b9226d Remove precision rounding from HA MQTT autodiscovery template (#3636)
* Remove precision rounding from HA MQTT autodiscovery template

Precision rounding should be handled in converters and made available to
all MQTT consumers (not just HA)

* Update homeassistant.test.js

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-05-29 23:13:09 +02:00
Koen Kanters 7d1a97841c Update herdsman and converters. 2020-05-29 23:09:09 +02:00
JaydenandKoen Kanters 9c71ba8754 Support E1E-G7F (#3630)
I couldn't see battery data in the output so I have only added the sensor_action type. This works and home assistant can see button presses + link quality.

This is linked to: https://github.com/Koenkk/zigbee-herdsman-converters/pull/1265

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-05-29 19:39:32 +02:00
Koen Kanters 5f63dcb0f2 Fix old state being published due to debounce. #3572 2020-05-29 19:24:59 +02:00
Koen Kanters 89a6c976cb Update converters 2020-05-28 19:49:38 +02:00
Koen Kanters f793eab4ab Republish availability on MQTT connected. #3625 2020-05-28 17:44:50 +02:00
Jonas Bergler d5604ab5ec Make thermostat more like thermostatHeatCool (#3613)
* Make thermostat more like thermostatHeatCool

This change tries to unify the two thermostat templates a little.
I'm making this change because I wanted to enable tracking the current
state of the Zen thermostat and noticed that the logic was very specific
to a subset of thermostats.

The matching change in zigbee-herdsman-converters ensures that the
thermostats that were sending the "operation" field use the new format
and should effectively behave the same after the change.

* 0.5 degree steps for Zen thermostat

Because it supports it.
2020-05-27 16:26:55 +02:00
Koen Kanters 780246fe74 Fix typo 2020-05-26 17:36:04 +02:00
Koen Kanters b706233604 Fix lint. 2020-05-25 22:05:34 +02:00
Koen Kanters c4ce339942 Update converters. 2020-05-25 22:04:30 +02:00
Koen Kanters 409fb2407a #3281 Add tests for new bridge API 2020-05-24 18:16:39 +02:00
Koen Kanters 1638b81723 Update converters 2020-05-24 15:57:29 +02:00
Koen Kanters 396bdf5592 Update converters 2020-05-24 14:41:40 +02:00
sswongandKoen Kanters 89b9b84f94 add support for QBKG22LM-aqara-double-key-wall-switch-without-neutral (#3600)
* add support for QBKG22LM-aqara-double-key-wall-switch-without-neutral (updated model variant)

* removed tab

* Update homeassistant.js

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-05-24 14:19:51 +02:00
Koen Kanters 770a7e77e7 Update converters 2020-05-23 20:53:20 +02:00
Koen Kanters 49df5751b2 Log friendly error when endpoint does not exist on device. https://github.com/Koenkk/zigbee-herdsman-converters/issues/125 2020-05-23 20:48:07 +02:00
f594664f55 add support for WXKG06LM-aqara-single-key-wireless-wall-switch (#3593)
* add support for WXKG06LM-aqara-single-key-wireless-wall-switch

* Update homeassistant.js

Co-authored-by: sswong <saiseng.wong@wizvision.com>
Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-05-22 18:33:05 +02:00
Koen Kanters d9b8e1fc18 Fix messages being skipped for Xiaomi devices with Deconz adapter. #3592 2020-05-22 18:25:32 +02:00
Koen Kanters 94dbf9c505 Fix not able to read state from multiple endpoints at once. https://github.com/Koenkk/zigbee-herdsman-converters/issues/1252 2020-05-22 18:16:53 +02:00
Koen Kanters 83215c3290 Update converters. 2020-05-21 15:47:01 +02:00
Andrew N Golovkov adcec74f23 added Aqara Opple MX650 aka XDD12LM (#3579) 2020-05-21 14:55:37 +02:00
Koen Kanters 7e6c508263 Fix number action causing exception in Home Assistant extesion. #3578 2020-05-21 14:52:02 +02:00
Koen Kanters b2034943a5 Update converters. 2020-05-21 12:21:15 +02:00
Koen Kanters 6e382516cb Dev 2020-05-20 16:52:49 +02:00
Koen Kanters 3046680f61 1.13.1 2020-05-20 16:52:20 +02:00
Koen Kanters f206945506 Undev 2020-05-20 16:52:04 +02:00
Koen Kanters 2e96c8b03a Update converters 2020-05-20 16:51:11 +02:00
Koen Kanters 43699e133a Update converters. 2020-05-19 20:02:26 +02:00
Ryan Kim(True-World) a293b665b4 ADD DOWON_NEW_SW (#3570)
'PM-S140-ZB': [cfg.switch],
    'PM-S240-ZB': [switchEndpoint('top'), switchEndpoint('bottom')],
    'PM-S340-ZB': [switchEndpoint('top'), switchEndpoint('center'), switchEndpoint('bottom')],
2020-05-19 19:50:24 +02:00
Koen Kanters ad9421a9b0 Update converters. 2020-05-18 18:59:15 +02:00
Koen Kanters 134f67134b Update herdsman 2020-05-17 19:11:36 +02:00
Koen Kanters c7fddbc6e3 Fix devices not discovered in Home Assistant when repaired. https://github.com/home-assistant/core/issues/35684 2020-05-17 13:45:11 +02:00
Koen Kanters 29e5b9682c Update herdsman. 2020-05-17 13:44:02 +02:00
John Doe 33bed2bbfb Add more enpoins names for validation (#3552) 2020-05-15 16:54:36 +02:00
Koen Kanters 528539214c Also respect device_options for Home Assistant device specific configuration. #3541 2020-05-14 19:03:54 +02:00
Koen Kanters 855e9e0eb1 Don't add lastSeen to state. #3545 2020-05-14 18:47:27 +02:00
Michael Barrett 845bed4e11 add energy sensor for salus SP600 (#3551) 2020-05-14 18:39:48 +02:00
Michael Barrett 8e49dab722 add energy sensor for GP-WOU019BBDWG (#3550)
Simple metering support added for device in https://github.com/Koenkk/zigbee-herdsman-converters/pull/1234
2020-05-14 18:39:30 +02:00
kjkim74andKyungJong Kim 9a28f116b1 add support ECW-100-A03 (#3538)
Co-authored-by: KyungJong Kim <kyungjong74@gmail.com>
2020-05-12 17:57:08 +02:00
Koen Kanters cb64a865d9 Add requested_brightness_level and requested_brightness_percent Home Assistant sensor for IKEA E1745. #3535 2020-05-12 17:53:45 +02:00
Koen Kanters 520f59f47c Update converters 2020-05-11 18:35:45 +02:00
relaystarandTom Seeley c88666bde7 adding RS 229 T (#3527)
Co-authored-by: Tom Seeley <tom@tomseeley.co.uk>
2020-05-11 17:46:15 +02:00
Jussi Heikkilä 24a85abcd8 GL-C-008-2ID: White endpoint color temp control in Home Assistant (#3526) 2020-05-11 17:31:33 +02:00
hamsandoandKoen Kanters 8929544a12 Added ZBHT-1 (#3522)
* Added ZBHT-1

* Update homeassistant.js

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-05-11 17:12:16 +02:00
Koen Kanters fed84cfd5e Update converters. 2020-05-09 16:32:24 +02:00
Koen Kanters 739e6fb66b Update converters. 2020-05-09 16:10:31 +02:00
Koen Kanters 2a6659582b Update herdsman. 2020-05-08 20:29:32 +02:00
Koen Kanters 3f8371bef2 Update azure-pipelines.yaml 2020-05-08 17:05:20 +02:00
Koen Kanters 3d79688ffd Update azure-pipelines.yaml 2020-05-08 16:50:46 +02:00
Koen Kanters 3795562383 More new api stuff. https://github.com/Koenkk/zigbee2mqtt/issues/3281 2020-05-07 19:41:03 +02:00
Koen Kanters f816c8e740 Update converters. 2020-05-07 19:38:01 +02:00
nukusinji b2331da671 Update homeassistant.js (#3506)
Add Support TS0601
2020-05-07 19:32:26 +02:00
Koen Kanters e7e752a032 Dont log No converter available for.. on genTime messages. #3503 2020-05-07 18:01:09 +02:00
RicoGeandKoen Kanters fe0919d02a Added Linkind Door/Window Sensor Homeassistant config (#3500)
* Added Linkind Door/Window Sensor Homeassistant config

* Update homeassistant.js

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-05-06 20:01:06 +02:00
Koen Kanters 5aedf6b2ee Fix lint 2020-05-05 13:43:37 +02:00
Koen Kanters 5244fa0ed8 Update herdsman and converters. 2020-05-05 10:42:40 +02:00
Koen Kanters 856ecf47f1 Start on new API implementation. #3281 2020-05-04 20:06:50 +02:00
Koen Kanters 772f6c0bde Update converters. 2020-05-04 15:11:17 +02:00
Arno Moonen ff61695355 Fix Home Assistant discovery for GL-FL-004TZS. See Koenkk/zigbee2mqtt#3480 (#3484) 2020-05-04 11:33:58 +02:00
Niall McAndrew 07446ce1c1 Add temp and consumption to ZNCZ02LM (#3476) 2020-05-04 11:21:49 +02:00
dramamoose 20df5e5639 Add AE 260 to homeassistant.js (#3473) 2020-05-02 13:56:16 +02:00
presslab-us 7ae77ea528 Fixes for homeassistant thermostatHeatCool (#3466)
Remove 'auto' mode for 3157100 thermostat
unit_of_measurement in JSON should be temperature_unit
2020-05-02 13:47:02 +02:00
presslab-us bf1111edcb Support leakSMART water leak sensor (#3465) 2020-05-02 13:44:36 +02:00
Markus Pfeiffer 4c57323eae Add Dresden ballast Homeassistant companion (#3452) 2020-05-02 13:33:54 +02:00
Koen Kanters 90d8326e0c Update herdsman. 2020-05-02 11:33:23 +02:00
Koen Kanters e792f8bc8c Prevent sending Home Assistant discovery messages when not connected to MQTT yet. #3451 2020-04-30 19:06:17 +02:00
Igor Gocalinski a12d9fb73e Add temp sensor for QBKG11LM switch. (#3458)
Xiaomi Wired Single Switch QBKG11LM does support temperature readout
2020-04-30 18:41:35 +02:00
swissbyteandKoen Kanters cb47c12b55 Added new device DTB-ED2004-012 and added new cfg light_switch (#3439)
* added new device and added new cfg light_switch

* Added new device DTB-ED2004-012 and added new cfg light_switch

* added cfg.switch to generic ED2004-012

* Update homeassistant.js

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-04-30 18:39:58 +02:00
Koen Kanters 26e2757df6 Update converters. 2020-04-29 21:44:26 +02:00
Koen Kanters dabc944cd3 CC2530.router: state -> led. https://github.com/Koenkk/zigbee2mqtt/issues/3414 2020-04-29 21:27:58 +02:00
575e6fd4a3 3321 fixes (#3434)
* Add home assistant mapping for hive MOT003

* fix pipeline

* remove garbage

* Added 3321 battery sensor

* Update homeassistant.js

Co-authored-by: Iain Matchett <iain.matchett@beeksfx.com>
Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-04-29 21:18:30 +02:00
matchett808-ghandIain Matchett 305cb259b3 Add home assistant mapping for hive MOT003 (#3429)
* Add home assistant mapping for hive MOT003

* fix pipeline

* remove garbage

Co-authored-by: Iain Matchett <iain.matchett@beeksfx.com>
2020-04-29 17:36:49 +02:00
Jose Luis PedrosaandKoen Kanters 04bd928f3a Add support to home assistant for ZL1000700-22-EU-V1A02 (#3448)
* Add support to home assistant for ZL1000700-22-EU-V1A02 + missing devices

* Update homeassistant.js

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-04-29 17:27:16 +02:00
Koen Kanters e0ba80249c Dev 2020-04-29 17:09:38 +02:00
Koen Kanters 55e628398b 1.13.0 2020-04-29 17:09:06 +02:00
Koen Kanters 835bba5414 Undev 2020-04-29 17:09:01 +02:00
Koen Kanters ce62f43edf Update converters. 2020-04-28 21:53:17 +02:00
Koen Kanters 7c0e1b0c65 Don't throw exception when device requets OTA but does not have OTA endpoint. #3339 2020-04-28 21:23:32 +02:00
Koen Kanters 4a6a88e0e8 Update converters. 2020-04-28 17:04:28 +02:00
Viet Dzung 89f1c709aa Support DIY DNCKAT_D001 dimmer (#3441) 2020-04-28 16:50:05 +02:00
Koen Kanters 785601476e Fix order of commands when turning bulb on. 2020-04-26 18:18:20 +02:00
dramamooseandKoen Kanters 134712322f Add support for Sengled Extra Bright A19 bulbs (#3425)
* Add support for Sengled Extra Bright A19 bulbs

* Update homeassistant.js

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-04-26 10:29:53 +02:00
Koen Kanters d8ec59bd9f Don't add coordinator to configuration.yaml. #3421 2020-04-24 22:43:35 +02:00
Koen Kanters 48641f3028 Fix OTA percentage. #3422 2020-04-24 22:38:51 +02:00
James BrechtelandKoen Kanters 265d5c4877 Support Linkind PIR motion in HA (#3423)
* Support Linkind PIR motion in HA

This marks the Linkind PIR motion sensor as having
binary_sensor_occupancy with HomeAssistant.

The sensor likely has additional capabilities like battery reporting but
I don't know how to make sense of the rest of its information yet.

* Update homeassistant.js

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-04-24 22:31:42 +02:00
Koen Kanters 63ecc1501d Update converters. 2020-04-23 22:36:17 +02:00
Jorge Schrauwen f0f7905782 Also pass settings to Extensions (#3410)
* Also pass settings to Extensions

* Swap order of settings and logger
2020-04-23 22:02:00 +02:00
Koen Kanters d073a7fc7a Fix lint. 2020-04-22 19:36:03 +02:00
Koen Kanters 4b0e427e6c Update converters. 2020-04-22 19:30:20 +02:00
Jorge SchrauwenandKoen Kanters 8d70ebd91a Don't try and load non .js extensions (#3409)
* only try and load extensions ending in .js

* Update controller.js

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-04-22 18:52:09 +02:00
freakshock88 99acd3b50f Added GL-FL-006TZ to homeassistant.js (#3408) 2020-04-21 22:31:02 +02:00
Koen Kanters f0ca71648b Pass down logger to extension. #3279 2020-04-21 22:15:12 +02:00
Koen Kanters d22e73ebb4 #3271 Allow to randomize network_key by settings 'network_key: GENERATE' 2020-04-21 21:58:43 +02:00
Philipp KolmannandKoen Kanters e1f9a3910d Update Invalid rename message format expected to be proper json (#3397)
* Update Invalid rename message format expected to be proper json

The example in the 'Invalid rename message format expected' error message, was not proper JSON and missing the last string end

* Updates

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-04-20 19:38:55 +02:00
Koen Kanters c0ed4aa9cc Update converters. 2020-04-19 20:15:08 +02:00
Koen Kanters a8793ab60b Load extensions from data directory. https://github.com/Koenkk/zigbee2mqtt/issues/3297 2020-04-19 20:08:24 +02:00
Koen Kanters 11fd5ffde6 Refactor 2020-04-19 18:10:53 +02:00
statte d00a1fed30 Update to support Zipato RGBW LED Bulb 2 (#3386) 2020-04-18 14:44:22 +02:00
Koen Kanters 9d6c7b2614 Revert "Use CMD alongside ENTRYPOINT in the Dockerfile (#3366)" (#3389)
This reverts commit d193673917.
2020-04-18 14:34:21 +02:00
Dominik 2177b33712 Add Zemismart ZM79E-DT as Home Assistant cover (#3377) 2020-04-17 16:47:59 +02:00
Jorge Schrauwen 4a771a75df Sort state/brightness to front or back depending on bulb state (#3368) 2020-04-16 21:42:47 +02:00
Koen Kanters c9298c5606 Update herdsman. 2020-04-16 21:35:19 +02:00
Koen Kanters 07dc837b76 Refactor receive 2020-04-15 22:34:59 +02:00
Koen Kanters 67151fba04 Refactor bind 2020-04-15 20:36:40 +02:00
Koen Kanters a56c5cfe50 Fix exception in Home Assistant extension when device not mapped. #3302 2020-04-15 20:03:02 +02:00
Koen Kanters 383561cbc4 Update herdsman and converters. 2020-04-15 18:16:19 +02:00
Pranas Ziaukas d193673917 Use CMD alongside ENTRYPOINT in the Dockerfile (#3366)
This allows for runtime customization, see #3362.
2020-04-15 18:07:01 +02:00
Jorge Schrauwen 62254bb67a #3352 Apply brightness_percent before others (#3361)
As mentioned, simply adding brightness_percent seems to fix the problem.

I'll look into doing the reverse if the state is off when I have more time.
2020-04-14 22:36:22 +02:00
ghostcode 85b57cd639 Fix missing color temp for ZG2819S/511.344 (#3360) 2020-04-14 22:31:23 +02:00
Koen Kanters 838cb6e702 Update converters. 2020-04-13 21:15:08 +02:00
simonses1andKoen Kanters 38acbb0234 Update homeassistant.js (#3349)
added HALIGHTDIMWWE14 for HA discovery
https://github.com/Koenkk/zigbee-herdsman-converters/pull/1153 for converter PR

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-04-13 17:36:49 +02:00
Koen Kanters 74aefcca76 Don't log no converter warning for genOta messages. #1620 2020-04-13 17:18:45 +02:00
Koen Kanters 5c3cd99288 Update converters. 2020-04-13 11:40:43 +02:00
Koen Kanters 121eaf3dcb settingUp -> queue. https://github.com/Koenkk/zigbee2mqtt/commit/eab988640281d60deef827a2692a2f0a01578a3f#r38455677 2020-04-13 11:28:19 +02:00
Koen Kanters 22126a3e5d Refactor 2020-04-12 20:32:14 +02:00
Koen Kanters eab9886402 Refactor. 2020-04-12 18:29:52 +02:00
Koen Kanters bab71fb5ea Refactor 2020-04-12 17:04:47 +02:00
Koen Kanters 29762b2720 Update converters. 2020-04-12 10:19:12 +02:00
TePazz edab607f7d Add thermostat Stelpro SMT402AD and new code for ST218 (#3341) 2020-04-12 10:09:31 +02:00
Koen Kanters 0aedbe0db3 Merge remote-tracking branch 'origin/master' into dev 2020-04-12 10:07:37 +02:00
Koen Kanters bd5cb7790a Only subsribe to legacy topic when enabled. 2020-04-11 20:59:52 +02:00
Koen Kanters a2d09b08ea Refactor DeviceConfigure 2020-04-11 20:58:22 +02:00
Koen Kanters 0cc834b4b6 Fix tests 2020-04-11 20:47:25 +02:00
Koen Kanters 10a47df33b Refactor 2020-04-11 20:45:50 +02:00
Koen Kanters 9da1a35bbd Refactor. 2020-04-11 20:34:50 +02:00
Koen Kanters cc008db2ad Refactor 2020-04-11 18:31:57 +02:00
Koen Kanters ba0d930ddd DeviceAvailability -> Availability 2020-04-11 18:14:40 +02:00
Koen Kanters b8b4ff9ee7 baseExtension -> extension 2020-04-11 18:10:56 +02:00
Koen Kanters 1573687979 Refactor deviceAvailability.js 2020-04-11 18:04:00 +02:00
Koen Kanters 2ce2876f04 Refactor 2020-04-11 17:44:31 +02:00
Koen Kanters e1ec16042f GreenPower devices don't support a network scan. #3322 2020-04-11 17:11:09 +02:00
Koen Kanters 911cd58ef2 Update ISSUE_TEMPLATE.md 2020-04-11 16:43:54 +02:00
Koen Kanters 4cc0e5d88e Update herdsman. #3238 2020-04-11 16:24:58 +02:00
Koen Kanters 2dcc74f9c6 Update herdsman. 2020-04-11 15:20:15 +02:00
Koen Kanters 4f81b7aa0b Refactor 2020-04-11 15:18:17 +02:00
Koen Kanters 2d66145c6e Update converters. 2020-04-10 18:12:25 +02:00
Koen Kanters 7824f102c8 Update herdsman and converters. 2020-04-09 22:01:09 +02:00
Koen Kanters 4b6add19d5 GreenPower defintions. (#3321) 2020-04-09 21:54:26 +02:00
Koen Kanters 637ad8d2e6 Update converters. 2020-04-09 20:02:59 +02:00
Koen Kanters 6857f2ad5e Don't setup reporting for TS0001. #3311 2020-04-09 20:00:24 +02:00
Koen Kanters 272892b112 Merge branch 'master' into dev
# Conflicts:
#	npm-shrinkwrap.json
#	package.json
2020-04-09 17:52:52 +02:00
Koen Kanters 7d27a54f8f 1.12.2 2020-04-09 17:48:12 +02:00
Koen Kanters e1355aa2e0 Update herdsman 2020-04-09 17:48:08 +02:00
mario-1024andKoen Kanters 2c2af0603b Add Schwaiger ZHS-15/SPW35Z-D0 power socket (#3313)
Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-04-08 19:12:34 +02:00
Koen Kanters 3f058c317c Dev 2020-04-08 17:57:44 +02:00
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
Koen Kanters 31e56785e4 1.11.0 2020-02-26 18:25:39 +01:00
Koen Kanters 962282b38c Undev 2020-02-26 18:25:36 +01:00
Koen Kanters e241d5ac8a Update converters. 2020-02-26 18:22:36 +01:00
Koen Kanters 1a973d0cd7 Update converters. 2020-02-26 17:30:38 +01:00
Koen Kanters 11ec191580 Don't discover illuminance_lux for RTCGQ11LM. https://github.com/Koenkk/zigbee-herdsman-converters/issues/1017 2020-02-26 17:20:31 +01:00
Koen Kanters 95788b8847 Discover illuminance_lux sensor. 2020-02-25 20:37:42 +01:00
Koen Kanters a36f11a4fb Update converters. 2020-02-25 20:20:52 +01:00
Koen Kanters 9cc84feb67 Allow to rename groups through zigbee2mqtt/bridge/config/rename. https://github.com/Koenkk/zigbee2mqtt/issues/2991 2020-02-23 21:51:30 +01:00
Koen Kanters dd82b29629 Update converters. https://github.com/Koenkk/zigbee2mqtt/issues/2967 2020-02-23 20:47:38 +01:00
Koen Kanters 2a9d0d1875 Update converters. https://github.com/Koenkk/zigbee2mqtt/issues/2921 2020-02-23 20:26:13 +01:00
Koen Kanters 66173ff689 Update herdsman. 2020-02-23 20:02:29 +01:00
Koen Kanters 645da4e3c0 Update herdsman. 2020-02-23 19:01:02 +01:00
shades684 409df4c193 Matches this pull request: https://github.com/Koenkk/zigbee-herdsman-converters/pull/1010 (#2988) 2020-02-23 13:33:30 +01:00
Koen Kanters aca32e2f02 Update converters. 2020-02-22 19:03:06 +01:00
Koen Kanters 79116a1158 Fix Hue bulbs in a group controlled by a Hue dimmer not reporting off state. #2882 2020-02-22 18:45:30 +01:00
Koen Kanters ad59ff57bc Also remove group from herdsman on remove. #2265 2020-02-22 15:53:05 +01:00
Koen Kanters df67c429bf Undiscover ota_update sensor on device remove. 2020-02-22 00:32:15 +01:00
Koen Kanters 6b5b4ab433 Log when update is availabe. https://github.com/Koenkk/zigbee2mqtt/commit/58d987b52328a40b6ac92f343f3e8ceeae3f2a10#r37363068 2020-02-20 20:01:26 +01:00
Koen Kanters c25c32f1be Update converters. 2020-02-19 22:12:25 +01:00
Koen Kanters 9b644ff82d Update herdsman. 2020-02-19 21:46:25 +01:00
Koen Kanters 0289a6c30d Update converters. 2020-02-18 22:07:34 +01:00
Koen Kanters 2b3cdebe41 Fix AC08559 missing Home Assistant colorxy mapping. #2966 2020-02-18 22:05:32 +01:00
Takisg 6ef4fac30a GL-C-007S (#2955)
Gledopto GL-C-007S

Add support for Gledopto GL-C-007S
Zigbee LED controller RGBW plus model
2020-02-17 20:15:57 +01:00
Koen Kanters f0903cd02c Discover action sensor for WXKG11LM. #2953 2020-02-16 20:55:40 +01:00
Koen Kanters 58d987b523 Implement update_available attribute and discover Home Assistant sensor. #2948 2020-02-16 16:00:15 +01:00
Koen Kanters 9a87abd0f4 Update herdsman and converters. 2020-02-15 16:39:35 +01:00
timstanley1985andKoen Kanters b379830e36 Log ota message to MQTT (#2936)
* Log ota message to MQTT

* Fix lint

* Amend MQTT log messages

* Fix typo

* Fix lint

* some changes.

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-02-14 23:41:34 +01:00
Koen Kanters 97af26b340 Also poll hue bulbs on button 1/2 press of Hue dimmer switch. #2882 2020-02-14 22:41:04 +01:00
rbrack42 7de51340a0 Adding support for Sylvania 72567 Flushmount Light (#2943) 2020-02-14 16:52:07 +01:00
Koen Kanters bbf432eae5 Update herdsman and herdsman-converters. 2020-02-13 21:35:37 +01:00
Koen Kanters eac15a748a npm ci. https://github.com/Koenkk/zigbee2mqtt/issues/2918 2020-02-13 21:31:14 +01:00
Koen Kanters 87faaa1817 Don't crash when devices doesn't respond to read modelID after update. https://github.com/Koenkk/zigbee2mqtt/issues/2921 2020-02-13 21:10:44 +01:00
Koen Kanters 984bad4cb3 Major OTA improvements. https://github.com/Koenkk/zigbee2mqtt/issues/2921 2020-02-09 20:44:37 +01:00
Koen Kanters 13b996eb70 Update converters. 2020-02-08 23:41:22 +01:00
Ricardo Pereira fb7c3a31dd Adding availability support to Commercial Electric Downlight model 53170161 (#2922) 2020-02-08 23:23:44 +01:00
Boris PrüßmannandKoen Kanters 06b6d66090 Feedback requested: add polling for commandOn & commandOff (#2730)
* Add polling for commandOn & commandOf.

When using groups together with devices that do not support reporting, this is needed
to have the new state reflected.

* Update deviceReport.js

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-02-08 20:53:16 +01:00
Koen Kanters 3d897c55e2 v2.7.0 rocks. 2020-02-08 20:50:07 +01:00
Koen Kanters c5fb651481 Try with v2.8.0 2020-02-08 20:46:26 +01:00
Koen Kanters 7d52a013ad Something wrong with the alpine 12 image? 2020-02-08 20:27:28 +01:00
Koen Kanters e278bb0145 Downgrade node. 2020-02-08 20:20:27 +01:00
Koen Kanters b36da25d68 Attempt to fix Docker build. 2020-02-08 20:17:13 +01:00
Koen Kanters 83291e242e OTA https://github.com/Koenkk/zigbee-herdsman/issues/60 (#2920)
* ota

* Bla

* Update converters.
2020-02-08 19:55:26 +01:00
Koen Kanters 99dc214fbe Update herdsman. 2020-02-07 19:50:48 +01:00
Koen Kanters 5e152f2ce4 Promote to dev. 2020-02-05 21:45:47 +01:00
Koen Kanters 8df6be8813 1.10.0 2020-02-05 21:41:31 +01:00
Koen Kanters 415e764592 Undev 2020-02-05 21:40:58 +01:00
Koen Kanters e8d9cbc19b Update converters. 2020-02-05 21:38:42 +01:00
svh1985 e473590dd9 Added log_file name setting (#2894)
* Added log_file name setting

Added log_file to schema while preserving the default log.txt setting.
Added option to logger to use the filename and support for the %timestamp% var.

* Update logger.js

Added the filename to the console/log output.
2020-02-05 19:37:13 +01:00
Koen Kanters 558153ebd6 Update converters. 2020-02-04 20:28:47 +01:00
Koen Kanters a07a28cb65 Update herdsman. 2020-02-02 21:05:25 +01:00
Koen Kanters 6090f124c0 Update converters. 2020-02-02 14:30:53 +01:00
Koen Kanters 5d8a9a3e51 Update converters. 2020-02-01 17:35:20 +01:00
Koen Kanters 313edcc445 Keep latest log in log.txt (not in log1.txt, etc.). https://github.com/Koenkk/zigbee2mqtt/issues/2855 2020-01-31 23:13:15 +01:00
Koen Kanters 4926fb85ae Await permit join before continuing with startup. https://github.com/Koenkk/zigbee2mqtt/issues/2617 2020-01-31 22:52:39 +01:00
Koen Kanters 0111681cb7 Update converters. https://github.com/Koenkk/zigbee2mqtt/issues/2850 2020-01-31 22:42:24 +01:00
Koen Kanters 9bc427e32f Update converters. 2020-01-31 21:05:13 +01:00
Koen Kanters 36e39e2f02 Update herdsman. 2020-01-31 20:31:02 +01:00
Rob Long 58e08d1443 Update homeassistant.js (#2861)
Added 5900131C5
2020-01-31 16:27:46 +01:00
Koen Kanters 2e19a8f916 Update converters. 2020-01-30 20:08:31 +01:00
Koen Kanters 5488504809 Update converters. 2020-01-29 21:38:37 +01:00
Michal Szymura 82fb79820a Added support for Sengled E11-U2E (#2853) 2020-01-29 21:21:22 +01:00
Koen Kanters c87ccea9ba Update converters. 2020-01-29 18:34:40 +01:00
Koen Kanters b6cb7acf7e Update converters. 2020-01-27 22:20:48 +01:00
Markus Peter ad286cbbc6 Home assistant config for Philips Hue Discover 17435/30/P7 (#2834) 2020-01-27 21:48:04 +01:00
Koen Kanters fe62ceb0f9 Add unbind for default_bind_group. https://github.com/Koenkk/zigbee2mqtt/issues/2772 2020-01-27 20:56:11 +01:00
Koen Kanters 61a3f0e839 Update converters and fix tests for real. 2020-01-26 21:38:04 +01:00
Koen Kanters b58cbd4883 Fix tests. 2020-01-26 19:57:15 +01:00
a-bailey 833bfcd81a added home assistant extension for LS12128 (#2825) 2020-01-26 19:44:44 +01:00
Philipp Bender 9e413bf35a Added homeassistant mapping for OSRAM A60 DIM Z3 (#2824) 2020-01-26 19:39:43 +01:00
Koen Kanters 3c28ed8f0b Update herdsman. https://github.com/Koenkk/zigbee2mqtt/issues/2749 2020-01-26 19:21:30 +01:00
Koen Kanters 20ba6a5274 Add icon and unit to Home Assistant linkquality sensor. #2806 2020-01-25 20:43:51 +01:00
Koen Kanters bd30b0b4a3 Update converters. 2020-01-25 20:00:22 +01:00
Koen Kanters 93e96a2e5e Update converters. 2020-01-23 21:00:50 +01:00
Koen Kanters e1d51e6171 Fix error when configure section of device is removed. 2020-01-23 20:42:10 +01:00
Marco AddarioandKoen Kanters cb855373ac Added support for Linkind Smart Zigbee LED (#2804)
* Added support for Linkind Smart Zigbee LED

Added support for Linkind Smart Zigbee LED bulb
( https://www.linkind.com/product-page/smart-zigbee-led-9w-a19-bulb-dimmable-tunable-hub-required-alexa-control )

* Update homeassistant.js

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-01-23 19:51:41 +01:00
Koen Kanters 145f8a577d Update converters. 2020-01-22 21:34:15 +01:00
Koen Kanters 0d3fa83ab1 Update herdsman. 2020-01-22 20:52:12 +01:00
Koen Kanters dae52a22d7 Update converters. 2020-01-21 21:19:11 +01:00
Koen Kanters e94b34caad Update converters. 2020-01-20 21:36:19 +01:00
wrcvr4andKoen Kanters 43c745df1d Support NUET56-DL27LX1.2 (#2784)
* Support DL27LX1.2

* Update homeassistant.js

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-01-20 17:48:33 +01:00
Koen Kanters 2e958f863f Update herdsman. 2020-01-18 23:05:05 +01:00
Koen Kanters 3b1ef5179b Update herdsman. 2020-01-18 20:27:53 +01:00
Koen Kanters ae5330d090 Update converters. 2020-01-17 22:51:37 +01:00
Twan Coenraad dd0ca2a392 Add keepalive option for MQTT (#2767) 2020-01-17 21:38:46 +01:00
Koen Kanters 39ed95371e Log when using non-valid log_level. #2706 2020-01-16 23:33:17 +01:00
Koen Kanters 3f6a95bc0b Don't setup reporting for BASICZBR3 as it doesn't support it. #2740 2020-01-16 22:52:13 +01:00
Koen Kanters 42f1a37499 Promote to dev 2020-01-16 22:44:11 +01:00
Koen Kanters 287f843bbb 1.9.0 2020-01-16 22:32:17 +01:00
Koen Kanters cd4319d281 Remove dev from version. 2020-01-16 22:32:13 +01:00
Viet DzungandKoen Kanters 2188937eea Home Assistant 0.104 breaking change: support new HA separate lock state (#2753)
* Support new HA separate lock state for Xiaomi ZNMS12LM and ZNMS12LM

https://github.com/home-assistant/home-assistant/pull/29808

* Update homeassistant.js

* Update homeassistant.js

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-01-16 22:25:58 +01:00
Koen Kanters a9cce7c222 Update converters. 2020-01-16 21:27:28 +01:00
jungmonam f9d85df51b Update homeassistant.js (#2758) 2020-01-16 21:17:55 +01:00
Ashton Kemerling 64315d0fc9 Home assistant bindings for Sylvania 72569 (#2754)
* Home assistant bindings for Sylvania 75269

Related to https://github.com/Koenkk/zigbee-herdsman-converters/pull/913.

* Fix Typo (Again)

Replace 75269 with 72569
2020-01-16 21:15:19 +01:00
MrNickllandKoen Kanters eba84647c1 Update TH1123ZB Home Assistant config (#2752)
* Update homeassistant.js

Added config parameters for Sinope TH1123ZB line voltage thermostat:
- Keypad lockout using the code for Stelpro thermostats.
- Power sensor.

* Update homeassistant.js

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-01-16 21:08:14 +01:00
Boris Prüßmann 7d268732de Let ubisys devices expose power consumption via Home Assistant (#2743) 2020-01-15 12:58:03 +01:00
Boris PrüßmannandKoen Kanters a79b2bae81 Add support for Philips Fair Hue ceiling light (#2742)
* Added endpoints for Busch-Jaeger

* Added RM01 to homeassistant.js

* Updated mapping to reflect latest change in converter

* Renamed endpoint according to converted PR

* Support for Philips Hue Fair

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-01-15 12:57:08 +01:00
Koen Kanters 5c18734e68 Update converters. 2020-01-14 19:06:35 +01:00
Boris PrüßmannandKoen Kanters 2234fd1e8a Added endpoints for Busch-Jaeger (#2723)
* Added endpoints for Busch-Jaeger

* Added RM01 to homeassistant.js

* Updated mapping to reflect latest change in converter

* Renamed endpoint according to converted PR

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-01-14 18:47:32 +01:00
Koen Kanters 80838bd248 Update converters. 2020-01-13 22:09:21 +01:00
lukeIamandKoen Kanters 4a0059afcd Allow attribute and json in parallel (#2712)
* Allow attribute and json in parallel

* Fix tests

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-01-12 15:07:06 +01:00
Martin Raatz 4a14706638 adding support for LUPUS - 1 chanel relay with ZigBee (#2711) 2020-01-12 14:31:06 +01:00
Koen Kanters 9890fb3ae2 Update herdsman and converters. 2020-01-11 18:04:30 +01:00
jungmonam 15d984e21b Update homeassistant.js (#2720) 2020-01-11 16:20:45 +01:00
Koen Kanters 57a5253203 Discovery battery sensor for E1744. #2715 2020-01-11 16:17:22 +01:00
TilmanK 7a8bef3e60 Fixed check if entity is of type "device" in deviceConfigure.js. (#2713)
The current statement (!entity.type === 'device') will always evaluate to false since it compares a boolean to a string.
2020-01-11 15:50:00 +01:00
Daniel Chesterton 77fc851236 Update Docker to Node 12 and use multistage builds to reduce image size (#2703) 2020-01-11 15:11:27 +01:00
Koen Kanters e76633519f Update converters. 2020-01-09 22:10:16 +01:00
Roberto Barbero a652df6ed7 Added Sinope TH1400ZB and TH1500ZB (#2708)
Added for Home Assistant MQTT autodiscovery
2020-01-09 21:56:03 +01:00
Koen Kanters cb0b0b5af9 Clear Home Assistant MQTT discovery on device remove. #2678 2020-01-09 21:47:19 +01:00
Koen Kanters 3a463b0782 Update converters. 2020-01-08 20:06:01 +01:00
TilmanKandKoen Kanters 0df966755c Corrected several typos in "Successfully" within log messages (#2697)
Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-01-08 19:29:22 +01:00
Daniel Chesterton 94d0253f27 Update availability_blacklist and availability_whitelist to allow for friendly names (#2684) 2020-01-08 18:02:49 +01:00
Jevgeni Kiski 4ee34fd637 LLKZMK11LM Supports power, temperature and consumption (#2657)
* LLKZMK11LM Supports power, temperature and consumption

LLKZMK11LM already sends power, temperature and consumption in mqtt json.

```
info  2020-01-02 20:06:20: MQTT publish: topic 'zigbee2mqtt/front_outdoor_lights', payload '{"state_l1":"ON","linkquality":54,"state_l2":"OFF","power":35.1,"consumption":2.89,"temperature":33}'
```

Not sure in which units `consumption` is. Not adding right now.

* LLKZMK11LM power consumption

* Linter

* mdi-flash
2020-01-08 17:57:40 +01:00
Carl de Billy cabb1f3979 Added <operation>_failed logging (#2636)
* Added <operation>_failed logging
for external tools (like Zigbee2MqttAssistant), this will allow the tool to know when an operation is failed.
https://github.com/Koenkk/zigbee2mqtt/issues/2223

* Added _failed logging to binding operations too

* Added _failed to group operations
2020-01-07 21:06:48 +01:00
Koen Kanters 8a72916d7d Update converters. 2020-01-07 20:08:12 +01:00
Koen Kanters c041f0cddc Ignore setup reporting for closuresWindowCovering ZNLDP12LM. #2611 2020-01-07 19:59:43 +01:00
Koen Kanters 6245c729cf Update converters. 2020-01-06 21:55:43 +01:00
Carl de BillyandKoen Kanters e5b2f71fcd Added support for Stelpro Ki & Stelpro Maestro (#2628)
* fix potential null exception

* Added support for Stelpro Ki

* Stelpro Ki: Added support for action_mode

(cherry picked from commit 0f740f1aedbedb28d64245531f10a9bfd985e49b)

* Stelpro Ki: fix "lock" status update

(cherry picked from commit 6ac94411183d92d1f658a7d17a724e50587b8571)

* Fixed lint issues

* Stelpro: Fixed local_temperature sensor

* Added support for Stelpro Maestro

* Fix lint

* HASS: Fixed support for action_topic/action_template

* Prevent a non supported device from causing a null-ref

* Update naming.

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-01-06 21:36:45 +01:00
Koen Kanters d0e9889f7d Fix race condition when Zigbee starts. #2591 2020-01-03 23:43:04 +01:00
Koen Kanters d3aba2689c Update converters. 2020-01-03 23:29:28 +01:00
jasperroandKoen Kanters 7a6d5f9a42 Added hue/saturation mode and tamper to home assistant (#2603)
* Added hue/saturation mode to home assistant extension

* Added tamper to homeassistant

* Fix ESlint stuff

* Update homeassistant.js

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-01-03 22:28:21 +01:00
AThomsenandKoen Kanters 89fb54d5c8 Add Nordtronic Box Dimmer 2.0 98425031 (#2629)
* Add Nordtronic Box Dimmer 2.0 98425031

* Update homeassistant.js

Co-authored-by: Koen Kanters <koenkanters94@gmail.com>
2020-01-03 18:55:57 +01:00
Samuel Gaus afaed3f783 Support new IKEA GUNNARP round panel (#2653)
See: https://github.com/Koenkk/zigbee-herdsman-converters/pull/865
2020-01-03 09:09:28 +01:00
Kryzek dc6bf51b8e Update homeassistant.js (#2651)
Expose battery information to Home Assistant with couple of Trust battery-powered sensors.
Related to https://github.com/Koenkk/zigbee-herdsman-converters/pull/856
2020-01-03 09:04:21 +01:00
Koen Kanters 5f97f19d7f Add brightness_move for groups. #2620 2019-12-31 13:52:23 +01:00
Jack Wilsdon f04e01ff54 Use correct Home Assistant configuration for GL-S-007Z (#2616) 2019-12-27 15:56:24 +01:00
Koen Kanters f069a7e58e Update herdsman and converters. 2019-12-26 22:46:44 +01:00
Phi Dong 2197d4127d Update homeassistant.js (#2606)
Add support for Ecosmart-ZBT-A19-CCT-Bulb (A9A19A60WESDZ02) to Home Assistant
2019-12-26 21:32:34 +01:00
Martin Brooksbank 89fe701197 Added Ajax Online LED Strip HomeAssistant Mapping (#2592) 2019-12-23 21:08:40 +01:00
Koen Kanters e63d196966 Skip configure when device does not require it. https://github.com/Koenkk/zigbee2mqtt/issues/2588 2019-12-23 20:48:37 +01:00
fb22 9db1467ed8 Add 4023330P7 (#2574)
Add support for Philips Hue white suspension Amaze
2019-12-23 20:08:43 +01:00
Anthony Lavado 3bab32c1d7 Add support for the EcoSmart D1533 (#2570) 2019-12-23 19:56:55 +01:00
Koen Kanters 66b3bcb639 Update herdsman. 2019-12-19 21:52:45 +01:00
Koen Kanters 6f7d29392e Update herdsman and converters. 2019-12-17 21:35:47 +01:00
Koen Kanters 83e10f446e Update converters. 2019-12-17 19:59:22 +01:00
Koen Kanters af4184e3ff Always log 'No converter available...` to debug. #2543 2019-12-17 19:19:57 +01:00
Koen Kanters 316755a5c8 Fix get device group membership with friendly_name containing slashes. #2546 2019-12-17 19:02:11 +01:00
Wilmar den Ouden 5083bbcc16 feat: create environment variable for the config file (#2519)
Signed-off-by: wilmardo <info@wilmardenouden.nl>
2019-12-16 20:49:25 +01:00
Koen Kanters 981612c64c Support tint_scene for group. https://github.com/Koenkk/zigbee-herdsman-converters/issues/281 2019-12-16 20:17:58 +01:00
Koen Kanters 960f9e44ad Update herdsman. 2019-12-15 20:11:22 +01:00
Koen Kanters 8545a341c9 Promote to dev 2019-12-15 20:04:10 +01:00
Koen Kanters da4d26af62 1.8.0 2019-12-15 17:33:54 +01:00
Koen Kanters f64bf16f6f Update converters. 2019-12-15 16:37:00 +01:00
Koen Kanters 0b9997b7a5 Update converters. 2019-12-15 15:55:10 +01:00
mailq 6f33529c79 Add GL-S-005Z RGBW GU5.3 MR16 (#2533) 2019-12-15 15:07:31 +01:00
Koen Kanters 1972eb450c Update converters. 2019-12-13 19:25:22 +01:00
Markus Pfeiffer f4f910f014 Support for Hive Thermostatic Radiator Valve (#2517) 2019-12-13 19:18:34 +01:00
Wilmar den Ouden 087d1b8761 fix: avoid creating the log/ directory when file not enabled (#2516)
Signed-off-by: wilmardo <info@wilmardenouden.nl>
2019-12-13 19:09:18 +01:00
Timo S 4334e01759 temp_step attribute for climate entities (#2515) 2019-12-13 19:00:02 +01:00
Koen Kanters 6fd059967a Support setting cover position and thermostat occupied heating setpoint via group. #2505 2019-12-13 18:26:03 +01:00
Koen Kanters 61f5776310 Update converters. 2019-12-12 20:55:57 +01:00
stumps444 3f2d50900d Added support for Lockwood keyless deadbolt (#2506) 2019-12-12 20:02:41 +01:00
Koen Kanters be601cffb0 Update herdsman and converters. 2019-12-11 21:54:16 +01:00
Koen Kanters 6b7bd9da37 Re-add model to device information. #2497 2019-12-11 20:15:42 +01:00
Koen Kanters 3a9dfb04a7 Bind closuresWindowCovering. https://github.com/Koenkk/zigbee2mqtt/issues/2496 2019-12-11 20:00:09 +01:00
Thomas Jager 67f8e97b12 Add namron dimmer - homeassistant extension (#2494)
https://github.com/Koenkk/zigbee-herdsman-converters/pull/808
2019-12-11 19:41:06 +01:00
Koen Kanters 37089e440a Update herdsman. 2019-12-11 19:08:22 +01:00
Koen Kanters d17eec5310 Don't allow postfix to be a friendly_name. #2486 2019-12-09 18:27:39 +01:00
Jorge Schrauwen bcf79a7e34 Device Availability: Allow battery devices to report offline/online based on device.lastSeen (#2464)
* Remove execution bits for deviceReceive.js

* deviceAvailability.isPingable should return true if 'availability_lastseen_timeout' is set for device

* deviceAvailability.handleInterval should know how to handle lastseen_timeout setting

* Allow availability_lastseen_timeout for all devices

* Use a default lastseen timeout of 24h

* Updates

* Updates

* Updates

* 25 hours instead of 24.
2019-12-09 18:12:13 +01:00
Koen Kanters 6bd9e74e0c Fix tests 2019-12-08 16:52:23 +01:00
dusanmsk 6aad019328 mqtt listener to rename last paired device. (#2478)
* mqtt listener to rename last paired device.
send zigbee2mqtt/bridge/config/rename_last with payload containing new name and last paired device will be renamed

* Updates
2019-12-08 16:50:18 +01:00
Sven Lankes d05a3a066a add support for Mueller Licht 44435 Tint LED Stripe (#2483) 2019-12-08 14:11:27 +01:00
Koen Kanters 5440aadec0 Log remove docs on failure. #2477 2019-12-07 17:57:39 +01:00
Koen Kanters be30067a39 Let devices only report when there is a change. #2424 2019-12-07 17:54:40 +01:00
Koen Kanters 17560ca885 Check if state is not null. #2450 2019-12-07 17:45:00 +01:00
Marius e00dbbf4a9 Support Hue Go with Bluetooth LCT026 (7602031P7) (#2474) 2019-12-07 17:29:37 +01:00
Koen Kanters 33201367f1 Update herdsman and converters. 2019-12-05 21:33:28 +01:00
Jaron Viëtor 60627ab6e3 Added support for accepting hex color on deviceName/set/color MQTT topic (#2441)
* Added support for accepting hex color on deviceName/set/color MQTT topic

* Update entityPublish.js
2019-12-04 21:23:46 +01:00
Koen Kanters 88a1c2884a Update herdsman and converters. 2019-12-04 21:12:27 +01:00
Koen Kanters a53a19026c Add extra logging when publish to device fails. #2450 2019-12-04 20:46:19 +01:00
Koen Kanters 1459ffea7a Publish availabilty when non pinagable device joins. #2452 2019-12-04 20:21:14 +01:00
Koen Kanters ba26887ea5 Update converters and herdsman. 2019-12-03 20:11:45 +01:00
Wilmar den Ouden 694c45fd96 Make logging transports configurable (#2231)
* feat: Make logging optional

Signed-off-by: wilmardo <info@wilmardenouden.nl>

* feat: be more verbose about what logging is enabled

Signed-off-by: wilmardo <info@wilmardenouden.nl>

* feat: adds tests

Signed-off-by: wilmardo <info@wilmardenouden.nl>

* Updates.

* Updates

* fix tests.

* Remove onlythis.

* Remove another onlythis

* Improve test stability

* Remove another onlythis
2019-11-29 23:36:57 +01:00
Koen Kanters 5e165810ec Allow to configure manually. https://github.com/Koenkk/zigbee2mqtt/issues/2365 https://github.com/Koenkk/zigbee-herdsman-converters/issues/779#issuecomment-559598591 2019-11-29 09:43:59 +01:00
Koen Kanters 99fd93f9a7 Allow setting transmit power. https://github.com/Koenkk/zigbee2mqtt/issues/2253 2019-11-27 22:02:49 +01:00
Koen Kanters c2be95777f Mark nodejs 10, 12 and 13 as supported. #2423 2019-11-27 20:02:18 +01:00
Koen Kanters acce25737f Update converters. 2019-11-27 19:57:25 +01:00
Koen Kanters 134f86a580 Update herdsman. 2019-11-27 18:49:41 +01:00
Koen Kanters 2a81a54609 Stop pinging device when removed. #2419 2019-11-27 18:14:39 +01:00
Koen Kanters 2fcddb5ad5 Update herdsman. 2019-11-26 21:24:41 +01:00
Koen Kanters ac0291f09c Update herdsman. 2019-11-26 20:08:45 +01:00
Koen Kanters 7d1635aff8 Update converters. 2019-11-25 18:39:12 +01:00
Koen Kanters 6c56c95e3f Always make endpoint 1 the coordinator endpoint. 2019-11-25 17:44:44 +01:00
Koen Kanters d37d9ee859 Factory reset device through Touchlink. 2019-11-23 20:44:23 +01:00
Koen Kanters e179e053ce Update herdsman and converters. 2019-11-23 20:19:38 +01:00
Koen Kanters 546a72ff53 Update dependencies. 2019-11-23 12:07:23 +01:00
Koen Kanters c9122eecda Update gitignore. 2019-11-23 12:07:07 +01:00
Kryzek 46d7176976 availability_whitelist (#2387)
* availability_whitelist

* Tests

* Cleanup

* Update deviceAvailability.js
2019-11-23 11:47:37 +01:00
Hans-Wilhelm Warlo 2df1acf532 Return false when mappedDevice is falsy (#2383) 2019-11-22 07:48:11 +01:00
himpich c5bd3a2450 Add support for Innr FL 130 C Color LED Strip - homeassistant extension (#2377) 2019-11-21 20:26:10 +01:00
frontend89 260d2904f3 Add device specific configuration option: debounceIndexes (#2370)
* Add device specific configuration option: debounceIndexes

* Rename debounceIndexes to debounce_ignore

* Lint
2019-11-20 21:21:23 +01:00
Koen Kanters 8ae57e7ef0 Update herdsman and converters. 2019-11-20 20:08:30 +01:00
Koen Kanters b23276f7f3 Re-configure when device rejoins. https://github.com/Koenkk/zigbee-herdsman-converters/issues/758 2019-11-20 19:06:04 +01:00
Koen Kanters fdc8fcc02b Allow to specify endpoint via property. #2356 2019-11-20 17:36:36 +01:00
Koen Kanters ef16fcd505 Fix tests. 2019-11-20 17:35:49 +01:00
Koen Kanters c5898598ae Fix json_attributes_topic discovery for climate. https://github.com/Koenkk/zigbee2mqtt/issues/2321 2019-11-19 20:50:55 +01:00
Koen Kanters 461544ed6a Update converters. 2019-11-18 21:34:23 +01:00
Koen Kanters 661b2f1cc0 Home Assistant: discover json_attributes_topic for all MQTT device types. https://github.com/Koenkk/zigbee2mqtt/issues/2321 2019-11-18 18:14:22 +01:00
Koen Kanters eea660374f Use correct endpoint for binding dimmer. https://github.com/Koenkk/zigbee2mqtt/issues/2343 2019-11-18 17:54:28 +01:00
Kryzek 878a88632b Customizable timestamp (#2357)
* Customizable timestamp

Add a customizable timestamp

* Revert "Customizable timestamp"

This reverts commit 7ae06e8e2c.

* Customizable timestamp

* Update settings.js
2019-11-17 21:29:53 +01:00
Koen Kanters 22c8f14659 Update herdsman and converters. 2019-11-17 21:22:24 +01:00
Koen Kanters d2c4133e56 Update herdsman. 2019-11-16 13:52:49 +01:00
Koen Kanters 44db557a0c Log in local timezone. https://github.com/Koenkk/zigbee2mqtt/issues/2341 2019-11-15 23:04:23 +01:00
胡明春 31246efc64 Add UI support to 'S31 Lite zb' and SA-003-Zigbee (#2340)
* Add UI support to 'S31 Lite zb' and SA-003-Zigbee

* Update homeassistant.js
2019-11-15 22:55:49 +01:00
Koen Kanters a7486d723f Update herdsman converters. 2019-11-14 20:43:20 +01:00
Koen Kanters e33b49e2ff Update herdsman and converters. 2019-11-12 19:40:52 +01:00
Koen Kanters e51ed89641 Promote to dev. 2019-11-12 18:50:38 +01:00
Koen Kanters b459c35219 1.7.1 2019-11-12 18:47:59 +01:00
Koen Kanters d8512c73df Fail gracefully when state retrieval fails after device reconnects. #2318 2019-11-11 19:25:11 +01:00
Koen Kanters fdcaaee955 Fix typo. 2019-11-11 17:45:11 +01:00
Koenkk e2858dc90f Fix topic postfix detection having number. #2309 2019-11-11 17:36:33 +01:00
Jorge Schrauwen 3dbf454d07 Fix minor type in entityPublish.js (#2311) 2019-11-11 17:27:26 +01:00
Koen Kanters fc98b951ff Update herdsman. 2019-11-10 22:31:37 +01:00
Koen Kanters 0b0a9bca4d Update converters. 2019-11-10 19:53:37 +01:00
Jorge Schrauwen be1c81a778 #2296 only publish /availability if the state has changed (#2303) 2019-11-10 17:56:01 +01:00
Koen Kanters b61723923e Promote to 1.7.0+dev. https://github.com/Koenkk/zigbee2mqtt/issues/2263 2019-11-09 21:04:38 +01:00
Koen Kanters 551a58a4a4 1.7.0 2019-11-09 20:40:40 +01:00
Koen Kanters d562541178 Shepherd -> herdsman. 2019-11-09 20:38:47 +01:00
Koen Kanters 720e3930e3 Update herdsman converters. 2019-11-08 18:59:27 +01:00
Koen Kanters 6c453738d4 Update herdsman and converters. 2019-11-07 18:28:17 +01:00
Koen Kanters 6245c6a59f Don't log link to how to support new devices when receiving message without converter. 2019-11-07 18:27:47 +01:00
Koen Kanters dcf1c83a25 Fix tests for real now. 2019-11-07 17:48:03 +01:00
Koen Kanters 2b7d9e6ee7 Fix tests. 2019-11-06 22:08:33 +01:00
Koen Kanters 019b087af1 Fix tests. 2019-11-06 20:51:31 +01:00
Koen Kanters af770acd2d Make retain a optional option and default it to false. 2019-11-06 20:30:33 +01:00
Koen Kanters 23cf8eade9 Make graphviz networkmap ISO_8601_local time. https://github.com/Koenkk/zigbee2mqtt/issues/2239 2019-11-06 19:49:03 +01:00
Tim Kent 45c6f2345c Fix extendedPanID parameter name (#2283)
* Fix extendedPanID parameter name

* Update herdsman and fix tests.
2019-11-06 19:43:12 +01:00
Koen Kanters 00bc4de943 Update herdsman. 2019-11-05 21:35:18 +01:00
Koen Kanters 5cdf820bf6 Update herdsman and converters. 2019-11-05 21:14:19 +01:00
Koen Kanters 99118a0ad8 Update herdsman. 2019-11-05 20:42:32 +01:00
Andreas Brett 34166a5535 fixed typo (#2275) 2019-11-05 07:39:51 +01:00
Jorge Schrauwen 5ad97325be Fix missing retain on add_group, allow specifying of groupID (#2266)
* Accept json for add_group so a groupID can be provided, also set retain property on group creation

* Update util/settings tests for groupID and retain

* Update bridgeConfig tests for add_group with json
2019-11-04 17:59:00 +01:00
Koen Kanters 2fb4e20e1d Update zigbee-herdsman-converters. 2019-11-03 21:23:41 +01:00
Koen Kanters 467c0062bb Dont' crash when removing non-existing device. https://github.com/Koenkk/zigbee2mqtt/issues/2241 2019-11-03 15:02:00 +01:00
Koen Kanters afbfdda0d7 Implement force remove. https://github.com/Koenkk/zigbee2mqtt/issues/2241 2019-11-03 14:54:03 +01:00
Koen Kanters 4265fe05c6 Correctly log name. #2256 2019-11-03 14:29:43 +01:00
Koen Kanters 833769af0c Log name instead of ieeeAddr on ping. https://github.com/Koenkk/zigbee2mqtt/issues/2256 2019-11-03 14:17:57 +01:00
Koen Kanters 8a5f39f6aa Subscribe to nested topics for bind. https://github.com/Koenkk/zigbee2mqtt/issues/2250 2019-11-02 00:03:22 +01:00
Koen Kanters 857fc230d4 Update herdsman. 2019-11-01 23:55:53 +01:00
Koen Kanters 6162dcc4f0 Update zigbee-herdsman. 2019-11-01 23:33:48 +01:00
Koen Kanters 7669682716 Update zigbee-herdsman. 2019-10-30 23:56:46 +01:00
Koen Kanters 4ca8e8e43e Update zigbee-herdsman-converters. 2019-10-30 23:27:46 +01:00
Koen Kanters 5f054862f0 Update zigbee-herdsman-converters. 2019-10-30 23:12:16 +01:00
Koen Kanters 964367fc66 Update zigbee-herdsman-[converters]. 2019-10-30 19:44:02 +01:00
Luke Pomfrey 84915dd1d4 Add homeassistant integration for innr SP 222 smart switch (#2230) 2019-10-30 16:32:55 +01:00
Koen Kanters 344cd60088 Update zigbee-herdsman-converters. 2019-10-28 18:48:20 +01:00
Koenkk 754db956b5 Don't turn on with 255 brightness when transition is provided. https://github.com/Koenkk/zigbee2mqtt/issues/2220 2019-10-28 18:07:15 +01:00
Koenkk 646cd34715 Support secret for network_key. https://github.com/Koenkk/zigbee2mqtt/issues/2209 2019-10-28 18:05:50 +01:00
Koen Kanters cb3ec45294 Fix lint. 2019-10-26 18:25:51 +02:00
Koen Kanters 9eac34a5bb Update zigbee-herdsman-[converters]. 2019-10-26 18:14:51 +02:00
Koen Kanters 7e9dfd4f41 Accept device without log when no ban or whitelist set. 2019-10-26 18:05:40 +02:00
Koen Kanters 63ffe279ea Log uninteresting messages without converters as debug. 2019-10-26 18:03:44 +02:00
Koen Kanters 6f92a41ca9 Update zigbee-herdsman-converters. 2019-10-25 20:43:38 +02:00
Tommy Goode ca19b77e8c Improve support for Centralite 4257050-ZHAC dimmable plug (#2187)
* Add HA power sensors for Centralite 4257050-ZHAC outlet.

* Enable dimming in HA for Centralite 4257050-ZHAC outlet.

* Add new HA sensors for the Iris 3210-L plug.
2019-10-25 20:10:14 +02:00
Koen Kanters 4983048191 Only poll on Hue dimmer switch brightness button. https://github.com/Koenkk/zigbee2mqtt/pull/2122 2019-10-25 19:42:47 +02:00
Koen Kanters 78531a0878 Finish https://github.com/Koenkk/zigbee2mqtt/issues/2201. 2019-10-25 19:17:47 +02:00
Koenkk 505be311a4 Allow to store MQTT credentials separate from configuration.yaml. https://github.com/Koenkk/zigbee2mqtt/issues/2201 2019-10-25 18:43:14 +02:00
Koenkk 02bf8a88bc Also subscribe to groups with slashes. https://github.com/Koenkk/zigbee2mqtt/issues/2200 2019-10-25 18:40:37 +02:00
Jorge Schrauwen a813663de5 Poll device when device does not support reporting. (#2122)
* Support emulation of attReport

Some device do not support attReport for some keys, this will emulate
it.

You can configure which keys that should be read when another device
send a message and the configured device a bind target or in a group the
message was send to.

```yaml
devices:
  '0x0017880104259333':
    friendly_name: bedroom/desk_lamp
    retain: true
    debounce: 0.5
    report_emulate:
      - brightness
      - color
```

Will have the brightness and color queried for example when a hue dimmer
sends commands to the bulb.

* Refactor polling.

* Finish poll tests.

* Update herdsman.

* Improve test stability.
2019-10-24 22:15:40 +02:00
Tommy Goode ec5064bc4d Store last_seen in state.json, so that it is sent out correctly on restart. (#2197) 2019-10-24 07:46:19 +02:00
Koen Kanters ebd2f264a9 Update herdsman. 2019-10-21 21:13:05 +02:00
Koen Kanters 5bd87d338b Update zigbee-herdsman-[converters]. 2019-10-21 20:35:58 +02:00
Koen Kanters ada9316148 birthtimeMS is not realiable on Linux leading to removal of latest instead of oldest log directory which makes the logging stop. 2019-10-21 18:11:16 +02:00
Koen Kanters b476bc2bf8 Update zigbee-herdsman-converters. 2019-10-20 22:52:00 +02:00
Koen Kanters 2076bbae5d Add more logo variants. https://github.com/Koenkk/zigbee2mqtt/issues/2171 2019-10-20 21:56:11 +02:00
Koen Kanters 593dd858d9 Update herdsman. 2019-10-20 21:52:27 +02:00
Koen Kanters c80be7bda2 Don't provide undefined state. https://github.com/Koenkk/zigbee2mqtt/issues/2164 2019-10-20 21:17:18 +02:00
Koen Kanters 01dfcd18ce Install eudev 2019-10-20 17:17:19 +02:00
Koen Kanters 3effa07cf8 Add udevadm #2157 2019-10-20 16:32:00 +02:00
Tommy Goode 6b97df7b47 Add support for battery percentage on Iris 3326-L motion sensor. (#2170) 2019-10-20 11:04:23 +02:00
Tristan Crichton 35a1dd6b0a Add autodiscovery for Innr BF 263 bayonet filament bulb (#2165) 2019-10-20 11:00:32 +02:00
Tommy Goode ff9e6cdacc Improve support for MCT-340 E, MCT-340 SMA, XHS2-SE (#2156)
* Add temperature and battery level reporting for Visonic MCT-340 E contact sensor.

* Improve HA sensors for MCT-340 SMA and XHS2-SE.
2019-10-19 10:32:39 +02:00
Koen Kanters f219e5df9f Fix ban todo. 2019-10-17 22:08:34 +02:00
Koen Kanters f64285703c Implement acceptJoiningDeviceHandler. 2019-10-17 22:01:39 +02:00
Koen Kanters f02ec9a8dd Update herdsman and herdsman-converters. 2019-10-17 19:42:40 +02:00
Tommy Goode 3ca35ad72f Allow a device to be configured even if the interview process fails (#2150)
* Allow a device to be configured even if the interview process fails. This fixes #2148.

* Adjust failing test to account for new behavior.
2019-10-17 18:36:55 +02:00
Timo S da58dcbd7c Eurotronic thermostat improvments (#2124)
* - Setting temperature_command_topic
 to current_heating_setpoint for Eurotronic thermostat
- Thermostat function to dynamically publish values to HA

* Function getTemperatureCommandTopicByVendor()

* strict compare

* Get right setpoint by function and mapping
for current_heating_setpoint

* fix lint

* Update homeassistant.js

* Update homeassistant.js

* Update homeassistant.js
2019-10-17 18:31:42 +02:00
Koen Kanters 7ffe255d93 Install udev. #2145 #2146 2019-10-16 21:54:46 +02:00
Koen Kanters 512f31fbb9 Update zigbee-herdsman. 2019-10-16 21:35:16 +02:00
Koen Kanters f415171036 Allow null for port. https://github.com/Koenkk/zigbee2mqtt/issues/2145 2019-10-16 21:21:52 +02:00
Koen Kanters 4164f01a6b Update zigbee-herdsman and zigbee-herdsman-converters. 2019-10-16 19:44:44 +02:00
Koen Kanters f1b4cd0480 Don't log start error twice. 2019-10-16 19:33:55 +02:00
Koen Kanters 1428e0bb87 Don't setup reporting for Gledopto devices. https://github.com/Koenkk/zigbee2mqtt/issues/2132 2019-10-15 20:16:04 +02:00
Koen Kanters d16981d539 Update zigbee-herdsman. 2019-10-15 20:15:12 +02:00
Dennis Neufeld 2f52878140 Update README.md badge url (#2138)
* Update README.md badge url

* Update README.md
2019-10-15 19:01:33 +02:00
Gabe Cook 9ebb1b96dd Group device staying off when already off (#2140)
* Fix devices within a group staying off if they are off when the group state changes

* Group test cleanups
2019-10-15 16:42:28 +02:00
Koen Kanters 0527b89b49 Update zigbee-herdsman-converters. 2019-10-14 20:32:01 +02:00
Koen Kanters 8bcbb5930a Update zigbee-herdsman-converters. #2133 2019-10-14 18:56:41 +02:00
Gabe Cook 09b7fe699e Fix optimistic group behavior whenever a device is shared between groups (#2134) 2019-10-14 18:04:04 +02:00
Koen Kanters 4abafa9527 Update zigbee-herdsman to 0.9.2. 2019-10-13 00:09:31 +02:00
Koen Kanters f3a51f66fd Make serial and serial.port optional. 2019-10-12 23:18:01 +02:00
Koen Kanters d5925efca7 Only try to configure reporting once. https://github.com/Koenkk/zigbee2mqtt/issues/2123 2019-10-12 18:02:15 +02:00
Koen Kanters 5e0d72c41c Update zigbee-herdsman to 0.9.1. https://github.com/Koenkk/zigbee2mqtt/issues/1429 2019-10-12 14:39:06 +02:00
Koen Kanters ba92f73961 Resolve Coordinator to coordinator. https://github.com/Koenkk/zigbee2mqtt/issues/2100 2019-10-09 19:40:46 +02:00
Koen Kanters f2132f6c50 Update badge. 2019-10-09 18:09:10 +02:00
Koen Kanters 6e6305253e Update zigbee-herdsman-converters. 2019-10-09 18:08:14 +02:00
Tommy Goode dcebba857b Fix power reporting for Iris 3210-L smart plug. (#2105) 2019-10-09 17:58:05 +02:00
Koen Kanters 8d97262d39 Discover thermostat and battery for SPZB0001. https://github.com/Koenkk/zigbee2mqtt/issues/2094 2019-10-07 22:21:41 +02:00
Koen Kanters a9b4188434 Improve test stability. 2019-10-07 22:06:27 +02:00
Koen Kanters 997c5d3e44 Allow to disable Home Assistant device discovery. https://github.com/Koenkk/zigbee2mqtt/issues/2089 2019-10-07 21:58:35 +02:00
Koen Kanters a3bbb93f99 Update zigbee-herdsman and zigbee-herdsman-converters. 2019-10-07 19:34:10 +02:00
Koen Kanters 41c8c2a146 Update zigbee-herdsman-converters. 2019-10-04 19:12:49 +02:00
Koen Kanters 8833fb57b5 Update zigbee-herdsman. https://github.com/Koenkk/zigbee2mqtt/issues/2017 2019-10-04 18:58:07 +02:00
Matt 4a996bd84d Add ZWallRemote0 homeassistant mapping (#2076)
* Add ZWallRemote0 homeassistant mapping

* Fix Spaces in list

* Update homeassistant.js
2019-10-04 18:38:12 +02:00
Koen Kanters 732a97ba0c Don’t write to configuration.yaml when it didn’t change. https://github.com/Koenkk/zigbee2mqtt/issues/2071 2019-10-03 20:06:31 +02:00
Koen Kanters e7bf5ee648 Update zigbee-herdsman-converters. 2019-10-03 19:03:36 +02:00
Gabe Cook 159a846c50 Do not publish a new optimistic group state if any devices within are (#2063)
on. Relates to #764
2019-10-03 17:41:36 +02:00
Koen Kanters a6d3e7209f Update zigbee-herdsman-converters. 2019-10-02 22:01:29 +02:00
Koen Kanters 1a48c85365 Update zigbee-shepherd-converters. 2019-10-01 21:11:44 +02:00
Koen Kanters 6a8abd8ff4 Fix tests. 2019-10-01 20:58:08 +02:00
Koen Kanters b492b0ce5f Improve logging. 2019-10-01 20:50:05 +02:00
Koen Kanters 518232e15e Zigbee-herdsman 0.8.0 2019-10-01 20:22:47 +02:00
Koen Kanters 90c70e8629 Bump zigbee-herdsman-converters. 2019-09-30 21:41:53 +02:00
Gabe Cook fe4f43843d Update other groups with a shared device when a group state updates (#2055)
* Update other groups with a shared device when a group state updates #764

* Add group to test which does not have the shared device to be sure it does not change
2019-09-30 21:18:07 +02:00
Koen Kanters a5ce7e6890 Fix azure pipline triggers and conditions. 2019-09-30 21:16:16 +02:00
Koen Kanters fc3a826f50 Bump zigbee-herdsman. https://github.com/Koenkk/zigbee2mqtt/issues/892 2019-09-30 21:16:00 +02:00
Koen Kanters ebd0415945 Remove triggers. 2019-09-30 20:49:06 +02:00
Koen Kanters ce08668543 Only trigger hassio on dev change. 2019-09-30 20:39:13 +02:00
Koen Kanters 80aa023f7f Azure badge 2019-09-30 20:36:40 +02:00
Koen Kanters e4df2ac66e Add azure pipelines. 2019-09-30 20:31:31 +02:00
Koenkk 9a21e9d956 Migrate to node Docker image and buildx. https://github.com/Koenkk/zigbee2mqtt/issues/2054 2019-09-30 17:29:58 +02:00
Koen Kanters a7e9ad70e3 Bump alpine to 3.10 and other docker improvements. 2019-09-29 21:55:40 +02:00
Koen Kanters 61e2087242 Bump zigbee-herdsman-converters. 2019-09-29 21:37:26 +02:00
Raymond Mouthaan 99ebc46981 Added tzdata and --virtual devtools (#2053)
* Update Dockerfile.arm32v6

using --virtual for devtools, added tzdata

* Update Dockerfile.arm64v8

* Update Dockerfile.amd64

* Lint
2019-09-29 21:32:11 +02:00
Koen Kanters c8eb503ae7 Simplify group optimistic mode. https://github.com/Koenkk/zigbee2mqtt/issues/764 2019-09-29 14:35:05 +02:00
Pauline Middelink 7507ad6dcb Remove caching for to_side and from_side. (#2048)
Stop caching `to_side` and `from_side` which only have meaning during the `flip90` action of the MFKZQ01LM Smart Cube.
Fixes #641
2019-09-29 13:42:58 +02:00
Koen Kanters 92fcf5a85a Update zigbee-herdsman-converters. 2019-09-28 18:11:02 +02:00
Koen Kanters 42bc5f274b Fix logger test writing to configuration.yaml. 2019-09-28 13:49:27 +02:00
Koen Kanters 7b8b2c5213 Update zigbee-shepherd-converters 2019-09-28 13:48:25 +02:00
Koen Kanters 9d8e56408a Fix device configuring when paired through zigbee-shepherd. 2019-09-28 13:08:32 +02:00
Koen Kanters caf92c5e30 Update zigbee-shepherd-converters. 2019-09-28 00:26:33 +02:00
Koen Kanters 67f6ccc8a8 Don’t allow duplicate friendly_name. #1876 2019-09-27 22:56:59 +02:00
Koen Kanters bf36f1e8a3 Update zigbee-herdsman-converters and zigbee-herdsman. 2019-09-27 21:58:49 +02:00
Koen Kanters d444969151 Update zigbee-herdsman-converters. 2019-09-26 09:43:40 +02:00
Andreas Brett d12943556c Update controller.js (#2040)
fixed typo
2019-09-26 09:30:12 +02:00
Koen Kanters 9964d8e462 Fix various crashes when removing a device. https://github.com/Koenkk/zigbee2mqtt/issues/2004 2019-09-26 01:14:58 +02:00
Koen Kanters 3083655072 Codeacy badge. 2019-09-26 00:16:24 +02:00
Koen Kanters 265bcf1de3 Add 100% coverage badge. 2019-09-26 00:10:36 +02:00
Koen Kanters bd93d09290 Update zigbee-herdsman-converters. 2019-09-25 23:51:38 +02:00
Koen Kanters ca481d7f76 Update zigbee-shepherd-converters. 2019-09-25 13:38:10 +02:00
Koen Kanters 62e67e99d2 Don’t publish chached states when cache_state is disabled.https://github.com/Koenkk/zigbee2mqtt/issues/2033 2019-09-25 13:15:30 +02:00
Koen Kanters d4011fabc7 Implement group optimistic ‘group_devices’ mode. https://github.com/Koenkk/zigbee2mqtt/issues/764#issuecomment-534146878 2019-09-25 12:51:17 +02:00
Koen Kanters cfefaeb73c Validate settings on startup with JSON schema. 2019-09-25 12:08:39 +02:00
Koen Kanters 34111159ae Update Winston logger to 3.x 2019-09-25 10:55:50 +02:00
Koen Kanters 9d4705fc1c Remove onlyThis. 2019-09-23 23:59:01 +02:00
Koen Kanters 007bc42bf7 Update zigbee-shepherd-converters. 2019-09-23 23:57:41 +02:00
Koen Kanters 3001e2d3a0 Add more properties for coordinator /devices/get. https://github.com/Koenkk/zigbee2mqtt/issues/2020 2019-09-23 23:10:29 +02:00
barrygwn f60b4ddd80 added support for IKEA LED1836G9: TRADFRI bulb E27 WW 806lm (#2022)
* added 'LED1836G9' TRADFRI bulb E27 WW 806lm

* added 'LED1836G9' TRADFRI bulb E27 WW 806lm

* Update homeassistant.js
2019-09-23 22:39:22 +02:00
Koen Kanters e56e620f54 Add test case for https://github.com/Koenkk/zigbee2mqtt/issues/1997 2019-09-23 22:24:03 +02:00
Koen Kanters 41e68c8ffe Update zigbee-herdsman to 0.7.0. 2019-09-23 22:21:27 +02:00
Koen Kanters 63acd4a43b Update zigbee-herdsman and zigbee-shepherd-converters. 2019-09-22 21:29:38 +02:00
Koen Kanters c5218bbd31 Update zigbee-herdsman. 2019-09-22 20:02:46 +02:00
alwashe 4dd9f0ee57 Update homeassistant.js (#2015) 2019-09-22 18:35:47 +02:00
Koen Kanters e441cf1752 Add extra logging for failed to configure. https://github.com/Koenkk/zigbee2mqtt/issues/1957 2019-09-22 18:01:10 +02:00
Koen Kanters e65f9d36d0 Add extra failed to setup reporting logging. https://github.com/Koenkk/zigbee2mqtt/issues/2005 2019-09-22 17:56:12 +02:00
Koen Kanters 9e94148459 Fix group membership args. https://github.com/Koenkk/zigbee2mqtt/issues/2003 2019-09-20 22:09:11 +02:00
Koen Kanters e3d0b97085 Update zigbee-herdsman. 2019-09-20 22:05:47 +02:00
Koen Kanters 5b71eeeed8 Update zigbee-herdsman zigbee-shepherd-converters. 2019-09-20 21:25:56 +02:00
Koen Kanters d4f01e6893 Replace Livolo extension with DeviceEvent. https://github.com/Koenkk/zigbee2mqtt/issues/592 2019-09-19 20:36:05 +02:00
Koen Kanters e9a336fd16 Update zigbee-herdsman to 0.6.13. https://github.com/Koenkk/zigbee2mqtt/issues/1960 2019-09-18 21:18:58 +02:00
Koen Kanters 5f203d15c4 Update zigbee-herdsman to 0.6.12. 2019-09-18 19:39:49 +02:00
felixstorm d7401c817c entityPublish.js - add logger to meta (#1988) 2019-09-17 21:46:16 +02:00
Koen Kanters bd29a5d35c Back to alpine 3.9 2019-09-17 19:59:58 +02:00
Koen Kanters 983f55ce3d npm don’t install dev dependencies. 2019-09-17 19:20:52 +02:00
Koen Kanters 130366575e Bump alpine to 3.10 2019-09-17 19:14:44 +02:00
Koen Kanters 7fb7dbbe0d Docker experimental is still needed. 2019-09-17 19:12:25 +02:00
Koen Kanters a7b3304b57 Is docker experimental still needed? 2019-09-17 19:07:21 +02:00
Koen Kanters c09f55873b Add group optimistic feature. https://github.com/Koenkk/zigbee2mqtt/issues/764 2019-09-17 19:01:57 +02:00
Koen Kanters ef7049f899 Update zigbee-herdsman to 0.6.11. https://github.com/Koenkk/zigbee-herdsman/issues/29 2019-09-17 18:41:46 +02:00
Koen Kanters 1a7331609a Fix lint. 2019-09-17 18:38:25 +02:00
Koenkk ff83840f76 Change group state when device state changes. https://github.com/Koenkk/zigbee2mqtt/issues/1971 2019-09-17 18:33:27 +02:00
Koenkk c8a07a5c2d Add base extension. 2019-09-17 18:32:16 +02:00
Koenkk 11aacb8620 Fix networkmap raw graph breaking change. https://github.com/azuwis/zigbee2mqtt-networkmap/issues/6 2019-09-17 18:19:42 +02:00
Koen Kanters d24c41cbba Update zigbee-herdsman. 2019-09-16 20:09:52 +02:00
Koen Kanters e758443190 Fix tests. 2019-09-16 20:03:51 +02:00
Koen Kanters 21dadd631c Don’t throw error when devices is null. https://github.com/Koenkk/zigbee2mqtt/issues/1973 2019-09-16 19:49:49 +02:00
Koen Kanters c32f8961b6 Update zigbee-shepherd-converters. 2019-09-16 19:38:24 +02:00
Koenkk 1f1c771075 Make logging consistent. https://github.com/Koenkk/zigbee2mqtt/issues/1965 2019-09-15 09:13:02 +02:00
Koenkk de8dd74968 Update zigbee-herdsman to 0.6.9. https://github.com/Koenkk/zigbee2mqtt/issues/1960 2019-09-14 08:32:20 +02:00
Koen Kanters f5463dbf0e Add last seen to zigbee2mqtt/bridge/config/devices/get. https://github.com/Koenkk/zigbee2mqtt/issues/1910 2019-09-12 22:50:51 +02:00
Koen Kanters 9c5b3bf4d1 Use lastSeen from zigbee-herdsman. 2019-09-12 22:48:23 +02:00
Koen Kanters 798a4ee565 Fix hardware and software version in devices payload. https://github.com/Koenkk/zigbee2mqtt/issues/1958 2019-09-12 20:58:57 +02:00
Koen Kanters 09743f13f9 Improve publish logging. https://github.com/Koenkk/zigbee2mqtt/issues/1958 2019-09-12 20:53:23 +02:00
Koen Kanters 8f4cf5e520 Update zigbee-herdsman to 0.6.7. https://github.com/Koenkk/zigbee2mqtt/issues/1952 2019-09-12 20:51:24 +02:00
Koen Kanters d53e1330f5 Improve error message when reading invalid YAML file. 2019-09-11 21:42:44 +02:00
Koen Kanters 17f1a865b4 Update zigbee-herdsman to 0.6.6. https://github.com/Koenkk/zigbee2mqtt/issues/1568 2019-09-11 21:12:41 +02:00
Koen Kanters 8b4e0fd865 Log stack on zigbee start error. 2019-09-10 22:07:31 +02:00
Koen Kanters cfae1bf3b0 Default transition for groups. https://github.com/Koenkk/zigbee2mqtt/issues/1948 2019-09-10 19:42:04 +02:00
Koen Kanters 411f1fab73 Update zigbee-herdsman. #1888. 2019-09-09 21:33:34 +02:00
Koen Kanters 053e646f50 Update zigbee-herdsman-converters. 2019-09-09 21:31:57 +02:00
Koen Kanters d83085ea7f Zigbee-herdsman (#1945)
* Update zigbee-herdsman and zigbee-shepherd-converters.

* Force Aqara S2 Lock endvices (#1764)

* Start on zigbee-herdsman controller refactor.

* More updates.

* Cleanup zapp.

* updates.

* Propagate adapter disconnected event.

* Updates.

* Initial refactor to zigbee-herdsman.

* Refactor deviceReceive to zigbee-herdsman.

* Rename

* Refactor deviceConfigure.

* Finish bridge config.

* Refactor availability.

* Active homeassistant extension and more refactors.

* Refactor groups.

* Enable soft reset.

* Activate group membership

* Start on tests.

* Enable reporting.

* Add more controller tests.

* Add more tests

* Fix linting error.

* Data en deviceReceive tests.

* Move to zigbee-herdsman-converters.

* More device publish tests.

* Cleanup dependencies.

* Bring device publish coverage to 100.

* Bring home assistant test coverage to 100.

* Device configure tests.

* Attempt to fix tests.

* Another attempt.

* Another one.

* Another one.

* Another.

* Add wait.

* Longer wait.

* Debug.

* Update dependencies.

* Another.

* Begin on availability tests.

* Improve availability tests.

* Complete deviceAvailability tests.

* Device bind tests.

* More tests.

* Begin networkmap refactors.

* start on networkmap tests.

* Network map tests.

* Add utils tests.

* Logger tests.

* Settings and logger tests.

* Ignore some stuff for coverage and add todos.

* Add remaining missing tests.

* Enforce 100% test coverage.

* Start on groups test and refactor entityPublish to resolveEntity

* Remove joinPathStorage, not used anymore as group information is stored into zigbee-herdsman database.

* Fix linting issues.

* Improve tests.

* Add groups.

* fix group membership.

* Group: log names.

* Convert MQTT message to string by default.

* Fix group name.

* Updates.

* Revert configuration.yaml.

* Add new line.

* Fixes.

* Updates.

* Fix tests.

* Ignore soft reset extension.
2019-09-09 19:48:09 +02:00
Koen Kanters e26ad2aca2 1.6.0 2019-09-09 19:10:16 +02:00
Koen Kanters eb69ea6808 Fix lint 2019-09-09 19:04:07 +02:00
Koen Kanters d0242fbd54 Update zigbee-shepherd-converters to 10.2.5. 2019-09-08 20:52:17 +02:00
Michal Szymura bd8801698f Added Sengled Z01-A60EAE27 to HA Autodiscovery (#1936)
* Added Sengled Z01-A60EAE27 to HA Autodiscovery

* Update homeassistant.js

* Update homeassistant.js
2019-09-06 08:09:41 +02:00
wixoff b77be8e673 Support Hue white ambiance E26 with Bluetooth (#1932) 2019-09-05 19:44:07 +02:00
BIERAAP 1189d16839 Added support TRADFRI bulb GU10 WW 400lm LED1837R5 (#1927) 2019-09-03 18:04:42 +02:00
LagaV b00d4d55fa Adding Philips Adore lights to Home Assistant integration (#1917) 2019-09-01 10:41:29 +02:00
Abílio Costa 4f7e3a179f add support for TRADFRI bulb E27 WS clear 806lm (#1902) 2019-08-31 13:14:46 +02:00
stkang90 1bdbeae144 add support SA-003-Zigbee (#1894)
* add support SA-003-Zigbee

[product detail]
https://ko.aliexpress.com/item/32957480204.html?spm=a2g0o.productlist.0.0.5b4e7321varbKb&algo_pvid=a9497085-a7c0-4863-ba60-f911cb532362&algo_expid=a9497085-a7c0-4863-ba60-f911cb532362-0&btsid=bb62c063-3baf-452c-99a9-ba43e40f04a1&ws_ab_test=searchweb0_0,searchweb201602_4,searchweb201603_52

* Update homeassistant.js
2019-08-28 17:32:31 +02:00
Koen Kanters 48fc7d8d3b Update zigbee-shepherd-converters. 2019-08-21 19:37:36 +02:00
Jorge Schrauwen 8ee3158783 [FIX] #1874: logging of groupid's (#1875)
While trying to get my IKEA remote to work I kept getting 'undefined' groupID's. This fixes it.
2019-08-19 17:44:54 +02:00
Koen Kanters 7d04185f2c Update zigbee-shepherd-converters and zigbee-herdsman. 2019-08-16 19:03:23 +02:00
Kiall Mac Innes 377e9d50dc IKEA TRADFRI E1810 (#1866)
Add the IKEA E1810, which appears to be a replacement for the E1524. Functionally, they appear to
work identically, the only difference I can see is front finish is matte rather than glossy, and
the internals behind the battery cover are slightly different.
2019-08-16 18:41:11 +02:00
felixstorm 9628cf2c95 Home Assistant discovery: allow to delete setting (#1839)
* Home Assistant discovery: allow to delete setting by setting it to `null`

* Home Assistant discovery: support boolean values
2019-08-16 17:44:18 +02:00
hawkefly 4d4a63f913 support aqara s2 lock pro (#1859) 2019-08-16 17:40:47 +02:00
Koen Kanters 22bed9a347 Update zigbee-herdsman. 2019-08-13 20:05:53 +02:00
Kiall Mac Innes d96c3da8d5 Fix commit hash output in version info (#1855) 2019-08-13 20:03:08 +02:00
Leander Seidlitz 6abe7d2fd7 Add support for Osram Smart+ GU10 PAR16 AC08560 (#1850) 2019-08-13 19:47:43 +02:00
Koen Kanters a62d6aad91 Update zigbee-herdsman and zigbee-shepherd-converters. 2019-08-12 19:20:33 +02:00
Koen Kanters c55691daec Fix groups log messages. https://github.com/Koenkk/zigbee2mqtt/issues/1848 2019-08-12 19:13:18 +02:00
acc c9f56f0bbf separate HGZB-01A and HGZB-02A and identify HGZB-01A as a switch (#1844) 2019-08-12 17:47:55 +02:00
felixstorm c53c4c894f Support reporting for closuresWindowCovering cluster (#1837) 2019-08-11 14:13:44 +02:00
felixstorm 6ae307d893 Home Assistant integration - support for ubisys D1, J1, S1, S2 (#1830)
* HomeAssistant integration - support for ubisys D1, J1, S1, S2

* fixes for eslint
2019-08-11 14:13:44 +02:00
hawkefly 511f9406e2 add sensor_action config for WXKG12LM (#1826) 2019-08-11 14:13:44 +02:00
Koen Kanters 9e63a4646e Also query color and color temp when device reconnects. 2019-08-11 14:13:44 +02:00
Kiall Mac Innes da5ca2f0bf Update HA extension to add batt support to E1524 and AC01353010G (#1822)
* Update HA eextension to add batt support to E1524 and AC01353010G

The IKEA E1524 TRADFRI remote control and the Osram SMART+ Motion Sensor
expose a battery and battery_low attribute, update the HA discovery
integration to include these sensors by default.

* Update homeassistant.js

* Update homeassistant.js

* Update homeassistant.js
2019-08-11 14:13:44 +02:00
John Dyer ecbee780db add samsung 2018 water sensor (#1819) 2019-08-11 14:13:44 +02:00
Koen Kanters a604fd6345 Update zigbee-herdsman and zigbee-shepherd-converters. 2019-08-11 14:13:44 +02:00
Koen Kanters 36e52ba4fb Update zigbee-shepherd-converters. 2019-08-11 14:13:44 +02:00
Koen Kanters f67eeffed6 Update zigbee-herdsman to 0.5.1. 2019-08-11 14:13:44 +02:00
Koen Kanters 5e55e1655f Update zigbee-herdsman and zigbee-shepherd-converters. 2019-08-11 14:13:44 +02:00
stkang90 519eb4eecf add support PM-C139-ZB (#1807) 2019-08-11 14:13:44 +02:00
Koen Kanters fd3019dce8 Update zigbee-herdsman to 0.4.5. https://github.com/Koenkk/zigbee2mqtt/issues/1798 2019-08-11 14:13:44 +02:00
Koen Kanters 1ca1be2ea2 Update zigbee-herdsman to 0.4.2. https://github.com/Koenkk/zigbee2mqtt/issues/1798 2019-08-11 14:13:44 +02:00
Koen Kanters 967bf1083c Update zigbee-herdsman to 0.4.1 https://github.com/Koenkk/zigbee2mqtt/issues/1784 2019-08-11 14:13:44 +02:00
GuGu927 c1e8dd990f Add support for Goqual zigbee switch(1~6gang) (#1783)
* Update homeassistant.js

* Update utils.js
2019-08-11 14:13:44 +02:00
Koen Kanters fcb6c37ef0 Set whitelist to empty array when null. https://github.com/Koenkk/zigbee2mqtt/issues/1774 2019-08-11 14:13:44 +02:00
didiht c9ec198c1f correct log of groupid #1785 (#1787) 2019-08-11 14:13:44 +02:00
Koen Kanters a60fdd75dc zcl-id > Zcl. 2019-08-11 14:13:44 +02:00
Koen Kanters 7853f41a0e Bump zigbee-herdsman to 0.4.0. 2019-08-11 14:13:44 +02:00
Koen Kanters 3ed5705253 Update zigbee-shepherd-converters and zigbee-herdsman. 2019-08-11 14:13:44 +02:00
Koen Kanters 5254eea6e0 Update zigbee-herdsman and zigbee-shepherd-converters. 2019-08-11 14:12:30 +02:00
Boostflow 92e930ede3 Added support for Philips Hue Struana (#1747) 2019-07-18 20:24:14 +02:00
Koen Kanters ac3b924065 1.5.1 2019-07-16 18:31:32 +02:00
Koen Kanters dd8a55cf08 Update zigbee-herdsman to 0.1.17. https://github.com/Koenkk/zigbee2mqtt/issues/1734#issuecomment-511403606 2019-07-15 20:04:39 +02:00
clockbrain 3ae2d2b946 Network map routes selectable by mqtt topic (#1736) 2019-07-15 20:02:56 +02:00
Koen Kanters 31b8352f5a 1.5.0 2019-07-13 19:39:20 +02:00
Koen Kanters 503fef807c Add changelog generator tool for new supported devices page. 2019-07-13 19:38:23 +02:00
Koen Kanters 4aab81d9e3 Remove HS1WD (not supported anymore). 2019-07-13 19:38:00 +02:00
Koen Kanters 8d705ade39 Update zigbee-shepherd-converters. 2019-07-13 16:36:24 +02:00
Koen Kanters d3e97953c3 Update zigbee-shepherd-converters. 2019-07-11 20:22:43 +02:00
wixoff 1b859c4dc2 Support for PP-WHT-US new sensors (#1718)
* Support for PP-WHT-US new sensors

* Update homeassistant.js
2019-07-11 19:36:50 +02:00
Koen Kanters 225919bb23 Update zigbee-herdsman to 0.1.6. https://github.com/Koenkk/zigbee2mqtt/issues/1710 2019-07-10 19:04:54 +02:00
Andreas Brett 74b8340afb add TLS/SSL options for connecting to MQTT server (#1706)
* add TLS/SSL options for connecting to MQTT server

* Update mqtt.js

* gotta love travis

* Update mqtt.js

separated processing of mqtt.ca and mqtt.key/mqtt.cert in order to allow for "server-authentication only" as well as "server+client authentication"

* Update mqtt.js
2019-07-10 17:57:41 +02:00
Koen Kanters 08c0f2b614 Lint. 2019-07-08 22:04:38 +02:00
Koen Kanters 61b54c50a5 Update zigbee-shepherd-converters and zigbee-herdsman. 2019-07-08 21:42:07 +02:00
Rick 6400f52a28 Added "alert" for groups (#1704) 2019-07-08 21:06:08 +02:00
clockbrain 97f9f83181 Use penwidth instead of dotted/dashed lines (#1694) 2019-07-06 10:09:44 +02:00
Koen Kanters 90c3fc0320 Add device rename test case. https://github.com/Koenkk/zigbee2mqtt/issues/1687 2019-07-04 20:50:54 +02:00
Koen Kanters 94a7cd8ec9 Update zigbee-shepherd-converters to 10.1.1 2019-07-04 20:16:20 +02:00
Craig Stephen 1df43bdbc4 Add support for UK Hive Bulb E27 & B22 - Warm to cool white (#1683) 2019-07-03 17:38:43 +02:00
Koen Kanters 3daf97283c Fix queue settings. 2019-07-02 19:13:06 +02:00
Koen Kanters aca0c39291 Move queue from advanced. 2019-07-02 19:00:42 +02:00
Koen Kanters 9624384c3f Add queue settings. https://github.com/Koenkk/Z-Stack-firmware/issues/93 2019-07-02 18:56:03 +02:00
Koen Kanters 3b4ee3bc2e Update zigbee-shepherd-converters to 10.1.0. 2019-07-01 16:48:54 +02:00
clockbrain 7a19c8876a Network map fixes (#1676)
* Include scan failed note in network map

* Include relationship in map structure

* Clearer source and destination node naming

* eslint fixes

* More eslint fixes

* Removed empty brackets for no routes

* Reposition short address in device node

* eslint fixes
2019-07-01 16:10:50 +02:00
Koen Kanters 51df6b7e8a Correctly call convert. https://github.com/Koenkk/zigbee2mqtt/issues/1639#issuecomment-506016224 2019-06-27 19:11:21 +02:00
Andreas Brett 7cabe3a523 colors for network map (#1666)
* Update settings.js

added default color options for network map

* Update networkMap.js

- add timestamp node to indicate when the map was created
- colorize nodes by device type
- colorize edges by activity

* Update networkMap.js

make travis happy

* Update networkMap.js

* Update networkMap.js

* Update settings.js

* Refactor

* Move to graphviz.
2019-06-26 19:30:38 +02:00
Viet Dzung 7b2522f712 Support whitelist devices feature #1643 (#1654)
* Support whitelist devices feature #1643

* Control via MQTT

* Log
2019-06-25 19:38:36 +02:00
Koenkk 5a132ad34b Retrieve default ep from mapping. #1662 2019-06-25 19:13:59 +02:00
Koen Kanters 362b910e48 Lint. 2019-06-24 21:10:06 +02:00
Dennis Keitzel 241b300f7b Allow custom home-assistant status topic (#1667) 2019-06-24 20:52:47 +02:00
Koen Kanters 0e9931af6c Improve bind logging. https://github.com/Koenkk/zigbee2mqtt/issues/1662 2019-06-24 20:25:37 +02:00
Koen Kanters f4f297e8a2 Update zigbee-herdsman. 2019-06-24 20:17:07 +02:00
Koen Kanters 5934efa41e Add last_seen when device publish succeeds. https://github.com/Koenkk/zigbee2mqtt/issues/1651 2019-06-24 20:16:03 +02:00
clockbrain 38a1aec823 Network map styling improvements (#1653)
* Weight and style lines based on routes

* Refactor to make End Device case more obvious
2019-06-23 21:22:13 +02:00
Koen Kanters 3c398df658 Lint. 2019-06-23 16:10:44 +02:00
Koen Kanters 91d415404c Update zigbee-shepherd-converters and zigbee-herdsman. 2019-06-23 16:02:43 +02:00
Koen Kanters ef01346776 Update zigbee-shepherd-converters to 10.0.0 and zigbee-herdsman to 0.1.11. 2019-06-19 21:44:44 +02:00
Koen Kanters 801e97143c Fix adding groups with duplicate names. #764 2019-06-19 18:35:57 +02:00
Koen Kanters 304b2efa48 Don’t publish emtpy messages. #1599 2019-06-19 18:11:35 +02:00
Koen Kanters a36ed2032d Update zigbee-herdsman to 0.1.10. 2019-06-19 18:07:13 +02:00
Koen Kanters 17d01e937e Update zigbee-herdsman to 0.1.9. 2019-06-18 22:07:07 +02:00
Koen Kanters 110f80ec84 Lint. 2019-06-17 21:41:48 +02:00
clockbrain b28da0265e Include last seen in device boxes on graphviz map (#1633)
* Include last seen in device boxes on graphviz map

* Refactor

* Fix test cases

* Bind

* Refactor last seen label construction

* style fix
2019-06-17 21:28:27 +02:00
Koenkk 1c529c4873 Add group remove_all without group #764 2019-06-17 21:17:29 +02:00
clockbrain 3981c1c6e4 Include network routes on the map (#1641)
* Initial inclusion of routes on map

* Forgot to include zigbee.js

* Hex string for route address

* Rebaseline to dev

* Cleaner merging of scan arrays

* style fixes
2019-06-16 13:49:15 +02:00
Koen Kanters c48f73e36b Discover action sensor for WXKG03LM. https://github.com/Koenkk/zigbee2mqtt/issues/1640 2019-06-16 13:13:03 +02:00
Koen Kanters 94e03d4189 Update zigbee-herdsman 2019-06-15 22:57:35 +02:00
Koen Kanters e30ff9e722 Move to zigbee-herdsman. 2019-06-15 22:20:54 +02:00
pali 1f63a32170 [graphviz] show network address in hexastring format (#1638)
* [graphviz] show network address in hexastring format

Wireshark shows network address in hexadecimal format, so it's easier to follow messages in Wireshark if both shows address in same format.

* Update networkMap.js

* Update networkMap.js
2019-06-15 17:04:35 +02:00
Jevgeni Kiski e9b5a588cc #1588 Openhab2 compatibility (#1589) 2019-06-15 16:55:33 +02:00
Koen Kanters 4357064203 Update zigbee-shepherd-converters to 9.0.22. 2019-06-15 14:02:58 +02:00
Koen Kanters 86a65ebec0 Merge branch 'master' into dev 2019-06-13 22:10:52 +02:00
Koen Kanters 259ba9d658 Update zigbee-shepherd-converters to 9.0.21. 2019-06-13 22:01:39 +02:00
Dan Chen 9fe76c29ef Add power usage metering to GE Plug-in Smart Switch 45853GE (#1629)
* Create FUNDING.yml

* Add power usage metering to GE Plug-in Smart Switch 45853GE

* Delete FUNDING.yml
2019-06-13 21:48:04 +02:00
clockbrain dd49a76e5c Network map rewrite using queue (#1626)
* Initial rewrite of network map scan using queue

* Rename routerList to scanList

* eslist fixes

* More eslint fixes

* Timeout now dynamic based on number of scanable devices
2019-06-13 21:43:12 +02:00
Anne Meijer 6976f8e70a Added support for HEIMAN HS1CA-E (#1622)
* Create FUNDING.yml

* Adde support for HEIMAN HS1CA-E

* Fixed eslint issues

* Delete FUNDING.yml
2019-06-11 20:07:32 +02:00
Koen Kanters 82dc8437a1 Get rid of logging during test cases. 2019-06-10 00:01:48 +02:00
Koen Kanters fb12d15d9d Fix lint error. 2019-06-09 23:46:19 +02:00
Koen Kanters 852950fc09 Update zigbee-shepherd-converters to 9.0.20. 2019-06-09 23:43:40 +02:00
clockbrain b663e37fd9 Also match network map link by short address (#1611) 2019-06-09 08:16:38 +02:00
Koen Kanters 70fbe714e3 Add trace logging and add trace logging to zigbeeQueue. https://github.com/Koenkk/zigbee2mqtt/issues/1566 2019-06-08 19:56:35 +02:00
Koen Kanters ee8161b807 Don’t add state_topic to payload for thermostat. #1599 2019-06-07 23:55:20 +02:00
Koen Kanters 8ad6aee43a Identify QBKG04LM and QBKG03LM as end device. https://github.com/Koenkk/zigbee2mqtt/issues/1594 2019-06-04 19:23:58 +02:00
clockbrain 4497214588 Network map fixes (#1590)
* Remove device status from network scan topology

* Random start for each lqi scan then sort resultant link map

* Fix log statement order

* Sort network map links by composite key

* Fix typo in link sorting

* Fix eslint formatting
2019-06-02 10:05:44 +02:00
Koen Kanters 08e55e469f Update zigbee-shepherd-converters to 9.0.19. 2019-05-29 20:26:40 +02:00
Koen Kanters c29bfe1455 Allow to specify endpoint when adding device to group. (#1515)
* uu

* Update
2019-05-29 20:11:40 +02:00
Koen Kanters 82ed260d47 Update zigbee-shepherd-converters to 9.0.18. 2019-05-29 19:33:15 +02:00
rachetfoot caff94559e Iterate objects recursively and support array output (#1573)
* Iterate objects recursively and support array output

* Fix eslint errors

* Improve array handling and expand related test

* Improve tests and array support, add special case for color attributes
2019-05-28 20:01:46 +02:00
Koen Kanters c2b4d63e12 Don’t cache elapsed. https://github.com/Koenkk/zigbee2mqtt/issues/1576 2019-05-26 20:03:43 +02:00
Koen Kanters 825f096434 Update zigbee-shepherd-converters to 9.0.17. 2019-05-24 18:32:37 +02:00
clockbrain 4b14222bda Network map error handling (#1565)
* Catch errors from failing network scans

* Tidier code for process result

* Fix eslint format errors
2019-05-24 18:21:53 +02:00
Koen Kanters 927c4dbc05 Create FUNDING.yml 2019-05-24 08:27:35 +02:00
clockbrain c4e9ea208a Add debugging for network scan (#1559)
* Add debugging for network scan

* Fix eslint warning
2019-05-23 18:53:47 +02:00
Koen Kanters af09624cff Update zigbee-shepherd-converters to 9.0.16. 2019-05-22 22:09:13 +02:00
Koen Kanters e4a50b662d Update zigbee-shepherd-converters to 9.0.15. 2019-05-21 21:15:16 +02:00
clockbrain 22b64d09f2 Network map (#1546)
* Initial iterative rewrite of network scan

* Remove unused linkKey

* Restore original log message

* Cleaner array flattening

* Fix various travis warnings

* Add a timeout so partial map can be generated

* Fix further eslint issues

* Add a timeout so partial map can be generated

* Fix further eslint issues
2019-05-21 21:04:14 +02:00
Koen Kanters dc028d5046 Update zigbee-shepherd. 2019-05-21 20:54:49 +02:00
Koen Kanters 0352a738a7 Update zigbee-shepherd-converters to 9.0.14. 2019-05-20 20:53:51 +02:00
Koen Kanters 6adfdacb3c Don’t quit twice. https://github.com/Koenkk/zigbee2mqtt/issues/1550 2019-05-20 20:43:25 +02:00
Koen Kanters 18913a1577 Update zigbee-shepherd-converters to 9.0.12. 2019-05-19 19:51:27 +02:00
Koen Kanters 1e04c229dd Merge remote-tracking branch 'origin/master' into dev 2019-05-19 19:34:02 +02:00
clockbrain 31d21546b9 Simpler network map scan (#1543)
* Initial iterative rewrite of network scan

* Remove unused linkKey

* Restore original log message

* Cleaner array flattening

* Fix various travis warnings
2019-05-19 19:33:30 +02:00
Koen Kanters 7f9104367b Reduce permitJoin interval to 160 seconds to fix pairing devices after pairing E1603. https://github.com/Koenkk/zigbee2mqtt/issues/1099 2019-05-19 19:10:51 +02:00
Koen Kanters 92d0002bbb Update zigbee-shepherd-converters to 9.0.11. 2019-05-19 18:51:00 +02:00
Koen Kanters 0074c32136 Update zigbee-shepherd-converters to 9.0.10. 2019-05-14 21:57:47 +02:00
Koen Kanters faa6aa41a9 Fix AC0251100NJ discovery. 2019-05-14 21:46:55 +02:00
Koen Kanters 3ed9bbde1a Update zigbee-shepherd-converters to 9.0.9 2019-05-14 21:36:07 +02:00
Koen Kanters 8f39ae9d63 Update zigbee-shepherd-converters to 9.0.8. 2019-05-14 21:18:48 +02:00
Koen Kanters a09da4fe10 Update zigbee-shepherd-converters to 9.0.7. 2019-05-14 21:12:13 +02:00
Koen Kanters 9cc82701c1 Fix crash when device not in configuration.yaml 2019-05-14 19:25:13 +02:00
Koen Kanters 190dda5104 Update zigbee-shepherd-converters to 9.0.6 2019-05-14 18:04:47 +02:00
Andreas Brett 3d74a6e031 log friendly name when possible (#1524)
* log friendly name when possible

* make travis happy
2019-05-14 17:51:43 +02:00
Koen Kanters 6b7546547d 1.4.0 2019-05-13 18:29:51 +02:00
Koen Kanters 3649fb1bc9 Update zigbee-shepherd-converter to 9.0.5. 2019-05-12 21:09:12 +02:00
Abílio Costa eb2c4cbdee Add support for EDP redy switch (#1519)
Added in https://github.com/Koenkk/zigbee-shepherd-converters/pull/432/files
2019-05-12 21:05:07 +02:00
Andreas Brett f93a3e1c07 Minor spelling correction (#1522)
* Update devicePublish.test.js

* Update devicePublish.js
2019-05-12 21:03:27 +02:00
Koen Kanters ee9584121a Update zigbee-shepherd-converters to 9.0.4. 2019-05-10 18:25:08 +02:00
Koen Kanters ba1eca82eb Reenable joining after 200 seconds. https://github.com/Koenkk/zigbee2mqtt/issues/1429 #1445 2019-05-07 21:16:25 +02:00
Koen Kanters 68d2d0a73d Update zigbee-shepherd-converters to 9.0.3 2019-05-07 19:25:47 +02:00
Koen Kanters d8d78af4ec Query device state on endDeviceAnnce when using device availability. https://github.com/Koenkk/zigbee2mqtt/issues/1383 2019-05-06 20:29:17 +02:00
Koen Kanters 80e682688d Update zigbee-shepherd-converters to 9.0.2. 2019-05-05 20:14:30 +02:00
Koen Kanters c6617fb7d9 Always keep state. https://github.com/Koenkk/zigbee2mqtt/issues/1489 2019-05-02 20:14:44 +02:00
Koen Kanters 26d8d27e85 Update zigbee-shepherd-converters to 9.0.1. 2019-05-02 19:59:23 +02:00
Chris Price 87232988e7 Add Home Assistant support for Philips Hue PAR38 outdoor bulb (#1488) 2019-05-02 19:44:56 +02:00
Koen Kanters a3d26ceeb2 Update zigbee-shepherd-converters to 9.0.0. 2019-05-01 21:50:01 +02:00
Koen Kanters 1f6e64b4c0 Fix Docker container being killed instead of stopped. #1482 2019-05-01 20:47:53 +02:00
Tadej Štajner 919b8a9b4c Add Home Assistant autodiscovery for Paulmann 50043 switch (#1486)
Depends on https://github.com/Koenkk/zigbee-shepherd-converters/pull/424 being merged.
2019-05-01 18:33:36 +02:00
Koen Kanters 31088255ab Update zigbee-shepherd. https://github.com/Koenkk/zigbee2mqtt/issues/1429 2019-04-30 20:34:28 +02:00
Koen Kanters 39fe50600e Fix crash when there is no state yet. 2019-04-30 19:30:26 +02:00
Koen Kanters a54e256b40 Group configuration via configuration.yaml and group state (#1464)
Group configuration via configuration.yaml and group state.
2019-04-29 20:38:40 +02:00
Koen Kanters 4472c01076 Update zigbee-shepherd-converters to 8.1.5. 2019-04-28 21:14:52 +02:00
Koen Kanters 801be951a4 Discover light for 99432. https://github.com/Koenkk/zigbee-shepherd-converters/pull/416 2019-04-28 21:04:52 +02:00
Koen Kanters cb16ba2f71 Update zigbee-shepherd-converters to 8.1.4. 2019-04-26 21:57:38 +02:00
Koen Kanters 0d587f304e Respond to time requests. https://github.com/Koenkk/zigbee2mqtt/issues/1214 2019-04-26 21:33:29 +02:00
Koen Kanters 21dc1a8c8e Add fan Home Assistant configuration. https://github.com/Koenkk/zigbee-shepherd-converters/pull/416 2019-04-24 20:59:06 +02:00
Andreas Brett 32b76edb7c Improve non-JSON output (#1462)
* Update controller.js

Do not use JSON.stringify when outputting Non-JSON to MQTT. When using JSON.stringify strings are quoted in the MQTT messages but they should not be quoted (MQTT is different from JSON).

* Update controller.js

* Update controller.js

* Update controller.js
2019-04-22 16:29:47 +02:00
Koen Kanters 0eaf0ad5d6 Update zigbee-shepherd-converters. 2019-04-19 20:56:05 +02:00
Javier Rodríguez 1ebd774d6f Support for HLC610-Z Wireless Dimmable Controller (#1451) 2019-04-19 20:44:11 +02:00
Koen Kanters 950b3c7ace Update zigbee-shepherd. 2019-04-19 20:30:39 +02:00
Koen Kanters f8106feb18 Update zigbee-shepherd-converters to 8.1.2 2019-04-18 18:27:41 +02:00
Koen Kanters 69e9dbc5b2 Remove expire_after for action and click. https://github.com/Koenkk/zigbee2mqtt/issues/959 2019-04-17 20:46:27 +02:00
Koen Kanters 75718b360e Don’t identify Trust device as Xiaomi device. https://github.com/Koenkk/zigbee2mqtt/issues/1420 2019-04-17 20:03:40 +02:00
Koen Kanters beb2713cdd Update zigbee-shepherd. 2019-04-17 19:10:53 +02:00
Koen Kanters 2cdbe49385 Merge branch 'master' into dev 2019-04-16 19:57:35 +02:00
Koen Kanters d0e66ed1da Only setup reporting for non battery powered routers. #1064 2019-04-16 17:56:28 +02:00
Koen Kanters 39d6a8e218 1.3.1 2019-04-16 17:47:14 +02:00
Koen Kanters 2f187ae282 Fix device availability. https://github.com/Koenkk/zigbee2mqtt/issues/1395 2019-04-16 17:46:37 +02:00
Koen Kanters 3a5bdffd4e Downgrade zigbee-shepherd. #1378 2019-04-16 17:46:34 +02:00
Simon Rasmussen a1b43d12f6 eCozy homeassitant discovery (#1432)
* WIP

* Fixed paths

* Reverted accidentally removed lines

* Fixed linting issues
2019-04-16 16:31:05 +02:00
Koen Kanters 310f9892d6 Update zigbee-shepherd. 2019-04-14 20:36:01 +02:00
Koen Kanters c2edaed866 Backup coordinator on start. 2019-04-14 18:53:34 +02:00
Koen Kanters 2d4c447ee1 Add CC2652R backup mechanism. 2019-04-14 16:27:02 +02:00
Sembrador b13d87d461 Added support for the L1 and L2 inputs of the xiaomi switch LLKZMK11LM. (#1411)
Added support for the L1 and L2 inputs of the xiaomi switch LLKZMK11LM.
2019-04-13 17:19:05 +02:00
Koen Kanters da9425290e Update zigbee-shepherd. 2019-04-09 21:16:48 +02:00
Koen Kanters 811692fed8 Fix device availability. https://github.com/Koenkk/zigbee2mqtt/issues/1395 2019-04-09 19:17:16 +02:00
Oli 78ff9b1937 harmonize coordinator output statement (#1386)
resize the coordinator payload to be harmonize with the other output.
2019-04-09 19:01:59 +02:00
Oli c6011c0911 simplify the cies for ias (#1387)
* simplify the cies for ias

minimize the code for the cies for ias stuff to be as short as it need.
add some comments.

* fix eslint build error
2019-04-09 18:23:55 +02:00
Koen Kanters 9f16f99424 Update zigbee-shepherd. 2019-04-08 20:32:44 +02:00
Koen Kanters 08ad3a877d Update zigbee-shepherd. 2019-04-07 20:43:52 +02:00
Koen Kanters 24780e6eac Home Assistant: publish counter value for click and action payloads. #959 2019-04-07 18:11:16 +02:00
Simon Rasmussen 2554cf8e8b Improved devicePublish topic parsing (#1373)
* Refactored device publish parsing and added ability to set attributes directly

* Fixed topic subscriptions and null json object

* Fixed tests

* Added more testing of attribute

* Fixed linting issue.
2019-04-07 17:51:27 +02:00
Koen Kanters 4aa5877797 Add extra is pingable logging. #775 2019-04-07 17:47:06 +02:00
Koen Kanters 61942f8411 Update zigbee-shepherd (zigbee 3.0 support, yay!) 2019-04-07 17:43:51 +02:00
Koen Kanters 00ebd441a0 1.3.0 2019-04-07 17:33:34 +02:00
Koen Kanters 4843d85fe9 Update zigbee-shepherd-converters to 8.1.1. 2019-04-07 15:38:27 +02:00
Koen Kanters 32db1fd07a Fix acceptDevIncoming. #538 2019-04-01 20:30:27 +02:00
Koen Kanters cee35c66e6 Don’t setup reporting for CC2530 router. #1227 2019-04-01 19:51:14 +02:00
Koen Kanters 76d7861671 Only do read after write when retrieve_state is enabled. #1349 2019-03-30 21:03:54 +01:00
Koen Kanters 35fd1a68fc Update zigbee-shepherd-converters to 8.1.0 (always assume state). #1349 2019-03-30 20:50:40 +01:00
Koen Kanters 8828ee60ae Setup reporting for all attributes when cluster has no attributes. #1064 2019-03-30 18:20:07 +01:00
Koen Kanters 55c3edfa95 Home Assistant: skip state when bulb is already on when setting color or color temperature. #1349 2019-03-30 18:19:10 +01:00
Koen Kanters 2f52b851a9 Add extra acceptDevIncoming logging. #538 2019-03-30 16:48:58 +01:00
Koen Kanters 91bc56a09f Update zigbee-shepherd (cc-znp). #1343 2019-03-29 20:10:02 +01:00
Koen Kanters c737f569f9 Allow already connected devices to rejoin. #1294 #1334 2019-03-29 19:18:15 +01:00
Koen Kanters de4f9f44fd Fix bind by friendly name. #176 2019-03-29 19:10:13 +01:00
Erik van Luijk 21714855bf Pr expcliv2 (#1344)
* Add multiplatform support

Using the experimental manifest support in docker one can
create a manifest that contain references to other images/tags
build for various architectures. When someone pulls koenkk/zigbee2mqtt
correct image is automatically selected.

Please note that experimental cli support needs to be enabled.

* Update docker.sh

* Use docker cli with experimental cli support enabled only when needed
2019-03-29 18:52:45 +01:00
Koen Kanters 50986591c1 Fix tests. 2019-03-28 21:08:18 +01:00
Erik van Luijk e10999f0f2 Add multiplatform support (#1336)
* Add multiplatform support

Using the experimental manifest support in docker one can
create a manifest that contain references to other images/tags
build for various architectures. When someone pulls koenkk/zigbee2mqtt
correct image is automatically selected.

Please note that experimental cli support needs to be enabled.

* Update docker.sh
2019-03-28 20:56:40 +01:00
Koen Kanters 7015741a08 Add dateCode to getDeviceInfoForMqtt. #1213 2019-03-28 19:58:21 +01:00
Bruceforce 64fa02abab Update ISSUE_TEMPLATE.md (#1338)
Handle the "FAQ stuff" as a comment and give the user a basic issue template.
2019-03-28 16:23:41 +01:00
Koen Kanters 7e6dc67861 Update zigbee-shepherd-converters to 8.0.14. 2019-03-27 18:22:40 +01:00
Koen Kanters 3c5727b320 Add dateCode en update zigbee-shepherd. https://github.com/Koenkk/zigbee2mqtt/issues/1213 2019-03-27 18:18:49 +01:00
Koen Kanters 9ef4d2b810 Check if message has endpoints. 2019-03-27 17:31:25 +01:00
Koen Kanters e96dac2596 Log endpoint on zigbee message received. #642 2019-03-27 17:09:55 +01:00
Koen Kanters 9a15e8c118 Improve ban functionallity. #816 2019-03-26 21:40:31 +01:00
Justin Hornosty 25408769e6 Publish and respond to bridge/config/devices/get (#1329)
* - When sent a empty payload to bridge/config/devices/get , publish to
  'bridge/config/devices'
- For bridge/config/devices & bridge/config/devices/get only ever
  publish to the corresponding topic if a empty payload is sent.
- Make sure devicesPublish doesn't treat messages to
  bridge/config/devices/get as a zigbee device.

* fix eslinting errors

* Update bridgeConfig.js
2019-03-26 20:40:50 +01:00
Koen Kanters 2328ecb2ee Update zigbee-shepherd-converters to 8.0.13. 2019-03-25 21:53:39 +01:00
carlos-villanueva b2a453bec3 Add support for smartthings button (model: IM6001-BTP01) (#1312)
* Add support for smartthings button (model: IM6001-BTP01)

* Fix lint
2019-03-24 15:05:56 +01:00
Koen Kanters 20d9bac317 Don’t ping in Xiaomi extension when device availability is enabled. #1248 2019-03-24 14:46:38 +01:00
Koen Kanters 40596bab6a Always ping xiaomi devices through ‘basic’ mechanism. #1248 2019-03-24 14:38:08 +01:00
Willi Eggeling 69d04d0648 shutdown controller on SIGTERM (#1313)
Previously, the controller was only properly shutdown on SIGINT.
SIGTERM is used by kill (unix) and to stop Docker containers.
2019-03-24 14:27:49 +01:00
Koen Kanters 363f4e1c3b Merge branch 'master' into dev 2019-03-24 14:26:49 +01:00
Koen Kanters 008fda4d90 Introduce new ping mechanism (‘basic’) and use it for Xiaomi. https://github.com/Koenkk/zigbee2mqtt/issues/1248 2019-03-23 17:45:28 +01:00
Koen Kanters c64158b75d CC2530/CC2531 routers are not Xiaomi devices. https://github.com/Koenkk/zigbee2mqtt/issues/1248 2019-03-23 17:20:30 +01:00
Koen Kanters 1ea694cb1a Update zigbee-shepherd-convertes to 8.0.12. 2019-03-23 15:32:18 +01:00
Koen Kanters e537784d34 Update zigbee-shepherd-converters to 8.0.11. 2019-03-22 23:37:07 +01:00
Koen Kanters 0277591085 Update zigbee-shepherd-converters to 8.0.10. 2019-03-22 22:45:59 +01:00
Koen Kanters 7b2480be52 Update zigbee-shepherd-conveters to 8.0.9. 2019-03-21 20:34:54 +01:00
Martin Helff 70c30736a1 add more details to device list (#1296) 2019-03-21 20:00:13 +01:00
Koen Kanters 24cf72f166 Update zigbee-shepherd. https://github.com/Koenkk/zigbee2mqtt/issues/1295 2019-03-21 19:59:25 +01:00
Martin Helff e5081b2856 set reportableChange default value to 1 to avoid report flooding (#1293) 2019-03-21 19:43:15 +01:00
Fredrik Lindqvist 4048cb81a4 Update discord link to the #welcome-rules channel (#1290)
New invite link for the new channel structure.
2019-03-20 07:10:37 +01:00
Koen Kanters 2af2a8ea05 Update zigbee-shepherd-converters to 8.0.8. 2019-03-19 20:58:12 +01:00
Oli 1b066d9f59 extend controller.js function getDeviceInfoForMqtt (#1274)
* Add Discord channel. https://github.com/Koenkk/zigbee2mqtt.io/issues/31

* extend controller.js function getDeviceInfoForMqtt

extend controller.js with 
``
zclVersion,
appVersion,
stackVersion,
hwVersion,
swBuildId,
``

* Rework #2

Only Publish hwVersion and swBuildId as this seems to be valid as posible.
Map with default option 'unknown' to be in a good way.

* Fix tests

* Update README.md
2019-03-19 20:29:41 +01:00
Koen Kanters 5c9b31b2fc Don’t create state when cache_state is set to false. #1287 2019-03-19 20:02:17 +01:00
Koen Kanters 61d85af3fd Publish brightness: 0 when turn off trough brightness. https://github.com/Koenkk/zigbee-shepherd-converters/issues/353 2019-03-19 19:43:06 +01:00
Martin Helff 789ec0cc90 query groups through MQTT bridge/config/groups (#1276)
* query groups through MQTT bridge/config/groups

* linter adjustments

* linter adjustments
2019-03-19 19:18:22 +01:00
Koen Kanters b97f5d1afa Add Discourse link. 2019-03-19 19:15:58 +01:00
Koen Kanters 4cb0c0bbb0 Update zigbee-shepherd-converters to 8.0.7. 2019-03-18 18:21:21 +01:00
Stoinov 6d24a49062 Expand attribute output. #493 (#1277)
* Expand attribute output. #493

If attribute is actually an Object, expand it in the format `topic/key-subkey` in order to keep the same amount of topic levels for predictable parsing.
This only expands the first level of contained object. If more expansion are needed a more robust method should be implemented rather than just nesting `if`s.

* Fixing whitespace

fixing https://travis-ci.org/Koenkk/zigbee2mqtt/builds/507616980

* first time splitting line... obviously

Not sure what the proper approach is, but I guess we can put all params on new line.

* identation... really...

How is that `eslint`? any other requests?
2019-03-18 18:17:29 +01:00
Koenkk bee722c9c4 Skip re-transmitted Xiaomi messages. #1238 2019-03-18 17:59:36 +01:00
Koenkk 36bba0154d Fix groupid logging. 2019-03-18 17:32:53 +01:00
Oli a2a90bcdbd Log zigbee2mqtt version information to bridge/config (#1267)
* add coordinator_firmware to bridge/config

* Add zigbee2mqtt version and commit

* Whoops
2019-03-17 20:07:24 +01:00
Koen Kanters 1043053812 Update zigbee-shehperd. 2019-03-17 20:03:07 +01:00
Koen Kanters e6044da604 Implemented device debounce option. #1264 2019-03-16 23:41:46 +01:00
Koen Kanters a8cf925fcb Update zigbee-shepherd, zigbee-shepherd-converters and zcl-id. 2019-03-16 22:55:37 +01:00
Koen Kanters ad835e090b Add Discord channel. https://github.com/Koenkk/zigbee2mqtt.io/issues/31 2019-03-16 20:53:22 +01:00
Koen Kanters 3a96473e2b Improve device bind robustness. https://github.com/Koenkk/zigbee2mqtt/issues/176 2019-03-16 20:07:34 +01:00
Koen Kanters 661f79ce93 Whoops! Fix tests 2019-03-15 23:42:36 +01:00
Koen Kanters 7461fec28b Update zigbee-shepherd-converters to 8.0.4. 2019-03-15 23:33:24 +01:00
Koen Kanters 8b4b9bea19 Refactor property cache responsibility to state. 2019-03-15 23:18:19 +01:00
Koen Kanters fdcf2e8c3d Option to set Home Assistant discovery topic. #1019 2019-03-15 22:41:39 +01:00
Koen Kanters b39e195763 Update zigbee-shepherd. 2019-03-15 22:06:02 +01:00
Koen Kanters f2cdbeab38 Update zigbee-shepherd-converters to 8.0.3. 2019-03-15 21:58:49 +01:00
Koen Kanters f37d52b870 Discover click sensor for QBKG03LM, QBKG04LM, QBKG11LM and QBKG12LM. https://github.com/Koenkk/zigbee2mqtt/issues/723 2019-03-15 21:52:21 +01:00
Koen Kanters 969585c84e Allow to bind specific endpoint. #176 2019-03-15 21:19:42 +01:00
Koen Kanters d4d85633d2 Log groupID. #1238 2019-03-15 19:07:26 +01:00
Koen Kanters f54f3bd40f Add coordinator to zigbee2mqtt/bridge/config/devices. #1236 2019-03-14 20:30:06 +01:00
Koen Kanters 03ca8ec24d Update zigbee-shepherd-converters to 8.0.2. 2019-03-13 20:02:53 +01:00
Koen Kanters a65fbd6e2c Update zigbee-shepherd-converters to 8.0.1. 2019-03-13 19:48:31 +01:00
Koen Kanters ac28ca2841 Update to zigbee-shepherd-converters 8.0.0 2019-03-13 19:41:58 +01:00
Koen Kanters 79d11e295b Fix crash on empty advanced section. https://github.com/Koenkk/zigbee2mqtt/issues/1237 2019-03-12 21:58:45 +01:00
Koen Kanters 9f31cd86a3 Implemented MQTT group add and remove. https://github.com/Koenkk/zigbee2mqtt/issues/764 2019-03-12 21:19:04 +01:00
Koen Kanters c722b611dd Fix livolo queue push. #1241 2019-03-12 20:14:58 +01:00
Roger 3c4fa40a32 Add Securifi Peanut Smart Plug (#1230) 2019-03-11 17:55:25 +01:00
Koen Kanters d81a972f1b Allow to override Home Assistant device discovery payload. https://github.com/Koenkk/zigbee2mqtt/pull/1030 2019-03-10 21:48:40 +01:00
Koen Kanters 0f9333f8b9 Fix elapsed being a string value instead of bool. https://github.com/Koenkk/zigbee2mqtt/pull/1206 2019-03-10 21:34:20 +01:00
Koen Kanters 6e60063337 Update zigbee-shepherd and zigbee-shepherd-converters to 7.2.8. 2019-03-10 14:12:11 +01:00
Andrey 438626691e Allow to configure elapsed via MQTT (#1206)
* Allow to configure elapsed via MQTT

* Update bridgeConfig.js
2019-03-10 14:04:09 +01:00
qm3ster a978b26001 Use toStrictEqual for objects
Not sure why `jest-codemods` didn't do this.
Changed some primitives to use `toBe`.
2019-03-10 13:32:36 +01:00
qm3ster 7cec70aba8 Add @types/jest for editor completion 2019-03-10 13:32:36 +01:00
qm3ster df1825d65e Use mockReturnValue instead of mockImplementation where possible 2019-03-10 13:32:36 +01:00
qm3ster 532b3b2484 Use toHaveBeenNthCalledWith in some cases 2019-03-10 13:32:36 +01:00
qm3ster 84a5277d45 Replace sinon with jest builtins 2019-03-10 13:32:36 +01:00
qm3ster acbab01b7e Apply jest-codemods
`chai` ELIMINATED
2019-03-10 13:32:36 +01:00
qm3ster 6a4073b305 Use jest instead of mocha
Oh nice, coverage works now
2019-03-10 13:32:36 +01:00
Koen Kanters 18aee4803b Merge branch 'master' into dev 2019-03-09 21:45:24 +01:00
Koen Kanters e5ca977579 1.2.1 2019-03-09 21:40:09 +01:00
Koen Kanters 1e1e0e4ca9 Fix no console logging. #1218 2019-03-09 21:36:07 +01:00
qm3ster 3b1fae1452 Remove whitespace 2019-03-09 21:09:39 +01:00
qm3ster cf2f10394a Mock fs in settings test 2019-03-09 21:09:39 +01:00
qm3ster 9eed7e271e Extract IO from settings.js 2019-03-09 21:09:39 +01:00
qm3ster 07765093be Fix all typos of separate 2019-03-09 21:09:39 +01:00
Koen Kanters 5f19d9cc82 1.2.0 2019-03-09 21:03:16 +01:00
Koen Kanters e2ebe5e1ff Update zigbee-shepherd-converters to 7.2.7. 2019-03-09 17:04:41 +01:00
qm3ster a93838be15 codemod: object-shorthand
Also fixed `new (` and `formatter` by hand.
2019-03-09 16:30:05 +01:00
qm3ster 044e8466ed Simplify settings getters 2019-03-09 16:30:05 +01:00
qm3ster c0bdf2e3a2 Lazy load settings on first use 2019-03-09 16:30:05 +01:00
qm3ster 9321a04ecc Move resolveEntity into settings.js
Had to refer to `module.exports.`
because all of those functions get mocked in tests.
2019-03-09 16:30:05 +01:00
Koen Kanters 184eef72b0 Update zigbee-shepherd-converters to 7.2.6. 2019-03-08 17:39:15 +01:00
Mihal Malostanidis bb6c226d55 Test improvements (#1207)
* Add missing `zcl-id` dependency

* Improve devicePublish test

Now passes in both mocha and jest
Each test now waits for all publishes, such as readbacks,
and asserts their number.
Replaced `calledOnce` and such with numeric assertion,
for a more informative error message.

* Use sinon default sandbox

* Take assert out of chai

Improves clutter, but also `jest-codemods` also makes use of this.

* Replace proxyquire with simple cache delete

* Reduce shared mutable state in settings.test
2019-03-08 16:56:53 +01:00
Koen Kanters e892a54013 Update zigbee-shepherd-converters to 7.2.5. 2019-03-06 22:09:51 +01:00
Koen Kanters 2c6176ff10 Fix parse topic when topic ends with postfix. https://github.com/Koenkk/zigbee2mqtt/issues/1200 2019-03-06 21:38:49 +01:00
Koen Kanters 83b8fc9778 Add top and bottom to postfixes. https://github.com/Koenkk/zigbee-shepherd-converters/pull/319 2019-03-06 21:08:33 +01:00
Koen Kanters f0e9ebe4ed Fix readRsp spamming no converter available messages. https://github.com/Koenkk/zigbee2mqtt/issues/1064 2019-03-05 19:41:59 +01:00
Koen Kanters 8902bd1d60 Fix zcl-id dependency. https://github.com/Koenkk/zigbee2mqtt/issues/1182 2019-03-05 19:27:37 +01:00
Markus Goy 1857ac525b Added Home Assistant autodiscovery configuration (#1187) 2019-03-04 20:04:42 +01:00
Koen Kanters 6427da244f Implement attribute output. https://github.com/Koenkk/zigbee2mqtt/issues/493 2019-03-04 18:13:36 +01:00
Koen Kanters 339816c160 Update zigbee-shepherd-converters to 7.2.4 2019-03-04 17:41:33 +01:00
Koen Kanters 2a3670d3d7 Update zigbee-shepherd-converters to 7.2.3 2019-03-03 18:37:46 +01:00
Koen Kanters 889e972176 Update zigbee-shepherd-converters to 7.2.2. https://github.com/Koenkk/zigbee2mqtt/issues/1176 2019-03-02 17:27:29 +01:00
Koen Kanters e213356c40 Update zigbee-shepherd-* dependencies. 2019-03-02 17:04:21 +01:00
Andreas Brett 1cde620d70 add support for local ISO8601 timestamp format (#1171)
* add support for local ISO8601 timestamp format

added local ISO8601 timestamp format for local rather than UTC-based timestamps

ISO8601 = 2019-03-01T15:32:45.941+0000
ISO8601_Local = 2019-03-01T16:32:45.941+0100 (for TZ GMT+1)

* fixed indentation

* tabs to spaces

* comply with Travis

* comply with Travis once again

* Removed spaces to make Travis happy

* updates
2019-03-02 16:47:36 +01:00
Koen Kanters ae14fa5cd6 Update zigbee-shepherd-converters to 7.2.0. 2019-03-02 16:35:00 +01:00
Jakub 672a0cac4f Hide network_key from debug output (#1169)
* Hide network_key from debug output

There's no need to print this key.

* strings must use singlequote

* Update zigbee.js
2019-03-02 14:04:52 +01:00
Andreas Brett 4ea55fe22a fixed typo (#1173) 2019-03-01 17:15:03 +01:00
Koen Kanters 05769ce1a3 Update zigbee-shepherd. #518 #176 2019-02-28 20:31:57 +01:00
Koen Kanters 61116ec670 Fix tests. 2019-02-26 21:06:48 +01:00
Koen Kanters 709046db2a Add binary battery low sensor for HS1SA and HS3SA. https://github.com/Koenkk/zigbee2mqtt/issues/1159 2019-02-26 21:00:20 +01:00
pixel::doc bef8a682ca Create docker-compose.yml (#1156) 2019-02-26 20:55:51 +01:00
Koen Kanters 8f0794cb8f Also assume brightness on publish. https://github.com/Koenkk/zigbee2mqtt/issues/1155 2019-02-26 20:53:30 +01:00
Koen Kanters cd2fb54615 Changes to report/bind functionallity. 2019-02-26 20:46:34 +01:00
Koen Kanters 7893f9256f Refactor report to new queue mechanism. 2019-02-26 19:33:32 +01:00
Koen Kanters 09f26a104c Restore zigbee.js changes. 2019-02-26 19:33:32 +01:00
Koen Kanters 5ffae5a09a Remove unecessary device param. 2019-02-26 19:33:32 +01:00
jbn f7ceb62eec fix lint more errors 2019-02-26 19:33:32 +01:00
jbn b8f689fe6e fix lint errors 2019-02-26 19:33:32 +01:00
jbn 09e0fe8e3f setup automatic attribute change reporting 2019-02-26 19:33:32 +01:00
jbn fdf97180b0 Fix race condition when configuring devices 2019-02-26 19:33:32 +01:00
Koen Kanters 5a9aef6d3b Change to action_color. https://github.com/Koenkk/zigbee-shepherd-converters/pull/304 2019-02-26 19:29:53 +01:00
Koen Kanters 863230eaa3 Fix cover_position typo. #294 2019-02-25 17:56:47 +01:00
Koen Kanters cb0cc149a1 ZNCLDJ11LM position Home Assistant discovery. #294 2019-02-24 21:35:48 +01:00
Koen Kanters 516bd704c6 Allow devices and groups to be specified in separate file. https://github.com/Koenkk/zigbee2mqtt/issues/1148 2019-02-24 15:49:41 +01:00
Joe Lu 46e75374b6 - added AXIS Gear and Keen Home vent to homeassistant.js (#1150) 2019-02-24 13:29:46 +01:00
Koen Kanters ee167e603a Update zigbee-shepherd-converters to 7.1.12. 2019-02-23 19:30:17 +01:00
Koen Kanters 9b12933a99 Dont cache action_group. 2019-02-23 19:13:01 +01:00
Koen Kanters ea7a4b1955 Remove last_seen from state when last_seen is disabled. https://github.com/Koenkk/zigbee2mqtt/issues/1075 2019-02-23 16:22:01 +01:00
Koen Kanters 147a130628 Update zigbee-shepherd-converters to 7.1.11 2019-02-23 16:02:45 +01:00
Koen Kanters 1fda02ae7c Allow to change device specific options via MQTT. https://github.com/Koenkk/zigbee2mqtt/issues/1132 2019-02-22 20:10:00 +01:00
Koen Kanters 4a664cf230 Implement zigbee queue. #1027 2019-02-22 18:58:50 +01:00
Andreas Brett 1a0baee788 log address resolution errors through MQTT (#1145)
* log address resolution errors through MQTT

* fixed params
2019-02-22 12:49:08 +01:00
Andreas Brett 1287a596f9 fix typo (#1142) 2019-02-22 10:54:10 +01:00
Andreas Brett 1862c8b035 fixed typo (#1135)
* fixed typo

* Update deviceConfigure.js
2019-02-21 18:47:05 +01:00
Andreas Brett 8c848b8368 add device model to log (#1136)
* add device model to log

* Update deviceReceive.js
2019-02-21 18:45:22 +01:00
Koen Kanters bdfabeb3da Discover linkquality sensor for all devices. https://github.com/Koenkk/zigbee2mqtt/issues/757 2019-02-20 20:10:38 +01:00
Koen Kanters ec0ee53c7a Log zigbee publish errors to MQTT. #1123 2019-02-20 17:57:28 +01:00
Koen Kanters 14f5c4d3c9 Prepare Home Assistant discovery for group support. #764 2019-02-19 19:43:50 +01:00
Koen Kanters f3e13f16f3 Add more don’t cache properties. https://github.com/Koenkk/zigbee-shepherd-converters/pull/284 2019-02-19 19:31:58 +01:00
Koen Kanters 061285bd17 Update zigbee-shepherd. 2019-02-19 19:31:05 +01:00
Andreas Brett 25448f823e Fix typo (#1124) 2019-02-19 19:16:18 +01:00
Koen Kanters 99006895b5 Merge branch 'master' into dev 2019-02-19 19:15:09 +01:00
Koen Kanters 26bed2d998 Allow to configure last_seen via MQTT. https://github.com/Koenkk/zigbee2mqtt/issues/1075 2019-02-18 19:46:57 +01:00
Koen Kanters cc45413e2d Add settings.set api. 2019-02-18 19:46:19 +01:00
Koen Kanters ba77860489 Exit when zigbee-shepherd fails to start. https://github.com/Koenkk/zigbee2mqtt/issues/1110 2019-02-18 19:24:26 +01:00
Koen Kanters 14377c04a0 Update zigbee-shepherd. 2019-02-18 19:19:52 +01:00
Glen Takahashi 3238687f60 Add group membership command (#1056)
* Group membership

* Fix lint

* Update deviceGroupMembership.js

* Update deviceGroupMembership.js
2019-02-18 18:21:54 +01:00
Ruslan Sayfutdinov 0632f83baf Create default and system MQTT postfixes (#1114) 2019-02-18 17:57:57 +01:00
Koen Kanters 259a3417e2 Coordinator group is not needed anymore. #102 2019-02-18 17:42:50 +01:00
Koen Kanters a20ec7caa1 Update zigbee-shepherd-converters to 7.1.10. 2019-02-17 15:14:36 +01:00
Koen Kanters b08bf33ccf Soft reset via MQTT. https://github.com/Koenkk/zigbee2mqtt/issues/1099 2019-02-16 19:40:34 +01:00
Koen Kanters 577bb0d12c Replace force_update with expire_after for home assistant buttons. https://github.com/Koenkk/zigbee2mqtt/issues/959 2019-02-15 23:31:44 +01:00
JLFN 92d88b680a All in one install (#1098)
* All in one install

Need to have user Pi added

* move to folder scripts
2019-02-15 23:08:35 +01:00
JLFN 00900958ef Zigbee2Socat installer (#1097)
* Zigbee2Socat

Zigbee2Socat installer


    -a, --addr IP       Listen on this IP-address
    -p, --port PORT     Listen on this port
    -u, --uninstall     Uninstall zigbee-socatvusb.service
    -v, --verbose       Print more information
    -m, --man           Make and display manual
    -h, --help          Display this help message

* All in one installer

* Update installer.sh

* Delete installer.sh

* Rename to install

* Rename zigbee2socat_install.sh to scripts/zigbee2socat_installer.sh
2019-02-15 23:08:11 +01:00
Koen Kanters 11a6e36a82 Correctly resolve device friendlyName when lookup via ieeAddr. 2019-02-14 20:12:27 +01:00
Koen Kanters d6b9627146 Don’t return error when coordinator is already in group. https://github.com/Koenkk/zigbee2mqtt/issues/1064 2019-02-14 19:47:25 +01:00
Koen Kanters 15cad740ee Update zigbee-shepherd-converters to 7.1.9. 2019-02-14 19:45:52 +01:00
Koen Kanters ab14cca0ee Update coordinator group documentation link. 2019-02-14 19:34:29 +01:00
MoskitoHorst 87889c0688 tint Remote (#1085)
* tint Remote

Added tint remote to group devices

* Update coordinatorGroup.js

* Update homeassistant.js
2019-02-14 19:33:21 +01:00
Koen Kanters 17a6fff3ce Publish group state. #764 2019-02-14 18:13:51 +01:00
Koen Kanters f171d54e4b Refactor extension names. 2019-02-13 21:03:23 +01:00
Koen Kanters 9faeb53ddb Refactor addCoordinatorToGroup. 2019-02-13 20:43:22 +01:00
Koen Kanters 21a782d2c6 Reporting: also bind cluster to coordinator. https://github.com/Koenkk/zigbee2mqtt/issues/1064 2019-02-13 20:26:31 +01:00
Koen Kanters 88cec5dfa6 Check for valid Zigbee channel. https://github.com/Koenkk/zigbee2mqtt/issues/1077 2019-02-13 20:06:14 +01:00
Koen Kanters a62f4289a7 Log more to MQTT. #1075 2019-02-13 19:49:06 +01:00
Koen Kanters 1b5e010cd3 Cleanup docs. 2019-02-13 19:30:14 +01:00
Koen Kanters 0f053425f3 Merge branch 'master' into dev 2019-02-13 19:28:35 +01:00
Koen Kanters 04e68014da Update link to zigbee2mqtt.io. #1072 2019-02-12 21:39:37 +01:00
Koen Kanters 54dbb9732f Cleanup dependencies. 2019-02-12 21:28:39 +01:00
Koen Kanters 8703847337 Merge branch 'master' into dev 2019-02-12 21:26:37 +01:00
Koen Kanters a85c68cca0 Update link. 2019-02-12 21:19:14 +01:00
Koen Kanters 4592b00fe1 Move docs to zigbee2mqtt.io repo. #1072 2019-02-12 21:16:42 +01:00
Koen Kanters d9ddce5797 Delete CNAME 2019-02-12 19:51:41 +01:00
qosmio b3310c49ca Adding support for OSRAM Lightify BR30 RGBW to Home Assistant (#1070)
* Add support for Sengled E12-N14 (BR30) Light

* .

* Add Osram BR30 RGBW LED to HA
2019-02-12 19:33:45 +01:00
Koen Kanters 781b542f92 Update zigbee-shepherd. #937 2019-02-12 19:21:18 +01:00
Koen Kanters 43726d8bb1 Create CNAME 2019-02-12 16:01:00 +01:00
Koen Kanters 8137b6f417 Delete CNAME 2019-02-12 15:24:42 +01:00
Koen Kanters c439508129 Create CNAME 2019-02-12 15:22:26 +01:00
Koen Kanters e5233494af Update zigbee-shehperd-converters to 7.1.8. 2019-02-11 19:59:50 +01:00
Wesley Elfring a2d378cc86 Add CC2530 + CC2591 case to docs (#1068)
Add info about a 3d printed case option for the CC2530 + CC2591 combination to the documentation
2019-02-11 19:37:09 +01:00
Koen Kanters 3d151298ae Update zigbee-shepherd-converters to 7.1.7. 2019-02-10 20:35:26 +01:00
Koen Kanters 5554579683 Fix configure section documentation. #1058 2019-02-10 20:05:13 +01:00
Russell Joyce ce2455510b Fixed link (and minor text edits) in 'How to support new devices' (#1054) 2019-02-10 19:29:02 +01:00
Russell Joyce bf526f6f50 Added Home Assistant support for Innr RS 225 bulb (#1053) 2019-02-10 14:40:54 +01:00
Koen Kanters 004f4a5eb9 Update zigbee-shepherd-converters to 7.1.5. 2019-02-09 20:25:08 +01:00
Koen Kanters 059e4719c6 Log ‘Failed to ping’ on debug instead of error when device is already unavailable. #775 2019-02-09 19:50:32 +01:00
timstanley1985 a0278b7577 Allow to override Home Assistant discovery configuration. (#1030)
* Add expiry_after configuration option

* Failed attempt at moving expire_after to under a homeassistant sub-section

* Update.
2019-02-09 19:42:31 +01:00
Koen Kanters 0f89053d05 Update zigbee-shepherd-converters to 7.1.4. 2019-02-09 01:01:08 +01:00
way2many e1ff6bdac5 Add support for Hue white ambiance suspension Fair (#1048) 2019-02-09 00:37:07 +01:00
Koen Kanters 73221f50f5 Merge branch 'master' into dev 2019-02-09 00:36:04 +01:00
Koen Kanters 37405ee079 1.1.1 2019-02-09 00:33:06 +01:00
Koen Kanters 52fb19360e Revert "Set state of stateless properties to ‘idle’ after publish. #959"
This reverts commit 0826db07d0.
2019-02-09 00:29:40 +01:00
Koen Kanters e47b672bcb Revert "Fix Home Assistant automation trigger reliability by adding a small delay. #958"
This reverts commit f4bf504642.
2019-02-09 00:29:16 +01:00
Koen Kanters 63c88cba5b Revert "Fix tests."
This reverts commit b6fda868ed.
2019-02-09 00:28:59 +01:00
Koen Kanters f0d0a62471 Update zigbee-shepherd. https://github.com/Koenkk/zigbee2mqtt/issues/1001 2019-02-09 00:26:18 +01:00
Bruceforce a497cf0457 Added information on how to flash firmware without re-pairing (#1045)
* Added information on how to flash firmware without re-pairing

* Fixed typos and added `permit_join` info

* Update index.md
2019-02-08 18:29:07 +01:00
pfischbach ed5675960e Update homeassistant.js
Add support for Bosch Motion Sensor RADON TriTech ZB
2019-02-07 19:46:16 +01:00
Koen Kanters ba5bf3c209 Remove payload.command_topic_prefix from payload. #1046 2019-02-07 19:33:00 +01:00
Glen Takahashi e40a3ba3bf Add docs on how to use HUSBZB to sniff (#1036)
* Add docs on how to use HUSBZB to sniff

* Update index.md
2019-02-06 21:26:17 +01:00
Glen Takahashi ecf1b9ded4 Show how to also get network key without re-pairing device (#1035)
* Show how to also get network key without re-pairing device

* Update how_to_sniff_zigbee_traffic.md
2019-02-06 21:21:58 +01:00
orrpan 314ab1b705 Venv documentation (#1033)
* Added guide for virtual environment

* grammer

* Update virtual_environment.md

* Update virtual_environment.md

* Update index.md
2019-02-06 21:12:23 +01:00
Koen Kanters b6fda868ed Fix tests. 2019-02-06 20:52:44 +01:00
Koen Kanters 443a14e40a Add coordinator to group 99 by default. https://github.com/Koenkk/zigbee2mqtt/issues/997 2019-02-06 20:33:58 +01:00
Koen Kanters c68790f2c4 Fix layout. 2019-02-06 19:51:27 +01:00
JLFN c9d00875c0 cc2530 with esp8266 (#1025)
* cc2530 with esp8266

Running cc2530 on an esp8266 with Espeasy with ser2net and then mounting on zigbee2mqtt server  with socat.

* Update esp8266_cc2530.md

* Update esp8266_cc2530.md

* Update esp8266_cc2530.md

* Update esp8266_cc2530.md

* Rename esp8266_cc2530.md to how_to_esp8266_with_cc2530.md

* Rename how_to_esp8266_with_cc2530.md to how_tos_esp8266_with_cc2530.md

* Update
2019-02-06 19:50:47 +01:00
Koen Kanters 0120284356 Update CC2531 flashing instructions. 2019-02-06 19:18:46 +01:00
Koen Kanters aa9e81d64d Fix integrity checksum failed #1026 2019-02-06 08:12:42 +01:00
Koen Kanters f4bf504642 Fix Home Assistant automation trigger reliability by adding a small delay. #959 2019-02-05 18:53:51 +01:00
Koen Kanters 5fc7760db6 Update zigbee-shepherd-converters to 7.1.3. 2019-02-05 18:26:17 +01:00
Koen Kanters ffa4fe35d9 Update availability_timeout documentation. #1020 2019-02-05 18:05:15 +01:00
Koen Kanters 778720b1b5 Fix availability_timeout typo. 2019-02-05 17:43:22 +01:00
Koen Kanters 0826db07d0 Set state of stateless properties to ‘idle’ after publish. #959 2019-02-05 17:41:47 +01:00
Koen Kanters 7642b295e1 Add option to enable livolo code. #592 2019-02-04 18:39:45 +01:00
Koen Kanters c9c599b60b Refactor publishDeviceState to publishEntityState (for future group support). 2019-02-04 18:36:49 +01:00
ptvo c0a87ff520 Improved Livolo extension (#1016)
* Improved Livolo extension (pause polling after 3 unsuccessful attempts)

* Added: queuing of all Zigbee messages

* Fixed problem with .startsWith
2019-02-04 16:55:44 +01:00
Glen Takahashi 4fbb6667ef super minor group typo (#1013) 2019-02-04 16:53:15 +01:00
Koen Kanters 1357b06185 Fix CC2530 link. 2019-02-03 18:42:30 +01:00
Koen Kanters 6d16875a37 Update zigbee-shepherd-converters to 7.1.2 2019-02-03 18:16:01 +01:00
Roman Zhukov f7f9a1699b Fix Xiaomi Gas Leak Sensor Homeassistant mqtt discovery config (#1009)
Remove battery sensor
2019-02-03 18:07:17 +01:00
Koen Kanters 46b96640f3 How to improve network range. 2019-02-03 18:06:30 +01:00
Koen Kanters 51c91e685e Check if device has manufName. #1005 2019-02-03 17:11:41 +01:00
Koen Kanters 8a6582739f Add missing SPZB0001. 2019-02-03 15:04:43 +01:00
Koen Kanters c569840d6c Update zigbee-shepherd-converters to 7.1.1. 2019-02-03 14:49:44 +01:00
Koen Kanters 2302240897 Fix linting. 2019-02-03 14:39:35 +01:00
Giel 60349171d2 Always read after write for devices that require it. (#1004)
* Always read after write for devices that require it.

Devices with readAfterWriteTime set, even if it's 0, will get their
state read after write because those devices don't automatically
report it themselves.

Devices that are capable of reporting but don't do it by default
should have `report: true` set in the device-specific config and
we won't read after write.

* Fix tests
2019-02-03 14:39:00 +01:00
Koen Kanters 35f0def29f Comment out Livolo switch code. #592 #1005 2019-02-03 14:25:01 +01:00
Koen Kanters a512ca2bd5 Add ext_pan_id to docs. 2019-02-02 20:32:13 +01:00
Koen Kanters 96dcb93859 Update zigbee-shepherd-converters to 7.1.0. 2019-02-02 20:31:55 +01:00
ptvo 37d516d770 Some improvements (extPanId, .configure, Livolo) (#982)
* Added the new ext_pan_id options (required update of zigbee-shepherd)
Improved code for configure
Added the new extension for Livolo.

* Formatting corrections

* Update controller.js

* Updated Livolo extension

* Improvements in the extensions for Livolo.

* Fixed conflict.

* Add default ext_pan_id.

* Remove duplicate extension.

* Update deviceConfigure.

* Update comment.

* Updates.
2019-02-02 20:09:20 +01:00
Koen Kanters 6c59bff223 Add re-pair warning to alternative flashing methods. #990 2019-02-02 18:20:34 +01:00
Koen Kanters f16616d3a6 Fix alternative flashing methods firmware link. #990 2019-02-02 18:19:26 +01:00
Koen Kanters 959e7458a4 Fix availability tests. 2019-02-02 18:15:03 +01:00
Koen Kanters 5828ee9989 Implement availability blacklist. #775 2019-02-02 18:10:25 +01:00
Koen Kanters 054892641b Check availability for new devices. #775 2019-02-02 17:58:38 +01:00
Koen Kanters c0326ec2bb Add reflashing stick warning. #990 2019-02-02 15:22:59 +01:00
Koen Kanters 189c0f360e Guard callbacks. 2019-02-02 02:14:31 +01:00
Koen Kanters dc70840c8a Use defaultCfg. 2019-02-02 02:00:20 +01:00
Koen Kanters 0b3c8df810 Fix linting. 2019-02-02 01:52:21 +01:00
Koen Kanters 4405e71610 Retrieve device state after device offline -> online. #775 2019-02-02 01:47:53 +01:00
Koen Kanters fd4a88acd0 Refactor zigbee publish queue to zigbee.js 2019-02-02 01:41:05 +01:00
Koen Kanters 3963a8d26f Refactor ping queue to zigbee.js. 2019-02-02 00:57:51 +01:00
Koen Kanters 720addd906 Update zigbee-shepherd-converters to 7.0.30. 2019-02-02 00:53:18 +01:00
Koen Kanters 4558bffd41 Don’t setup reporting for binding, use report functionallity. #782 2019-02-02 00:37:42 +01:00
Koen Kanters 89c66094c6 Setup reporting for X/Y color. #966 2019-02-02 00:35:45 +01:00
Koen Kanters ae08deb2fd Refactor and remove unnecessary bind. #966 2019-02-02 00:31:30 +01:00
Koen Kanters ff02e54f25 1.1.1 2019-02-01 23:36:20 +01:00
Koen Kanters 963064dc22 Fix Cannot read property 'close' of undefined. #937 https://github.com/danielwelch/hassio-zigbee2mqtt/issues/97 2019-02-01 23:33:59 +01:00
Koen Kanters 0d9741e511 Update zigbee-shepherd-converters to 7.0.28. 2019-02-01 19:58:12 +01:00
Koen Kanters 7d9c21ba24 Fix reporting. 2019-02-01 19:43:22 +01:00
Koen Kanters b8744ce890 Add reporting feature. #966 2019-02-01 19:04:49 +01:00
Koen Kanters dd8ee60535 Drop node 8 and 9 support. 2019-02-01 17:14:56 +01:00
Koen Kanters d5c6e39e7d Refactor device reconfigure when device comes online and mark online. #966 #775 2019-01-31 21:42:53 +01:00
jbn 588124b971 Add announcement handler to deviceAvailability extension 2019-01-31 21:33:37 +01:00
clockbrain a7eea5ecad Add reparenting statement to end devices (#983) 2019-01-31 20:24:04 +01:00
Koen Kanters e13bdf1a31 Add FAQ to index 2019-01-31 20:20:13 +01:00
Koen Kanters 30823a5a0c Update zigbee-shepherd. 2019-01-31 19:22:14 +01:00
Bruceforce 5bee8ccafe Update how_to_secure_network.md (#963)
* Update how_to_secure_network.md

Make clear that the key consists of 16 hex values and gave an example how to generate a key with command line tools.

* Clarified info about network key notation

* clarified network key notation (dec or hex)

* Update how_to_secure_network.md

Make clear that the key consists of 16 hex values and gave an example how to generate a key with command line tools.

* Remove trailing comma. #916
2019-01-31 19:09:49 +01:00
Bruceforce 8ffd7653ac [devicePublish.js] Increase timeout (#974)
This should avoid a non-function state of the app when too many
requests arrive at a specific time frame (e. g. turning a lot of lights
out in the same time).
See discussion in #362
2019-01-30 18:08:15 +01:00
Koen Kanters 99a29293dd Mock homeassistant zigbee2mqtt version. 2019-01-30 18:07:44 +01:00
Koen Kanters 9d61184013 Fix table layout of How to create a CC2530 router 2019-01-30 17:46:03 +01:00
Andreas Brett 4f300aa72d added ZBOSS for Windows users (#968) 2019-01-30 17:44:41 +01:00
Koen Kanters cf7e0d1aa9 1.1.0 2019-01-29 21:45:36 +01:00
Koen Kanters 17874cfdc1 Make availability_timeout non experimental. #775 2019-01-29 20:17:56 +01:00
Koen Kanters e12a371093 Fix before_install tag 2019-01-29 20:13:05 +01:00
Koen Kanters 7e74b8c549 Update zigbee-shepherd-converters to 7.0.27. 2019-01-29 20:11:06 +01:00
Koen Kanters cdf64823ef Merge branch 'master' into dev
# Conflicts:
#	docs/configuration/configuration.md
#	docs/getting_started/pairing_devices.md
#	docs/index.md
#	docs/information/mqtt_topics_and_message_structure.md
2019-01-29 19:57:02 +01:00
Koen Kanters 5d195fc299 Update link to group support firmware. 2019-01-29 19:55:24 +01:00
Koen Kanters fd932926e7 Update zigbee-shepherd-converters to 7.0.26. 2019-01-28 22:22:20 +01:00
zipbee 38159a536c Add support for Gledopto devices with multiple lights in one controller (#956) 2019-01-28 22:11:55 +01:00
MarkAdamson 7e2ca5a97e Added support for Salus SP600 Smart Plug (#954) 2019-01-28 22:10:44 +01:00
Robin Meis b95dcd0f9b Adding missing T for MQTT (#957) 2019-01-28 21:19:38 +01:00
Mikkel Kroman 73f0f8fe43 Fix Docker images having the wrong platform (#952)
* travis: Update Docker and add experimental support

* travis: Build images with experimental --platform

* Update docker.sh
2019-01-27 20:32:52 +01:00
Koen Kanters 16f3e884fc Update zigbee-shepherd-converters to 7.0.25. 2019-01-27 00:45:31 +01:00
Sebastian Raff c5e6b9dd13 add hue/saturation color (#948)
* add hue/saturation color

https://github.com/Koenkk/zigbee-shepherd-converters/pull/239

* Update mqtt_topics_and_message_structure.md
2019-01-27 00:32:15 +01:00
Koen Kanters cae5d1a004 Implement queue for Xiaomi router polling. https://github.com/Koenkk/zigbee2mqtt/issues/927 2019-01-26 21:19:20 +01:00
krikk 85375ffbae How to connect a CC2530 coordinator using a USB to serial adapter (#940)
* mini howto connect cc2530 an needing configuration

hope this helps

* missing link

* Update how_to_connect_cc2530_via_usb_to_serial_adapter.md

* update

* Update cc_sniffer_devices.md
2019-01-26 21:11:42 +01:00
Boris Hajduk 43fc66c436 Update flashing_the_cc2531.md (#926) 2019-01-24 17:46:30 +01:00
nldroid 5718cd0157 Added Why is this needed for E1524 remote (#922)
Added some explanation for the E1524 remote procedure.
2019-01-23 18:05:51 +01:00
Koen Kanters dd6e34a152 Fix tests. 2019-01-22 20:44:40 +01:00
Koen Kanters 1ddf60bef0 Fix some of the clogging issues. #914 #842 2019-01-22 20:31:50 +01:00
Koen Kanters 6ff3954b71 Update zigbee-shepherd-converters to 7.0.23. 2019-01-22 20:22:16 +01:00
Simon Rasmussen 6dd2926a1d Refactored light specific transtime to generic readAfterWriteTime value (#910)
* Refactored light specific transtime value to generic readAfterWriteTime
value

* Added line break
2019-01-22 20:08:57 +01:00
clockbrain 5970e498f3 Add styling to graphviz devices and links (#894)
* Add styling to graphviz devices and links

* Fix eslint error and gvrender_set_style warning
2019-01-22 20:07:38 +01:00
Simon Rasmussen dcd81cbbf2 Updated docs to reflect thermostat enums (#912) 2019-01-22 20:06:10 +01:00
Laurent 9e5fb04314 Elapsed time (#909)
* new elapsed attribute giving the elapsed time since the previous msg

* configurable elapsed attribute

* Update deviceReceive.js

* Update deviceReceive.js
2019-01-22 20:02:34 +01:00
Koen Kanters d324a91a5f Change unit of sensor_linkquality to -. #883 2019-01-21 18:51:53 +01:00
Koen Kanters fcfeac81e4 Fix state when controlling brightness via brightness_percent. https://github.com/Koenkk/zigbee2mqtt/issues/902 2019-01-21 18:02:50 +01:00
Fredrik Lindqvist c44816efee Add simple step for securing Zigbee network (#899)
* Add simple step for securing zigbee network

* Update configuration.md

* Update how_to_secure_network.md

* Update index.md
2019-01-21 17:51:21 +01:00
Koen Kanters 86f19affa1 Ensure that state and brightness are executed before other commands. #788 2019-01-21 17:38:06 +01:00
Koen Kanters e21bfc1567 Fix tests. 2019-01-19 14:10:59 +01:00
Koen Kanters 329c290505 Update docs. 2019-01-19 14:06:26 +01:00
Hmmbob b624a8ccad Update integrating-with-homeassistant.js (#890) 2019-01-19 14:05:15 +01:00
Koen Kanters a43cd5a864 Ignore messages from coordinator. https://github.com/Koenkk/zigbee2mqtt/issues/801 2019-01-18 22:23:47 +01:00
Koen Kanters 5f6b37bf83 Support mesh networks in grapvhiz networkmap. https://github.com/Koenkk/zigbee2mqtt/issues/652 2019-01-18 22:11:01 +01:00
Koen Kanters 653dfc7b6f Update zigbee-shepherd-converters to 7.0.22. https://github.com/Koenkk/zigbee2mqtt/issues/887 2019-01-18 22:00:33 +01:00
Koen Kanters aa87443c95 Add unit_of_measurment to linkquality sensor. https://github.com/Koenkk/zigbee2mqtt/issues/883 2019-01-18 21:41:41 +01:00
Koen Kanters f5a5668359 Update zigbee-shepherd-converters to 7.0.21. 2019-01-18 20:45:24 +01:00
pnewnam 5f2e93f64d Add Device Map for Sengled downlight E1ACA4ABE38A (#881)
* Add Device Map for Sengled downlight E1ACA4ABE38A

Add mapping for Sengled recessed downlight E1A-AC2

* Add image for Sengled downlight E1A-AC2

* Add Sengled model E1A-AC2

* Add Sengled model E1A-AC2 downlight

* Update supported_devices.md
2019-01-18 20:37:29 +01:00
Laurent 7cd30a3a05 configurable last_seen (#874)
* configurable last_seen

* Refactor last_seen.
2019-01-18 20:31:55 +01:00
Ivan Salazar 34a3e3c00b add Sengled E11-G13 bulbs to deviceAvailability.js (#860)
* add Sengled E11-G13 bulbs to deviceAvailability.js

* Update deviceAvailability.js

* Refactor and add tests

* Fix linting issue
2019-01-16 20:41:41 +01:00
Koen Kanters 28e32884d9 Update zigbee-shepherd-converters to 7.0.20 2019-01-15 21:19:07 +01:00
Timo Matthias dda2e064b2 Fix Typo (#863)
* Update coordinatorGroup.js

Fix Typo

* Update deviceAvailability.js

Fix Typo
2019-01-15 17:46:53 +01:00
Koenkk 9605e724e1 Update zigbee-shepherd-converters to 7.0.19 2019-01-14 18:19:59 +01:00
Koenkk 6912f8108d Refactor json_attributes to json_attributes_topic. https://github.com/Koenkk/zigbee2mqtt/issues/840 2019-01-14 18:04:33 +01:00
Koenkk 3c0e784afb Update zigbee-shepherd-converters to 7.0.18. 2019-01-14 17:38:49 +01:00
Koen Kanters be50d650a4 Update-zigbee-shepherd-converters to 7.0.16 2019-01-13 19:12:13 +01:00
Chrischi- a5057ac101 added hilips Hue power-on behavior (#851)
* added hilips Hue power-on behavior

i also removed json syntax highlighting where comments were added. They generate a syntax error (red).
JSON doesn't support comments.

* Update mqtt_topics_and_message_structure.md
2019-01-13 18:21:22 +01:00
Sander 72a74d7dc1 Add device support for iCasa Zigbee 3.0 Dimmer (#846)
* Add device support for iCasa Zigbee 3.0 Dimmer

* Update homeassistant.js
2019-01-13 17:28:56 +01:00
Koen Kanters dccdc5aafa Publish one MQTT message when a zigbee message is converted twice. #827 2019-01-11 22:38:16 +01:00
Koen Kanters 6dd60c09bf Fix tests. 2019-01-10 18:29:13 +01:00
Koen Kanters 4ec905efca Update zigbee-shepherd-converters to 7.0.14. 2019-01-10 18:23:22 +01:00
Koen Kanters f62eabcb6d Update zigbee-shepherd-converters to 7.0.13 2019-01-10 17:52:58 +01:00
mkventure fd2cf41f0f Update homeassistant.js for HGZB-01A & 464800 (#831)
- Add Nue HGZB-01A ZigBee Smart Light Controller to enable autodiscovery. (ref: PR#203 on zigbee-shepherd-converters,  https://github.com/Koenkk/zigbee-shepherd-converters/pull/203)
- Add Hue 464800 Hue white ambiance BR30 flood light
2019-01-09 20:57:14 +01:00
Koen Kanters 755d101738 Fix crash when there are no endpoints. #819 2019-01-09 20:49:22 +01:00
Koen Kanters 6fdd58be8a Update zigbee-shepherd-converters to 7.0.12. 2019-01-08 22:07:13 +01:00
Koen Kanters 26083a62d9 Update zigbee-shepherd-converters to 7.0.11 2019-01-08 19:38:56 +01:00
Koen Kanters 30b35e7272 Prevent Message without device! messages when pairing devices. 2019-01-08 19:22:09 +01:00
Koenkk f6c01a02c9 Home Assistant: set precision in value_template. #787 2019-01-08 19:00:47 +01:00
Koenkk 35b9e6204d Implement banning devices. #816 2019-01-08 19:00:02 +01:00
boojew 84f9d09b3f Rebased and added D1531 and D1532 bulbs (#829) 2019-01-08 18:46:38 +01:00
sebastianheierhoff f260bf974b Experimental ecozy support (WIP) - Documentation (#784)
* Added ecozy Smart Thermostat documentation

* Added initial documentation for ecozy and fixed Typo

* Fixing doc issues

* Fixing doc issues

* Update mqtt_topics_and_message_structure.md

* Finalizing documentation for ecozy and Bitron thermostats

* Update mqtt_topics_and_message_structure.md

* Update mqtt_topics_and_message_structure.md
2019-01-08 18:45:35 +01:00
Koen Kanters a2ea9c548f Improve logging. 2019-01-07 18:18:14 +01:00
Koen Kanters 932a66a5c4 Home Assistant: create separate sensor for battery. #787 2019-01-06 15:42:25 +01:00
Koen Kanters 3d0541a32d Add ‘%’ unit_of_measurement for Home Assistant battery sensor. #787 2019-01-06 15:35:30 +01:00
Koen Kanters 3bb1f0f10b Update zigbee-shepherd-converters to 7.0.10. 2019-01-06 15:31:08 +01:00
MarkAdamson 85b042ac25 Add support for Hive HALIGHTDIMWWB22 (Bayonet mount) (#800) 2019-01-06 14:37:38 +01:00
davidedmundson f1fe1edb49 Add 3321-S to home assistant (#797) 2019-01-05 20:56:30 +01:00
Frank 70d177485d added support for IKEA SURTE light door 38x64 (#804)
* added support for IKEA SURTE light door 38x64

* added ikea l1531 to documentation

* Revert "added ikea l1531 to documentation"

This reverts commit ee16a3d713.
2019-01-05 16:11:44 +01:00
allofmex fd44537984 Docu added for occupancy_timeout on SML001 (#796) 2019-01-03 14:32:34 +01:00
Koen Kanters dc20816043 Add configuration for CC2530 devices. #721 2019-01-02 21:41:53 +01:00
qosmio c6d09df01a Add support for Sengled E12-N14 (BR30) Light (#793) 2019-01-01 23:42:26 +01:00
Koen Kanters 74cdde23b9 Prevent battery devices to be checked for availability. https://github.com/Koenkk/zigbee2mqtt/issues/775 2019-01-01 22:15:05 +01:00
Koen Kanters 57aefe477d Update zigbee-shepherd-converters to 7.0.9. 2019-01-01 22:03:39 +01:00
netztrip d5a3ce3871 Add support for round Hue Aurelle LTC016 (#789) 2019-01-01 13:28:50 +01:00
Koen Kanters 92de1ca942 Implement binding feature. #765 #782 (#783)
* Start on bind implementation. https://github.com/Koenkk/zigbee2mqtt/issues/765

* Finish binding implementation.
2018-12-30 22:42:55 +01:00
Koen Kanters 6f477c2923 Add hex color to documentation. https://github.com/Koenkk/zigbee-shepherd-converters/pull/180 2018-12-30 20:15:07 +01:00
Koen Kanters 5453c082c4 Fix typo availablility -> availability. #777 #775 2018-12-30 20:08:31 +01:00
Koen Kanters 07fbc1b9a3 Add how to create a CC2530 router. #465 2018-12-30 17:26:00 +01:00
Gergely Markics afeed4f372 Add device availability functionality for HASS based on router devices ping and attribute reporting also available on battery-powered devices (#761)
* Discovery on HASS restart and last_message attribute added

- On restarting Home Assistant, resending device discovery information
- Add timestamp on receiving message from Zigbee

* Add option: add_timestamp in settings

* typo

* Update homeassistant.js

* Update homeassistant.js

* Update homeassistant.js

* Update controller.js

* Update zigbee.js

* Add files via upload

* Update zigbee.js

* Update deviceAvailabilityHandler.js

* Update deviceAvailabilityHandler.js

* Update deviceAvailabilityHandler.js

* Update deviceAvailabilityHandler.js

* Update deviceAvailabilityHandler.js

* Update deviceAvailabilityHandler.js

* Update deviceAvailabilityHandler.js

* Update homeassistant.js

* Update deviceAvailabilityHandler.js

* Update deviceAvailabilityHandler.js

* Update homeassistant.js

* Fix checkonline callback.

* Refactor.

* Refactor.
2018-12-29 19:55:59 +01:00
Koen Kanters 2a197a4ba8 Add tutorial on how to sniff zigbee traffic. #716 2018-12-28 14:02:03 +01:00
Koen Kanters 5e4e6d81de Add FAQ. 2018-12-27 23:26:53 +01:00
Koen Kanters faede151f3 Update zigbee-shepherd-converters to 7.0.7. #142 2018-12-27 22:51:16 +01:00
Koen Kanters ea4aaf2cfa Fix groups docs (groups -> group). https://github.com/Koenkk/zigbee2mqtt/issues/764 2018-12-27 22:39:41 +01:00
Koen Kanters ac94b95bba Update zigbee-shepherd-converters to 7.0.6. 2018-12-27 22:23:57 +01:00
Koen Kanters 708c497614 Update zigbee-shepherd. 2018-12-27 22:01:24 +01:00
DJTerentjev bd8aaea767 Add Gledopto GL-S-007Z to supported devices (#756)
* Upload GL-S-007Z image

* Add GL-S-007Z to supported devices

* Change GL-S-007Z image

* Update supported_devices.md

* Add "how to" for modelID 'undefined'

* Update how_to_support_new_devices.md

* Update how_to_support_new_devices.md

* Resize image

* Resize GL-S-007Z image

* modelID is 'undefined'

* Update supported_devices.md

* Update how_to_support_new_devices.md

* Update pairing_devices.md

* Update pairing_devices.md
2018-12-27 21:30:31 +01:00
Evildime ac4ca88b8a Add support for Xiaomi Aqara Curtain Motor (ZNCLDJ11LM) (#758)
* Add support for Xiaomi Aqara Curtain Motor (ZNCLDJ11LM)

* Update mqtt_topics_and_message_structure.md
2018-12-27 21:10:31 +01:00
Koen Kanters 8651fd7162 Merge branch 'master' into dev 2018-12-27 21:08:30 +01:00
Koen Kanters 03ff4e6e5a Finish groups documentation. #15 2018-12-27 19:37:39 +01:00
Koen Kanters 3bc2ec8c79 Simplify groups api. 2018-12-27 18:43:34 +01:00
Koen Kanters c4804e574e Fix tests. 2018-12-27 18:21:48 +01:00
Gergely Markics 5d3461c4c6 Add the timestamp of last received zigbee message visible in HASS (#739)
* Add timestamp on receiving message from Zigbee

Add last_message to the payload

* Discovery on HASS restart and last_message attribute added

- On restarting Home Assistant, resending device discovery information
- Add timestamp on receiving message from Zigbee

* Add option: add_timestamp in settings

* Add option: add_timestamp in settings

* Add option: add_timestamp in settings

* typo

* Update homeassistant.js

* Update homeassistant.js

* Update homeassistant.js

* Update deviceReceive.js

* Update deviceReceive.js

* Update homeassistant.js

* Update settings.js

* Update deviceReceive.js

* Update deviceReceive.js

* Update deviceReceive.js

* Update deviceReceive.js

* Fix tests

* Fix lint

* Fix lint
2018-12-26 17:33:39 +01:00
Koen Kanters 9380bbcadf Update README.md 2018-12-26 12:54:50 +01:00
Koen Kanters 3a0fe60b22 Update README.md 2018-12-26 12:44:45 +01:00
Der-Jan a1eea76dd4 Added OSRAM MR16 (#748) 2018-12-24 19:08:11 +01:00
Koen Kanters 69e805c882 Allow to configure network_key. https://github.com/Koenkk/zigbee2mqtt/issues/685 2018-12-24 16:29:06 +01:00
Koen Kanters 0fe3a9b45c Improve group support. #15 2018-12-24 00:39:58 +01:00
Koen Kanters ecf64c8058 Fix typo in logging. 2018-12-22 00:15:33 +01:00
Koen Kanters d3f705162d Group support #15 (#745)
* Start on group support. #15

* Implement publishing to zigbee groups. https://github.com/Koenkk/zigbee2mqtt/issues/15

* Complete first version of group support.

* Fix tests.
2018-12-22 00:07:53 +01:00
Koenkk bd8282a41a Update zigbee-shepherd-converters to 7.0.4. 2018-12-20 21:49:15 +01:00
Koenkk 82e87d563e Add semver dependency. https://github.com/Koenkk/zigbee2mqtt/issues/726 2018-12-19 17:36:06 +01:00
Koenkk d6c2b536ee Introduce device_options. https://github.com/Koenkk/zigbee2mqtt/issues/708 2018-12-19 17:33:02 +01:00
Koen Kanters 919178840f Merge branch 'master' into dev 2018-12-17 21:30:14 +01:00
Koen Kanters 84593a55ee 1.0.1 2018-12-17 21:28:17 +01:00
Koen Kanters 1b8154bac1 Fix crash when transition is used. #712 2018-12-17 21:27:13 +01:00
Koen Kanters 8a133de1d1 Fixed alternative_flashing_methods.md. #718 2018-12-17 19:54:58 +01:00
Koen Kanters 75dddf462e Update zigbee-shepherd-converters to 7.0.3. https://github.com/Koenkk/zigbee2mqtt/issues/708 2018-12-15 22:02:23 +01:00
Koen Kanters 91bbb0d4a8 1.0.0 2018-12-15 19:41:04 +01:00
Koen Kanters d25d093a1a Fix home assistant docs. 2018-12-15 19:38:29 +01:00
Koen Kanters 0bf91fd300 Sync with wiki. 2018-12-15 14:07:33 +01:00
Koen Kanters bf285681b4 Update stale.yml 2018-12-15 14:07:09 +01:00
Koen Kanters cf9a5b7553 Update zigbee-shepherd-converters to 7.0.2. 2018-12-14 22:08:01 +01:00
Koen Kanters c2a0a6b2d1 Require at least Home Assistant 0.84. https://github.com/Koenkk/zigbee2mqtt/pull/689 2018-12-14 21:50:48 +01:00
Koen Kanters eaff35421f Add logo to documentation. 2018-12-14 19:43:23 +01:00
Koen Kanters ec20bfdd15 Cleanup references to wiki. 2018-12-14 19:37:57 +01:00
Koen Kanters 1f2d3ec850 Update README.md with new logo! 2018-12-14 19:30:03 +01:00
Koen Kanters d9b418cdde Cleanup duplicate device images. 2018-12-14 19:29:43 +01:00
Koen Kanters 56ea61be3e Fix docs tests. 2018-12-13 21:40:47 +01:00
cbrherms b59afbd10d Change mqtt lights to new schema attribute (#689)
* Change mqtt lights to new schema attribute

* Update docs
2018-12-13 21:18:13 +01:00
EmmanuelLM 21fc5f0275 Update homeassistant.js (#694)
Add support for Innr B22 RGBW (BY 185 C)
2018-12-13 21:13:18 +01:00
Koen Kanters 9d6f6186b0 Merge branch 'master' into dev 2018-12-13 20:57:37 +01:00
Koen Kanters 590a897e9b Move docs from wiki to github pages. 2018-12-13 20:54:14 +01:00
Koen Kanters 753e8c3da7 Implement Home Assistant device registry. #646 2018-12-07 23:17:29 +01:00
Koen Kanters ef57083ae9 Always set name to friendly_name + object_id. #668 2018-12-07 23:13:20 +01:00
Koen Kanters 1fa13f3f96 Always set unique_id. https://github.com/Koenkk/zigbee2mqtt/pull/419 #668 #646 2018-12-07 23:09:56 +01:00
Adán SDPC 0fb84294f0 Stop caching forgotten and keyerror properties (#667)
* feat(device_receive): stop caching `forgotten` and `keyerror` properties

After this change, the `forgotten` and `keyerror` properties as emitted
by the Xiaomi Vima Smart Lock will stop being cached. Previously they
were mostly useless, because after they were set to `true`, they were
never being unset or set back to `false` upon a successful unlock.

Close #666

* chore(device_receive): order uncached properties lexicographically

As the list of uncached properties grows over time, it could be
useful to order them lexicographically. This will make life easier
to any developer looking for a particular property in the list, and
in overall makes things look tidier.
2018-12-07 17:51:34 +01:00
Koen Kanters 828df38e09 Fix failing docgen test. 2018-12-06 21:28:23 +01:00
Koen Kanters a13bd85ef3 Update zigbee-shepherd-converters to 7.0.1 2018-12-06 21:27:41 +01:00
Koen Kanters 65526e7f68 Revert "Experimental support for home assistant device registry. https://github.com/Koenkk/zigbee2mqtt/issues/646"
This reverts commit 7ea1fc66c2.
2018-12-06 21:27:41 +01:00
johnnyletrois 81d04d3dae Support Iris 3326-L occupancy/temperature sensor (#651)
* Support Iris 3326-L occupancy/temperature sensor

* Support for Iris contact sensor 3320-L
2018-12-06 21:27:41 +01:00
Koen Kanters 16c222d3b3 Support iAS cluster. (#654)
* Implement zapp-cie. https://github.com/Koenkk/zigbee2mqtt/issues/507

* Cleanup cie app. https://github.com/Koenkk/zigbee2mqtt/issues/507

* Update package.json

* Update zigbee.js
2018-12-06 21:27:41 +01:00
Koen Kanters 0e61618935 Experimental support for home assistant device registry. https://github.com/Koenkk/zigbee2mqtt/issues/646 2018-12-06 21:27:41 +01:00
Koen Kanters bede1032e6 Refresh state after transition. https://github.com/Koenkk/zigbee-shepherd-converters/issues/155 2018-12-06 21:27:41 +01:00
Koen Kanters 0786f22ce6 Prepare for github pages. 2018-12-06 21:27:41 +01:00
Koen Kanters c9c4fad7df Fix bridge/config topic. https://github.com/Koenkk/zigbee2mqtt/issues/626 2018-12-06 21:27:41 +01:00
Koen Kanters a52d3ea073 Publish bridge config. https://github.com/Koenkk/zigbee2mqtt/issues/626 2018-12-06 21:27:41 +01:00
Koen Kanters dcc410f6c5 Update zigbee-shepherd-converters to 6.0.7. 2018-12-06 21:27:41 +01:00
Dennis van den Bos c7743e6734 added Climax PSS-23ZBS power plug (#644) 2018-12-06 21:27:41 +01:00
Koenkk cc56141c39 Docker unlock nodejs and npm version. 2018-12-06 21:27:41 +01:00
Koenkk 60c2593669 Skip state when brightness is also published (reduces amount of useless zigbee commands). 2018-12-06 21:27:41 +01:00
Koenkk db945c90be Update zigbee-shepherd-converters to 6.0.6. https://github.com/Koenkk/zigbee2mqtt/issues/627 2018-12-06 21:27:41 +01:00
Koenkk 9df1065634 Add test with brightness as number. 2018-12-06 21:27:41 +01:00
Koenkk 65f23171e6 Update zigbee-shepherd-converters to 6.0.4 2018-12-06 21:27:41 +01:00
Koenkk 920d1c91c7 Update zigbee-shepherd-converters to 6.0.1 2018-12-06 21:27:41 +01:00
Koenkk 698b40554e Improve tests. 2018-12-06 21:27:41 +01:00
Koenkk cb9beaa2ad Fix getDeviceInfoForMqtt crash. https://github.com/Koenkk/zigbee2mqtt/issues/632 2018-12-06 21:27:41 +01:00
Koenkk d652856e90 Update zigbee-shepherd-converters 6.0.0. https://github.com/Koenkk/zigbee2mqtt/issues/608 2018-12-06 21:27:41 +01:00
Koenkk 7d09d065c5 Update zigbee-shepherd-converters to 5.0.3. https://github.com/Koenkk/zigbee2mqtt/issues/627 2018-12-06 21:27:41 +01:00
Koenkk 352fa2db50 More tests. 2018-12-06 21:27:41 +01:00
Koenkk 349ebad659 Move docs to repo 2018-12-06 21:27:41 +01:00
Koenkk 8fefa16fbc Prepare for github pages. 2018-12-06 21:27:41 +01:00
Koenkk 99b330e85e Lint 2018-12-06 21:27:41 +01:00
Koenkk 3f49e2e596 Don’t use unsupported json_attributes binary_sensor attribute. https://github.com/Koenkk/zigbee2mqtt/issues/605 2018-12-06 21:27:41 +01:00
Koenkk dcb75b19d3 Default postfix to empty string. https://github.com/Koenkk/zigbee2mqtt/issues/593 2018-12-06 21:27:41 +01:00
Koenkk c213a96133 Add missing device images. 2018-12-06 21:27:41 +01:00
Koenkk 78984a65ab Add devices images to repository. 2018-12-06 21:27:41 +01:00
Koenkk 6c059c3898 Update zigbee-shepherd-converters (remove onAfIncomingMsg code). https://github.com/Koenkk/zigbee2mqtt/issues/553 2018-12-06 21:27:41 +01:00
Koenkk ac6eb19aff Fix node version requirement. https://github.com/Koenkk/zigbee2mqtt/issues/596 2018-12-06 21:27:41 +01:00
Koenkk 6df4e39f18 Refactor! 2018-12-06 21:27:36 +01:00
Koenkk b0d3c2f964 0.2.0 2018-11-14 19:18:31 +01:00
Koenkk f797a12250 Update zigbee-shepherd-converters. 2018-11-14 18:32:02 +01:00
Jonas Janz 081d3c3dfe update docs for Home Hssistant (#583)
This adds a hint that you 'need' to set "hass/state" as a topic if you want zigbee2mqtt to resend the cached values on restarts.
2018-11-11 20:04:34 +01:00
Koenkk 7ca966ce39 npm is not installed by default anymore in Alpine. 2018-11-07 20:25:38 +01:00
Koenkk fc664bdc68 Fix node version to >=8.11 10 and implement check on startup. https://github.com/Koenkk/zigbee2mqtt/issues/552 2018-11-07 20:05:14 +01:00
Koenkk 2cb27b14f9 Allow ‘/‘ in friendly_name. https://github.com/Koenkk/zigbee2mqtt/issues/470 2018-11-07 19:40:58 +01:00
Koenkk 86a102e081 Only mock state after set. #518 2018-11-06 21:20:03 +01:00
Koenkk 9119e54c2c Prepare for read commands. https://github.com/Koenkk/zigbee2mqtt/issues/518 2018-11-05 21:55:30 +01:00
Dustin Wyatt f379bc0391 add linkquality to json_attributes for HA discovery (#566) 2018-11-05 19:39:36 +01:00
Koenkk 2e736bf501 Update zigbee-shepherd-converters to 4.0.11 2018-10-31 17:10:28 +01:00
Stanislav Demydiuk 1e7f985d4e Support both DeviceID and FriendlyName in device control topic (#476) 2018-10-30 21:23:34 +01:00
Koenkk 61c4ff33e0 Update zigbee-shepherd-converters to 4.0.10 2018-10-29 21:34:48 +01:00
mmnpkf 73ae48f387 Add Sengled Element Classic (A60) - B22 fitting (#544)
* Add Sengled Element Classic (A60) - B22 fitting

The Sengled Element Classic with Edison fitting (E27) is already defined - model E11-G23.  The same bulb comes with a bayonet fitting (B22) with a slightly different model number - E11-G33.

* Update homeassistant.js

* Update homeassistant.js
2018-10-29 21:12:37 +01:00
Stanislav Demydiuk 0a1c60b2cf Add Link for Domoticz integration to Readme (#546) 2018-10-29 08:29:28 +01:00
Koenkk 4eb56319c4 Update zigbee-shepherd-converters to 4.0.9 2018-10-25 20:44:55 +02:00
mmnpkf d8ea36af29 Add Nue Double GPO (au version) to Home Assistant (#506)
* Update homeassistant.js

Add code to expose Nue double power outlet (au version) to Home Assistant

* Update homeassistant.js
2018-10-25 20:43:31 +02:00
Felix Triller d0cf61bf10 Use Home Assistant's device_class (#528)
* Use Home Assistant's device_class for sensors.

* Unit for pressure should be hPa

* There is no device_class lock
2018-10-24 21:10:42 +02:00
Koenkk ddb83cc6e4 Handle zigbee commands sequentially (and refactor it). #529 2018-10-23 20:39:48 +02:00
Jens Willmer e54de4bea7 Adding update script (#525)
* Adding update script

Fix #389

* Update update.sh :)

* Make executable & update update.sh
2018-10-22 18:08:03 +02:00
Koenkk 97cc56b691 0.1.8 2018-10-19 22:44:26 +02:00
Koenkk c9df5c8221 Update zigbee-shepherd-converters to 4.0.7. 2018-10-19 22:27:29 +02:00
dcshoes23 7f13e2c3e6 Add homeassistant auto-discovery support for CE LED potlight 4" (#505) 2018-10-19 22:20:11 +02:00
Koenkk 0aab565083 Update zigbee-shepherd-converters to 4.0.6 2018-10-17 21:17:45 +02:00
Kiall Mac Innes 153f8bcfb5 Add Philips Hue white ambiance E14 (LTW012) HA Support (#491)
Adds HA support for LTW012 devices - See https://github.com/Koenkk/zigbee-shepherd-converters/pull/100
2018-10-17 18:25:33 +02:00
Simon van der Veldt c04ed81adb Fix typo in logging messages (#486) 2018-10-16 17:51:54 +02:00
Koen Kanters a1cf75456b Fix state caching. #485 2018-10-16 17:34:46 +02:00
Koenkk b063e67e24 Update zigbee-shepherd-converters to 4.0.5. https://github.com/Koenkk/zigbee2mqtt/issues/467 2018-10-15 19:07:12 +02:00
98 changed files with 34515 additions and 6136 deletions
+13 -5
View File
@@ -1,7 +1,15 @@
node_modules
.travis*
.eslintignore
.eslintrc.json
.git
.github
.gitignore
*.png
firmware
docker/Dockerfile*
.npmrc
.travis*
.travis.yml
README.md
docker/Dockerfile*
images
node_modules
scripts
test
update.sh
+1 -1
View File
@@ -1,2 +1,2 @@
node_modules/*
support/*
test/
+4 -3
View File
@@ -1,9 +1,10 @@
{
"env": {
"jest/globals": true,
"es6": true,
"node": true
},
"extends": ["eslint:recommended", "google"],
"extends": ["eslint:recommended", "google", "plugin:jest/recommended", "plugin:jest/style"],
"parserOptions": {
"ecmaVersion": 2018,
"sourceType": "module"
@@ -12,9 +13,9 @@
"require-jsdoc": "off",
"indent": ["error", 4],
"max-len": ["error", { "code": 120 }],
"mocha/no-exclusive-tests": "error"
"no-prototype-builtins": "off"
},
"plugins": [
"mocha"
"jest"
]
}
+2
View File
@@ -0,0 +1,2 @@
github: [koenkk]
custom: https://www.paypal.me/koenkk
+44 -9
View File
@@ -1,11 +1,46 @@
Unsupported device
First check: https://github.com/Koenkk/zigbee2mqtt/wiki/How-to-support-new-devices
<!--
Before submitting an issue make sure you've searched for a similar issue and read the documentation: https://www.zigbee2mqtt.io/.
Bug report
- First make sure your on the latest version of zigbee2mqtt.
- Make sure you are running the latest CC253X firmware from https://github.com/koenkk/z-stack-firmware.
- Provide a clear description of the problem.
- If applicable, provide steps how to reproduce the problem.
- Provide a log with `log_level` set to `debug`, see https://github.com/Koenkk/zigbee2mqtt/wiki/Configuration
Rules (don't ignore these, your issue will be closed without further notice):
- English only
- Make sure you are on the latest Zigbee2mqtt version
- Provide a clear description of the problem
- DON'T copy logs directly here, post a link to https://hastebin.com/ or https://pastebin.com/.
- Make sure you are running the latest firmware https://github.com/koenkk/z-stack-firmware.
Did you read the FAQ?
- https://www.zigbee2mqtt.io/information/FAQ.html
Zigbee2mqtt fails to start?
- https://www.zigbee2mqtt.io/information/FAQ.html#help-zigbee2mqtt-fails-to-start
Having issues when using a CC2531?
- Make sure the CC2531 is connected through a USB extension cable
- Try the source routing firmware: https://github.com/Koenkk/Z-Stack-firmware/tree/master/coordinator/Z-Stack_Home_1.2/bin/source_routing
- With larger networks (30/40+) devices, your CC2531 might not be powerful enough. This will cause weird issues, in this case it's advised to use a more powerful adapter: https://www.zigbee2mqtt.io/information/supported_adapters.html#texas-instruments-cc26x2r1
Unsupported device?
- https://www.zigbee2mqtt.io/how_tos/how_to_support_new_devices.html
Device does not pair or interview fails?
- https://www.zigbee2mqtt.io/information/FAQ.html#why-does-my-device-not-or-fail-to-pair
Bug report?
- If applicable, provide steps how to reproduce the problem.
- Provide the herdsman debug logging: https://www.zigbee2mqtt.io/information/debug.html#zigbee-herdsman-debug-logging
-->
<!--Start your bug report below this line-->
# Bug Report
## What happened
## What did you expect to happen
## How to reproduce it (minimal and precise)
## Debug Info
Zigbee2mqtt version:
Adapter hardware: CC2531, CC2530, CC26X2R1 or CC1352P-2
Adapter firmware version:
+1
View File
@@ -0,0 +1 @@
preferredBranch: dev
+1 -5
View File
@@ -1,11 +1,7 @@
# Number of days of inactivity before an issue becomes stale
daysUntilStale: 60
daysUntilStale: 30
# Number of days of inactivity before a stale issue is closed
daysUntilClose: 7
# Issues with these labels will never be considered stale
exemptLabels:
- enhancement
- bug
# Label to use when marking an issue as stale
staleLabel: stale
# Comment to post when marking an issue as stale. Set to `false` to disable
+29
View File
@@ -0,0 +1,29 @@
name: CI
on: [push, pull_request]
jobs:
ci:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2-beta
with:
node-version: 12
- name: Get NodeJS Version
id: nodeversion
run: |
echo "::set-output name=version::$(node --version)"
- name: Restore node_modules cache
id: cache-node-modules
uses: actions/cache@v2
with:
path: node_modules
key: ${{ runner.os }}-${{ steps.nodeversion.outputs.version }}-${{ hashFiles('npm-shrinkwrap.json') }}
- name: Install dependencies
if: steps.cache-node-modules.outputs.cache-hit != 'true'
run: npm ci
- name: Test
run: npm run test-with-coverage
- name: Lint
run: npm run eslint
+25
View File
@@ -0,0 +1,25 @@
name: Update dependencies
on:
workflow_dispatch:
schedule:
- cron: "0 0 * * 0"
jobs:
update_deps:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
ref: dev
ssh-key: ${{ secrets.SSH_PRIVATE_KEY }}
- uses: actions/setup-node@v2-beta
with:
node-version: 12
- run: npm install
- run: npm ls --depth 0 --prod --parseable | tail -n +2 | grep -v "zigbee-herdsman" | xargs -I '{}' basename "{}" | xargs -I '{}' npm install '{}'@latest
- run: rm -rf node_modules npm-shrinkwrap.json && npm install && npm shrinkwrap --dev
- uses: peter-evans/create-pull-request@v2
with:
commit-message: Update dependencies
branch: "update_deps"
title: Update dependencies
+22
View File
@@ -0,0 +1,22 @@
name: Update zigbee-herdsman
on:
repository_dispatch:
types: update_zh
jobs:
update_zh:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
ref: dev
ssh-key: ${{ secrets.SSH_PRIVATE_KEY }}
- uses: actions/setup-node@v2-beta
with:
node-version: 12
- run: npm install zigbee-herdsman@${{ github.event.client_payload.version }} --save-exact
- uses: peter-evans/create-pull-request@v2
with:
commit-message: Update zigbee-herdsman to ${{ github.event.client_payload.version }}
branch: "update_zh"
title: Update zigbee-herdsman
+22
View File
@@ -0,0 +1,22 @@
name: Update zigbee-herdsman-converters
on:
repository_dispatch:
types: update_zhc
jobs:
update_zhc:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
ref: dev
ssh-key: ${{ secrets.SSH_PRIVATE_KEY }}
- uses: actions/setup-node@v2-beta
with:
node-version: 12
- run: npm install zigbee-herdsman-converters@${{ github.event.client_payload.version }} --save-exact
- uses: peter-evans/create-pull-request@v2
with:
commit-message: Update zigbee-herdsman-converters to ${{ github.event.client_payload.version }}
branch: "update_zhc"
title: Update zigbee-herdsman-converters
+9 -1
View File
@@ -62,4 +62,12 @@ data/database.db
data/config.json
data/log*.txt
data/state.json
data/log
data/log
data-backup/
data/coordinator_backup.json
data/.storage
data/database.db.backup
data/extension
# MacOS indexing file
.DS_Store
+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
-29
View File
@@ -1,29 +0,0 @@
language: node_js
sudo: required
services:
- docker
node_js:
- "8"
install:
- npm install
before_script:
- npm test
- npm run verify-homeassistant-mapping
- npm run eslint
script:
- ".travis/docker.sh"
- ".travis/wiki.sh"
- ".travis/trigger-downstream.sh"
env:
global:
- DOCKER_USERNAME=koenkk
- secure: q5W9+mHz13PslLkTxuYNXivOau+N5OyB53sqgb+krOCPlbN9+gvi2Av9SribVd5jp2yx2O9rV/mr8eS0M2ykvBJ3UsIsCXiFL1dEPmsz1wlFAnW3kbD2EGhGFEV0dWRflSlA+5iQtcMPvbYu2PAOChUUoY7NNlhcz2EC+XXUapvvvaDwA1oSdtX+m61qyREshZb8B57DyXhziy6i/xjhFa84C0mR/iGFRWpZgcxmrNFH+/XDhSIpdq2KshhDWhjyag3ukAsTxTpqzLh1rFRlczjJEn0CcHG4WHsWHUFn9KK2lvT/YCDP8w0URnR1bCr8nyxGZJ2DLW6AzxZtJfWjvbeZYjO2R3WeHpzp6Jw6Qz5pG3gmu2FgeFpZ3FTEGtJ/Ev0/pjkY2Msx9mItzUJ7D8hY2noQZMPASar6oXEDYlkomx7gHHla0MPv3PKSJg5LX6Ybl137GIa6MLYYyz6SEKfyRUQhy3Itqrb/ID/ZP0UuLgyyDfShb8A6XOnsVqwZAsOPtU2UPnD1vsVXhjkpflK9+7QjL5m9MSqfAhg6qtwNsswl1KSiyhmdldGhZW5OfUasDxZKHyx7bsS1BhNnLi/iy4ifDh6KSr64aUW4iM0X99gkU+662Hgf73QpIG+oP41r30iEN0unTcRrFQDIbTSSapbA95bwUCBF1CgQC20=
- secure: em3lBVXvZ3kOVI4ipVlh93NIU6guLvyzHMmsLDuxhc92VFURqlYu3iXTTNEnknwyE31mziAkVFnmj+3OENd/VfzP01d4KKaYAQrbn2AnOMvcIIExLfaFU5QqbW1RMwRBIifhvrmboKt07pFsUy3Rghs80SwNSFDfLFoMhFMz+NdIZfJGW8LJy+gUPmz10YGzqh/chreowqOemgBBoswCGwIh1xB1KNejew3bQllnwQYGXcGuTDwDT4Wz+ObxlFt7YR/4n4oJY8jQYRPolM9qHQAGyn/Cn0TL3c8JqiBpVc1hm2OhYSDqvK0xf5IKsD+kIfFJPGa7nF2cwmhKdUNYR47oue3KB5tdrtDhwqUooTglvBOSXUIbthUR9Xu40ziyd5tHy0ixaLnDRGuKIIvEnXlcE6CgApoe3y2kHYa5dY+eUKxWwvH7b5hG+u82dYvw3VYpCHAnDQVgUzz4F63qZ2WZhcH0W3PF3/ytVAHyMu2vAMSrSXGi5xgM6el7Gp7SFVTFXBurbOaoJ3ZwwSEDP5d8mDyk1d8thmkQFL9P6iWtNnXOzjv4GIliEDWQg76BX6MLD3n3fnP0aq+RVmv+ev2Lp4xZZDfgGPek7g35IsaiohH6YvHloxE+ETQ0Ttb1lCQos9fj7LlI+ud6ExjwyRuEnzCOzr/qC/3Leg85Wc8=
- secure: GbJVFFY4nmQovp8i2VoQ1AOV8h9QoAcleBV9Mg5TItA8U2Y+6t9wx0iWbaclxOrzI727XZOk5HquMTKKTI430lT6OjU01+YJqwyq+k650YiX5PImsgJXGhFzBKeUcB3A53kKijfr9aEV00YiXRsKoKAn+Bl09m/9O+melBbTwO/YAQyt6EoUt21Yk0BoqpW2CTMPAgsU5tm6Ra3bbJ+IaUYVMYBtuHqtGiKg8jgTHqRhwKejDyV7+1dDxX8q51bK2Kb6PujbI1SS5wsJEpkU/eoPs7MuprmlYarYtBt1fDXSK1EOjcfpyEFRlrNLewIKiFEo3dkTOEtW2a4t3tcAiXOj8Hcvp+6RsjTfnjYmZweHVh/JKDhujjHBMviyTjwp4RnPaQSFou0iVIB5+Mo34hUhFDXc30SBzaux+lyR3rGoEu5pubZNjG5CkKIpw3IyduNKtIrlbCnfg+WDU3jrXmk0fzmwyriyXhx9BAzM+hyFiElZ+3xoXAlmDlwvaRZyJuQQNslwGPbZyX9EByIUkECjYPf92QPyD0mjbn8C32IphgQ515Up+15g2meDniugzowLJkDe3W86M5fB1kPQiDq5oT4M6TgAPRElLN6/ibyfOzDAtOdZgUiQvFnUQb1s9LunZqrc57AKzuzl2xG9Ok/cUkZFSOjrFr40jXgS2Lw=
-43
View File
@@ -1,43 +0,0 @@
#!/bin/bash -e
login() {
echo "$DOCKER_PASSWORD" | docker login -u "$DOCKER_USERNAME" --password-stdin
}
tag_push() {
docker tag $DOCKER_USERNAME/zigbee2mqtt:$1 $DOCKER_USERNAME/zigbee2mqtt:$2
docker push $DOCKER_USERNAME/zigbee2mqtt:$2
}
build_and_push() {
docker build --build-arg COMMIT=$(git rev-parse --short HEAD) -t $DOCKER_USERNAME/zigbee2mqtt:$1 -f $2 .
docker push $DOCKER_USERNAME/zigbee2mqtt:$1
}
# Only update Docker images for:
# - dev branch
# - version release
if [ "$TRAVIS_PULL_REQUEST" = "false" ] && [ ! -z ${TRAVIS_TAG+x} ] && [ ! "$TRAVIS_TAG" = "" ]
then
echo "Updating docker images for master branch!"
login
# Push versioned images
build_and_push "$TRAVIS_TAG" docker/Dockerfile.amd64
build_and_push "$TRAVIS_TAG-arm32v6" docker/Dockerfile.arm32v6
build_and_push "$TRAVIS_TAG-arm64v8" docker/Dockerfile.arm64v8
# Push latest images.
tag_push "$TRAVIS_TAG-arm32v6" "arm32v6"
tag_push "$TRAVIS_TAG-arm64v8" "arm64v8"
tag_push "$TRAVIS_TAG" latest
elif [ "$TRAVIS_BRANCH" = "dev" -a "$TRAVIS_PULL_REQUEST" = "false" ]
then
echo "Updating docker images for dev branch!"
login
build_and_push latest-dev docker/Dockerfile.amd64
build_and_push arm32v6-dev docker/Dockerfile.arm32v6
build_and_push arm64v8-dev docker/Dockerfile.arm64v8
else
echo "Not updating docker images, triggered by pull request or not on master/dev branch"
fi
-30
View File
@@ -1,30 +0,0 @@
#!/bin/bash
function travis_trigger() {
local org=$1 && shift
local repo=$1 && shift
local branch=${1:-master} && shift
body="{
\"request\": {
\"branch\": \"${branch}\"
}
}"
curl -s -X POST \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-H "Travis-API-Version: 3" \
-H "Authorization: token $TRAVIS_TOKEN" \
-d "$body" \
"https://api.travis-ci.org/repo/${org}%2F${repo}/requests"
}
# Only trigger downstream if on dev branch and not pull request
if [ "$TRAVIS_BRANCH" = "dev" -a "$TRAVIS_PULL_REQUEST" = "false" ]
then
echo "Triggering build of downstream projects!"
travis_trigger "danielwelch" "hassio-zigbee2mqtt" "master"
else
echo "Not triggering build of downstream projects, triggered by pull request or not on dev branch"
fi
-28
View File
@@ -1,28 +0,0 @@
#!/bin/sh -e
setup_git() {
git config --global user.email "travis@travis-ci.org"
git config --global user.name "Travis CI"
}
update_wiki() {
rm -rf zigbee2mqtt.wiki
git clone https://${GH_TOKEN}@github.com/Koenkk/zigbee2mqtt.wiki.git
npm run docgen zigbee2mqtt.wiki
cd zigbee2mqtt.wiki
git add -A
git diff-index --quiet HEAD || git commit -m "Travis CI: update wiki"
git push origin
cd ..
rm -rf zigbee2mqtt.wiki
}
# Only update wiki if on master branch and not pull request
if [ "$TRAVIS_BRANCH" = "master" -a "$TRAVIS_PULL_REQUEST" = "false" ]
then
echo "Updating wiki!"
setup_git
update_wiki
else
echo "Not updating wiki, triggered by pull request or not on master branch"
fi
+5
View File
@@ -0,0 +1,5 @@
{
"files.associations": {
"*.yaml": "home-assistant"
}
}
+63 -29
View File
@@ -1,44 +1,78 @@
[![Travis](https://img.shields.io/travis/Koenkk/zigbee2mqtt.svg)](https://api.travis-ci.org/Koenkk/zigbee2mqtt.svg)
<div align="center">
<a href="https://github.com/koenkk/zigbee2mqtt">
<img width="150" height="150" src="images/logo.png">
</a>
<br>
<br>
<div style="display: flex;">
<a href="https://dev.azure.com/koenkk/zigbee/_build?definitionId=5">
<img src="https://dev.azure.com/koenkk/zigbee/_apis/build/status/Koenkk.zigbee2mqtt?branchName=dev">
</a>
<a href="https://github.com/Koenkk/zigbee2mqtt/releases">
<img src="https://img.shields.io/github/release/koenkk/zigbee2mqtt.svg">
</a>
<a href="https://github.com/Koenkk/zigbee2mqtt/stargazers">
<img src="https://img.shields.io/github/stars/koenkk/zigbee2mqtt.svg">
</a>
<a href="https://www.paypal.me/koenkk">
<img src="https://img.shields.io/badge/donate-PayPal-blue.svg">
</a>
<a href="https://discord.gg/dadfWYE">
<img src="https://img.shields.io/discord/556563650429583360.svg">
</a>
<a href="http://zigbee2mqtt.discourse.group/">
<img src="https://img.shields.io/discourse/https/zigbee2mqtt.discourse.group/status.svg">
</a>
<a>
<img src="https://img.shields.io/badge/Coverage-100%25-brightgreen.svg">
</a>
<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>
Allows you to use your Zigbee devices <b>without</b> the vendors bridge or gateway.
</p>
<p>
It bridges events and allows you to control your Zigbee devices via MQTT. In this way you can integrate your Zigbee devices with whatever smart home infrastructure you are using.
</p>
</div>
# zigbee2mqtt :bridge_at_night: :honeybee:
![Thumbs up or down?](header.png)
<img align="right" height="40px" src="https://user-images.githubusercontent.com/7738048/40915536-1993dd32-6805-11e8-9f22-4dfca52133c0.png">
## [Getting started](https://www.zigbee2mqtt.io/#getting-started)
The [documentation](https://www.zigbee2mqtt.io/) provides you all the information needed to get up and running! Make sure you don't skip sections if this is your first visit, as there might be important details in there for you.
Allows you to use your Zigbee devices **without** the vendors (Xiaomi/TRADFRI/Hue) bridge or gateway.
If you aren't familiar with **Zigbee** terminology make sure you [read this](https://www.zigbee2mqtt.io/information/zigbee_network.html) to help you out.
It bridges events and allows you to control your Zigbee devices via MQTT. In this way you can integrate your Zigbee devices with whatever smart home infrastructure you are using.
## [Getting started](https://github.com/Koenkk/zigbee2mqtt/wiki/Getting-started)
The [wiki](https://github.com/Koenkk/zigbee2mqtt/wiki) provides you all the information needed to get up and running! Make sure you don't skip sections if this is your first visit, as there might be important details in there for you.
[The documentation](https://github.com/Koenkk/zigbee2mqtt/wiki) will provide information on how to prepare, configure and start **zigbee2mqtt**, but also on how to customize the setup to fit your needs.
If you aren't familiar with **zigbee** terminology make sure you [read this](https://github.com/Koenkk/zigbee2mqtt/wiki/ZigBee-network) to help you out.
## Integrations
## [Integrations](https://www.zigbee2mqtt.io/#integration)
Zigbee2mqtt integrates well with (almost) every home automation solution because it uses MQTT. However the following integrations are worth mentioning:
<img align="left" height="100px" width="100px" src="https://user-images.githubusercontent.com/7738048/40914297-49e6e560-6800-11e8-8904-36cce896e5a8.png">
### [Home Assistant](https://www.home-assistant.io/)
- [Hassio](https://www.home-assistant.io/hassio/): Using [the official addon](https://github.com/danielwelch/hassio-zigbee2mqtt) from [danielwelch](https://github.com/danielwelch)
- Generic install or Hassbian: Using instructions [here](https://github.com/Koenkk/zigbee2mqtt/wiki/Integrating-with-Home-Assistant)
- Generic install or Hassbian: Using instructions [here](https://www.zigbee2mqtt.io/integration/home_assistant.html)
## Architecture
![Architecture](architecture.png)
<img align="left" height="100px" width="100px" src="https://user-images.githubusercontent.com/2734836/47615848-b8dd8700-dabd-11e8-9d77-175002dd8987.png">
### [Domoticz](https://www.domoticz.com/)
- Integration implemented in [domoticz-zigbee2mqtt-plugin](https://github.com/stas-demydiuk/domoticz-zigbee2mqtt-plugin)
<br>
## Architecture
![Architecture](images/architecture.png)
### Internal Architecture
Zigbee2mqtt is made up of three modules, each developed in its own Github project. Starting from the hardware (adapter) and moving up; [zigbee-herdsman](https://github.com/koenkk/zigbee-herdsman) connects to your Zigbee adapter an makes an API available to the higher levels of the stack. For e.g. Texas Instruments hardware, zigbee-herdsman uses the [TI zStack monitoring and test API](https://github.com/koenkk/zigbee-herdsman/raw/master/docs/Z-Stack%20Monitor%20and%20Test%20API.pdf) to communicate with the adapter. Zigbee-herdsman handles the core Zigbee communication. The module [zigbee-herdsman-converters](https://github.com/koenkk/zigbee-herdsman-converters) handles the mapping from individual device models to the Zigbee clusters they support. [Zigbee clusters](https://github.com/Koenkk/zigbee-herdsman/raw/master/docs/07-5123-06-zigbee-cluster-library-specification.pdf) are the layers of the Zigbee protocol on top of the base protocol that define things like how lights, sensors and switches talk to each other over the Zigbee network. Finally, the zigbee2mqtt module drives zigbee-herdsman and maps the zigbee messages to MQTT messages. Zigbee2mqtt also keeps track of the state of the system. It uses a `database.db` file to store this state; a text file with a JSON database of connected devices and their capabilities.
## Supported devices
See [Supported devices](https://github.com/Koenkk/zigbee2mqtt/wiki/Supported-devices) to check whether your device is supported. There is quite an extensive list, including devices from vendors like Xiaomi, Ikea, Philips, OSRAM and more.
See [Supported devices](https://www.zigbee2mqtt.io/information/supported_devices.html) to check whether your device is supported. There is quite an extensive list, including devices from vendors like Xiaomi, Ikea, Philips, OSRAM and more.
If it's not listed in [Supported devices](https://github.com/Koenkk/zigbee2mqtt/wiki/Supported-devices), support can be added (fairly) easy, see [How to support new devices](https://github.com/Koenkk/zigbee2mqtt/wiki/How-to-support-new-devices).
If it's not listed in [Supported devices](https://www.zigbee2mqtt.io/information/supported_devices.html), support can be added (fairly) easy, see [How to support new devices](https://www.zigbee2mqtt.io/how_tos/how_to_support_new_devices.html).
## Support & help
If you need assistance you can check [opened issues](https://github.com/Koenkk/zigbee2mqtt/issues). Feel free to help with Pull Requests when you were able to fix things or add new devices or just share the love on social media.
## Contributors
* [AndrewLinden](https://github.com/AndrewLinden)
* [oskarn97](https://github.com/oskarn97)
* [dgomes](https://github.com/dgomes)
* [Koenkk](https://github.com/Koenkk)
* [kirovilya](https://github.com/kirovilya)
* [ciotlosm](https://github.com/ciotlosm)
If you need assistance you can check [opened issues](https://github.com/Koenkk/zigbee2mqtt/issues). Feel free to help with Pull Requests when you were able to fix things or add new devices or just share the love on social media.
+88
View File
@@ -0,0 +1,88 @@
trigger:
tags:
include:
- '*'
branches:
include:
- '*'
pool:
vmImage: 'ubuntu-latest'
steps:
# Prepare
- task: NodeTool@0
inputs:
versionSpec: '12.x'
displayName: 'Install Node.js'
- bash: npm ci
displayName: 'Install dependencies'
# Verify
- bash: npm run test-with-coverage
displayName: 'Test'
- 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
condition: and(succeeded(), ne(variables['Build.Reason'], 'PullRequest'))
inputs:
dockerVersion: 19.03.5
releaseType: stable
- task: Docker@2
displayName: Docker registry login
condition: and(succeeded(), ne(variables['Build.Reason'], 'PullRequest'))
inputs:
command: login
containerRegistry: docker_registry
- bash: |
sudo wget -O /usr/local/bin/buildx https://github.com/docker/buildx/releases/download/v0.3.1/buildx-v0.3.1.linux-amd64
sudo chmod a+x /usr/local/bin/buildx
docker run --rm --privileged hypriot/qemu-register:v2.7.0
buildx create --use
buildx ls
displayName: 'Docker setup'
condition: and(succeeded(), ne(variables['Build.Reason'], 'PullRequest'))
- bash: |
buildx build \
--build-arg COMMIT=$(git rev-parse --short HEAD) \
--platform linux/arm64/v8,linux/amd64,linux/arm/v6,linux/arm/v7,linux/386 \
-f docker/Dockerfile \
--push \
-t koenkk/zigbee2mqtt:latest-dev \
.
displayName: 'Docker build dev'
condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/dev'), ne(variables['Build.Reason'], 'PullRequest'))
- bash: |
TAG="$(git describe --tags)"
buildx build \
--build-arg COMMIT=$(git rev-parse --short HEAD) \
--platform linux/arm64/v8,linux/amd64,linux/arm/v6,linux/arm/v7,linux/386 \
-f docker/Dockerfile \
--push \
-t koenkk/zigbee2mqtt:latest -t "koenkk/zigbee2mqtt:$TAG" \
.
displayName: 'Docker build release'
condition: and(succeeded(), startsWith(variables['Build.SourceBranch'], 'refs/tags/'), ne(variables['Build.Reason'], 'PullRequest'))
# Trigger Home Assistant Zigbee2mqtt addon build
- bash: |
curl -s \
--request POST \
--header "Content-Type: application/json" \
--data '{"definition": {"id": 1}}' \
-u "$(HASSIO_TRIGGER_SECRET)" \
"https://dev.azure.com/danielwelch2101/hassio-zigbee2mqtt/_apis/build/builds?api-version=5.1"
displayName: 'Trigger Hass.io build'
condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/dev'), ne(variables['Build.Reason'], 'PullRequest'))
+33
View File
@@ -0,0 +1,33 @@
FROM node:12-alpine as base
WORKDIR /app
RUN apk add --no-cache tzdata eudev
COPY package.json ./
# Dependencies
FROM base as dependencies
COPY npm-shrinkwrap.json ./
RUN apk add --no-cache --virtual .buildtools make gcc g++ python linux-headers git && \
npm ci --production && \
apk del .buildtools
# Release
FROM base as release
COPY --from=dependencies /app/node_modules ./node_modules
COPY lib ./lib
COPY index.js data/configuration.yaml ./
COPY docker/docker-entrypoint.sh /usr/local/bin/
RUN chmod +x /usr/local/bin/docker-entrypoint.sh
RUN mkdir /app/data
ARG COMMIT
RUN echo "{\"hash\": \"$COMMIT\"}" > .hash.json
ENTRYPOINT ["docker-entrypoint.sh"]
CMD ["npm", "start"]
-20
View File
@@ -1,20 +0,0 @@
FROM alpine:3.7
# Copy files
ADD . /app
RUN cp /app/data/configuration.yaml /app
RUN cp /app/docker/run.sh /app
RUN chmod +x /app/run.sh
WORKDIR /app
# Write .hash.json
ARG COMMIT
RUN echo "{\"hash\": \"$COMMIT\"}" > .hash.json
# Install dependencies
RUN apk add --update --no-cache make gcc g++ python linux-headers udev nodejs git && \
npm install --unsafe-perm && \
apk del make gcc g++ python linux-headers udev git
# Entrypoint
ENTRYPOINT ["./run.sh"]
-22
View File
@@ -1,22 +0,0 @@
FROM arm32v6/alpine:3.7
# Setup cross-build
ENV QEMU_EXECVE 1
COPY docker/qemu-arm-static /usr/bin
WORKDIR /app
# Write .hash.json
ARG COMMIT
RUN [ "qemu-arm-static", "/bin/sh", "-c", "echo {\\\"hash\\\": \\\"$COMMIT\\\"} > .hash.json" ]
# Copy files & install dependencies
ADD . /app
RUN [ "qemu-arm-static", "/bin/sh", "-c", \
"cp /app/data/configuration.yaml /app && \
cp /app/docker/run.sh /app && chmod +x /app/run.sh && \
apk add --update --no-cache make gcc g++ python linux-headers udev nodejs git && \
npm install --unsafe-perm && \
apk del make gcc g++ python linux-headers udev git"]
# Entrypoint
ENTRYPOINT ["./run.sh"]
-22
View File
@@ -1,22 +0,0 @@
FROM arm64v8/alpine:3.7
# Setup cross-build
ENV QEMU_EXECVE 1
COPY docker/qemu-aarch64-static /usr/bin
WORKDIR /app
# Write .hash.json
ARG COMMIT
RUN [ "qemu-aarch64-static", "/bin/sh", "-c", "echo {\\\"hash\\\": \\\"$COMMIT\\\"} > .hash.json" ]
# Copy files & install dependencies
ADD . /app
RUN [ "qemu-aarch64-static", "/bin/sh", "-c", \
"cp /app/data/configuration.yaml /app && \
cp /app/docker/run.sh /app && chmod +x /app/run.sh && \
apk add --update --no-cache make gcc g++ python linux-headers udev nodejs git && \
npm install --unsafe-perm && \
apk del make gcc g++ python linux-headers udev git"]
# Entrypoint
ENTRYPOINT ["./run.sh"]
+14
View File
@@ -0,0 +1,14 @@
version: '3'
services:
zigbee2mqtt:
container_name: zigbee2mqtt
image: koenkk/zigbee2mqtt
volumes:
- ./data:/app/data
devices:
# CC251
#- /dev/ttyUSB_cc2531:/dev/ttyACM0
# CC2530 / GBAN GB2530S
#- /dev/ttyUSB_cc2530:/dev/ttyACM0
restart: always
network_mode: host
@@ -1,4 +1,5 @@
#!/bin/sh
set -e
if [ ! -z "$ZIGBEE2MQTT_DATA" ]; then
DATA="$ZIGBEE2MQTT_DATA"
@@ -13,8 +14,4 @@ if [ ! -f "$DATA/configuration.yaml" ]; then
cp /app/configuration.yaml "$DATA/configuration.yaml"
fi
if [ ! -z "$DEBUG" ]; then
npm start
else
DEBUG="$DEBUG" npm start
fi
exec "$@"
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 167 KiB

Before

Width:  |  Height:  |  Size: 103 KiB

After

Width:  |  Height:  |  Size: 103 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 244 KiB

+146
View File
@@ -0,0 +1,146 @@
<svg class="thumb" width="1000" height="1000" viewBox="0,0,600,600" xmlns="http://www.w3.org/2000/svg" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:ns1="http://www.inkscape.org/namespaces/inkscape" xmlns:sketch="http://www.bohemiancoding.com/sketch/ns">
<defs></defs>
<g transform="matrix(1.8288,0,0,1.8288,-76.3478,13.5303)">
<g transform="matrix(1.6652,0,0,1.6704,50.2843,0.6537)">
<svg width="186.77" height="186.769" viewBox="-5,-5,186.77,186.769">
<defs>
<linearGradient x1="0" y1="0.5" x2="1" y2="0.5" id="linearGradientSk1zes2vk4">
<stop offset="0%" stop-color="#000000"></stop>
<stop offset="100%" stop-color="#000000"></stop>
</linearGradient>
</defs>
<g></g>
<g></g>
<g>
<polygon points="51.774,176.769 0,124.995 0,51.774 51.774,0 124.995,0 176.77,51.774 176.77,124.995 124.995,176.769 " fill="url('#linearGradientSk1zes2vk4')"></polygon>
</g>
</svg>
</g>
<g transform="matrix(1.6204,0,0,1.6204,53.946,5.3)">
<svg width="186.77" height="186.769" viewBox="-5,-5,186.77,186.769">
<defs>
<linearGradient x1="0" y1="0.5" x2="1" y2="0.5" id="linearGradientSk1zes2vka">
<stop offset="0%" stop-color="#ffc038"></stop>
<stop offset="100%" stop-color="#ffc038"></stop>
</linearGradient>
</defs>
<g></g>
<g></g>
<g>
<polygon points="51.774,176.769 0,124.995 0,51.774 51.774,0 124.995,0 176.77,51.774 176.77,124.995 124.995,176.769 " fill="url('#linearGradientSk1zes2vka')"></polygon>
</g>
</svg>
</g>
<g transform="matrix(1.6146,0,0,1.6146,185.8484,123.0829)">
<svg width="27.265" height="16.606891038197716" viewBox="36.308,71.828,27.265,16.606891038197716">
<defs>
<linearGradient x1="0" y1="0.5" x2="1" y2="0.5" id="linearGradientSk1zes2vkg">
<stop offset="0%" stop-color="#000000"></stop>
<stop offset="100%" stop-color="#000000"></stop>
</linearGradient>
</defs>
<g></g>
<g></g>
<g></g>
<g></g>
<g>
<path d="M41.308,76.828c1.197,2.07,2.931,3.953,5.371,5.497c0,0,1.453,1.163,3.373,1.108c1.918,0.051,3.375-1.107,3.375-1.107 c2.289-1.446,3.958-3.192,5.146-5.112c-2.274,0.496-4.875,0.754-7.556,0.754C47.714,77.968,44.316,77.583,41.308,76.828z" fill="url('#linearGradientSk1zes2vkg')"></path>
</g>
</svg>
</g>
<g transform="matrix(1.6146,0,0,1.6146,182.6191,109.0829)">
<svg width="31.991999999999997" height="16.800092191011956" viewBox="34.051,63.36,31.991999999999997,16.800092191011956">
<defs>
<linearGradient x1="0" y1="0.5" x2="1" y2="0.5" id="linearGradientSk1zes2vkm">
<stop offset="0%" stop-color="#ffffff"></stop>
<stop offset="100%" stop-color="#ffffff"></stop>
</linearGradient>
</defs>
<g></g>
<g></g>
<g></g>
<g></g>
<g>
<path d="M39.051,68.36c0.055,1.736,0.307,3.47,0.818,5.141c5.94,2.063,15.1,2.206,20.244,0.407c0.563-1.692,0.85-3.453,0.93-5.221 c-2.995,0.938-6.551,1.364-10.114,1.364C46.659,70.052,42.394,69.434,39.051,68.36z" fill="url('#linearGradientSk1zes2vkm')"></path>
</g>
</svg>
</g>
<g transform="matrix(1.6146,0,0,1.6146,182.6191,96.0829)">
<svg width="31.867999999999995" height="16.630912092367097" viewBox="34.128,55.641000000000005,31.867999999999995,16.630912092367097">
<defs>
<linearGradient x1="0" y1="0.5" x2="1" y2="0.5" id="linearGradientSk1zes2vks">
<stop offset="0%" stop-color="#000000"></stop>
<stop offset="100%" stop-color="#000000"></stop>
</linearGradient>
</defs>
<g></g>
<g></g>
<g></g>
<g></g>
<g>
<path d="M50.929,62.06c-3.902,0-7.81-0.511-11.006-1.419c-0.373,1.537-0.658,3.156-0.795,4.812 c5.78,2.114,15.619,2.598,21.868,0.309c-0.119-1.662-0.384-3.297-0.745-4.846C57.427,61.692,54.187,62.06,50.929,62.06z" fill="url('#linearGradientSk1zes2vks')"></path>
</g>
</svg>
</g>
<g transform="matrix(1.6146,0,0,1.6146,185.041,84.8902)">
<svg width="28.836000000000006" height="15.788046460420631" viewBox="35.678,48.491,28.836000000000006,15.788046460420631">
<defs>
<linearGradient x1="0" y1="0.5" x2="1" y2="0.5" id="linearGradientSk1zes2vky">
<stop offset="0%" stop-color="#ffffff"></stop>
<stop offset="100%" stop-color="#ffffff"></stop>
</linearGradient>
</defs>
<g></g>
<g></g>
<g></g>
<g></g>
<g>
<path d="M59.514,58.241c-0.571-1.815-1.232-3.435-1.862-4.75c-2.599,0.543-5.42,0.809-8.212,0.809 c-2.458,0-4.881-0.204-7.097-0.579c-0.564,1.205-1.146,2.646-1.665,4.246C46.062,59.501,53.848,59.813,59.514,58.241z" fill="url('#linearGradientSk1zes2vky')"></path>
</g>
</svg>
</g>
<g transform="matrix(1.6146,0,0,1.6146,120.4554,23.9828)">
<svg width="108.32981691822947" height="57.54144295152284" viewBox="-4.359346882061053,10.889,108.32981691822947,57.54144295152284">
<defs>
<linearGradient x1="0" y1="0.5" x2="1" y2="0.5" id="linearGradientSk1zes2vk14">
<stop offset="0%" stop-color="#000000"></stop>
<stop offset="100%" stop-color="#000000"></stop>
</linearGradient>
</defs>
<g></g>
<g></g>
<g></g>
<g></g>
<g>
<path d="M58.786,38.047c-0.651-1.481-1.406-2.589-1.406-2.589c-0.11-0.123-0.253-0.232-0.394-0.342 c0.422-1.017,0.659-2.14,0.659-3.324c0-3.374-1.896-6.271-4.6-7.523l2.116-7.369l6.143-0.228c0.215-0.007,0.382-0.188,0.378-0.405 c-0.008-0.215-0.19-0.375-0.406-0.378l-6.396,0.238c-0.152,0.006-0.287,0.095-0.346,0.239l-3.563,7.305 c-0.302-0.039-0.607-0.065-0.92-0.065c-0.314,0-0.621,0.026-0.924,0.066l-3.565-7.308c-0.058-0.138-0.193-0.23-0.349-0.237 l-6.393-0.236c-0.216-0.001-0.396,0.161-0.407,0.376c-0.006,0.218,0.163,0.398,0.38,0.405l6.143,0.23l2.118,7.368 c-2.703,1.252-4.598,4.147-4.597,7.52c0,1.184,0.239,2.307,0.659,3.323c-0.148,0.11-0.288,0.223-0.393,0.344 c0,0-0.739,1.108-1.38,2.663C29.184,41.662-2.639,46.12,0.916,55.936c3.944,10.877,25.455,7.546,29.052,4.598 c5.007-4.104,9.231-7.95,11.843-11c0.224,0.512,0.459,0.979,0.694,1.396c4.583,0.822,10.289,0.82,14.998-0.245 c0.166-0.346,0.332-0.731,0.496-1.137c2.625,3.011,6.768,6.769,11.648,10.77c3.596,2.949,25.106,6.275,29.048-4.599 C102.202,46.038,71.295,41.566,58.786,38.047z" fill="url('#linearGradientSk1zes2vk14')"></path>
</g>
</svg>
</g>
<g transform="matrix(0.5515,-0.0096,0.0096,0.5515,184.0296,161.5473)">
<svg width="91.9" height="160" style="overflow: visible;">
<defs>
<linearGradient x1="0" y1="0.5" x2="1" y2="0.5" id="linearGradientSk1zes2vk1g">
<stop offset="0%" stop-color="#000000"></stop>
<stop offset="100%" stop-color="#000000"></stop>
</linearGradient>
</defs>
<g transform="matrix(1,0,0,1,0,75)">
<path d="M 28.2-77.4L 28.2-77.4L 28.2 5.4Q 28.2 7.3 27.35 8.15Q 26.5 9 24.6 9L 24.6 9L 10.1 9Q 8.2 9 7.35 8.15Q 6.5 7.3 6.5 5.4L 6.5 5.4L 6.5-77.4Q 6.5-79.3 7.35-80.15Q 8.2-81 10.1-81L 10.1-81L 24.6-81Q 26.5-81 27.35-80.15Q 28.2-79.3 28.2-77.4ZM 85.39999999999998-77.4L 85.39999999999998-77.4L 85.39999999999998 5.4Q 85.39999999999998 7.3 84.54999999999998 8.15Q 83.69999999999999 9 81.79999999999998 9L 81.79999999999998 9L 67.29999999999998 9Q 65.39999999999998 9 64.54999999999998 8.15Q 63.69999999999998 7.3 63.69999999999998 5.4L 63.69999999999998 5.4L 63.69999999999998-77.4Q 63.69999999999998-79.3 64.54999999999998-80.15Q 65.39999999999998-81 67.29999999999998-81L 67.29999999999998-81L 81.79999999999998-81Q 83.69999999999999-81 84.54999999999998-80.15Q 85.39999999999998-79.3 85.39999999999998-77.4Z" data-textpath="| |" data-text-anchor="middle" data-font-size="100" data-letterspacing="0" data-side="left" data-offset="0.5" data-dx="0" data-dy="0" data-xmlspace="preserve" data-href="" data-font="Bungee" data-font-src="/Content/clientfonts/bungee.woff" data-font-scale="contain" transform="translate(0,0)" data-x="0" data-y="0" fill="url('#linearGradientSk1zes2vk1g')"></path>
</g>
</svg>
</g>
<g transform="matrix(0.5,0,0,0.5,136.759,231)">
<svg width="289.30000000000007" height="160" style="overflow: visible;">
<defs>
<linearGradient x1="0" y1="0.5" x2="1" y2="0.5" id="linearGradientSk1zes2vk1j">
<stop offset="0%" stop-color="#000000"></stop>
<stop offset="100%" stop-color="#000000"></stop>
</linearGradient>
</defs>
<g transform="matrix(1,0,0,1,0,75)">
<path d="M 25.4 0L 25.4 0L 10.5 0Q 8.6 0 7.75-0.85Q 6.9-1.7 6.9-3.6L 6.9-3.6L 6.9-68.4Q 6.9-70.3 7.75-71.15Q 8.6-72 10.5-72L 10.5-72L 26.6-72Q 28.2-72 29.25-71.3Q 30.3-70.6 31.2-69L 31.2-69L 40.2-52.7Q 40.7-51.8 41.05-51.4Q 41.4-51 42-51L 42-51L 42.9-51Q 43.5-51 43.85-51.4Q 44.2-51.8 44.7-52.7L 44.7-52.7L 53.6-69Q 54.5-70.6 55.55-71.3Q 56.6-72 58.2-72L 58.2-72L 74.4-72Q 76.3-72 77.15-71.15Q 78-70.3 78-68.4L 78-68.4L 78-3.6Q 78-1.7 77.15-0.85Q 76.3 0 74.4 0L 74.4 0L 59 0Q 57.1 0 56.25-0.85Q 55.4-1.7 55.4-3.6L 55.4-3.6L 55.4-38.8L 49.5-27.9Q 48.6-26.2 47.35-25.45Q 46.1-24.7 44.2-24.7L 44.2-24.7L 40.2-24.7Q 38.3-24.7 37.05-25.45Q 35.8-26.2 34.9-27.9L 34.9-27.9L 29-38.8L 29-3.6Q 29-1.7 28.15-0.85Q 27.3 0 25.4 0ZM 129.4 9L 129.4 9L 114 9Q 112.10000000000001 9 111.25 8.15Q 110.4 7.3 110.4 5.4L 110.4 5.4L 110.4-0.1Q 98.80000000000001-1.8 94.75-7.05Q 90.7-12.3 90.7-19.8L 90.7-19.8L 90.7-53Q 90.7-57.6 92.05000000000001-61.35Q 93.4-65.1 96.85000000000001-67.8Q 100.30000000000001-70.5 106.4-72Q 112.5-73.5 121.80000000000001-73.5L 121.80000000000001-73.5Q 131.10000000000002-73.5 137.15-72Q 143.2-70.5 146.65-67.8Q 150.10000000000002-65.1 151.45-61.35Q 152.8-57.6 152.8-53L 152.8-53L 152.8-19.8Q 152.8-16 151.9-12.75Q 151-9.5 148.8-7Q 146.60000000000002-4.5 142.75-2.7Q 138.9-0.9 133-0.1L 133-0.1L 133 5.4Q 133 7.3 132.15 8.15Q 131.3 9 129.4 9ZM 113.4-49.3L 113.4-22Q 113.4-20 114.9-18.65Q 116.4-17.3 121.80000000000001-17.3L 121.80000000000001-17.3Q 127.2-17.3 128.7-18.65Q 130.2-20 130.2-22L 130.2-22L 130.2-49.3Q 130.2-51.2 128.7-52.55Q 127.2-53.9 121.80000000000001-53.9L 121.80000000000001-53.9Q 116.4-53.9 114.9-52.55Q 113.4-51.2 113.4-49.3L 113.4-49.3ZM 199 0L 199 0L 182.79999999999998 0Q 180.9 0 180.04999999999998-0.85Q 179.2-1.7 179.2-3.6L 179.2-3.6L 179.2-52.7L 164.5-52.7Q 162.6-52.7 161.75-53.55Q 160.9-54.4 160.9-56.3L 160.9-56.3L 160.9-68.4Q 160.9-70.3 161.75-71.15Q 162.6-72 164.5-72L 164.5-72L 217.3-72Q 219.2-72 220.05-71.15Q 220.89999999999998-70.3 220.89999999999998-68.4L 220.89999999999998-68.4L 220.89999999999998-56.3Q 220.89999999999998-54.4 220.05-53.55Q 219.2-52.7 217.3-52.7L 217.3-52.7L 202.6-52.7L 202.6-3.6Q 202.6-1.7 201.75-0.85Q 200.89999999999998 0 199 0ZM 264.6 0L 264.6 0L 248.40000000000003 0Q 246.50000000000006 0 245.65000000000003-0.85Q 244.80000000000004-1.7 244.80000000000004-3.6L 244.80000000000004-3.6L 244.80000000000004-52.7L 230.10000000000005-52.7Q 228.20000000000005-52.7 227.35000000000005-53.55Q 226.50000000000006-54.4 226.50000000000006-56.3L 226.50000000000006-56.3L 226.50000000000006-68.4Q 226.50000000000006-70.3 227.35000000000005-71.15Q 228.20000000000005-72 230.10000000000005-72L 230.10000000000005-72L 282.90000000000003-72Q 284.80000000000007-72 285.65000000000003-71.15Q 286.50000000000006-70.3 286.50000000000006-68.4L 286.50000000000006-68.4L 286.50000000000006-56.3Q 286.50000000000006-54.4 285.65000000000003-53.55Q 284.80000000000007-52.7 282.90000000000003-52.7L 282.90000000000003-52.7L 268.20000000000005-52.7L 268.20000000000005-3.6Q 268.20000000000005-1.7 267.35-0.85Q 266.50000000000006 0 264.6 0Z" data-textpath="MQTT" data-text-anchor="middle" data-font-size="100" data-letterspacing="0" data-side="left" data-offset="0.5" data-dx="0" data-dy="0" data-xmlspace="preserve" data-href="" data-font="Bungee" data-font-src="/Content/clientfonts/bungee.woff" data-font-scale="contain" transform="translate(0,0)" data-x="0" data-y="0" fill="url('#linearGradientSk1zes2vk1j')"></path>
</g>
</svg>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 12 KiB

+15 -2
View File
@@ -1,10 +1,23 @@
const Controller = require('./lib/controller');
const semver = require('semver');
const engines = require('./package.json').engines;
const version = engines.node;
if (!semver.satisfies(process.version, version)) {
console.log(`\t\tZigbee2mqtt requires node version ${version}, you are running ${process.version}!\n`); // eslint-disable-line
}
const Controller = require('./lib/controller');
const controller = new Controller();
controller.start();
process.on('SIGINT', handleQuit);
process.on('SIGTERM', handleQuit);
let stopping = false;
function handleQuit() {
controller.stop(() => process.exit());
if (!stopping) {
stopping = true;
controller.stop();
}
}
+302 -534
View File
@@ -1,605 +1,373 @@
const MQTT = require('./mqtt');
const Zigbee = require('./zigbee');
const EventBus = require('./eventBus');
const State = require('./state');
const logger = require('./util/logger');
const settings = require('./util/settings');
const ExtensionNetworkMap = require('./extension/networkMap');
const ExtensionSoftReset = require('./extension/softReset');
const ExtensionRouterPollXiaomi = require('./extension/routerPollXiaomi');
const zigbeeShepherdConverters = require('zigbee-shepherd-converters');
const homeassistant = require('./homeassistant');
const objectAssignDeep = require('object-assign-deep');
const utils = require('./util/utils');
const fs = require('fs');
const data = require('./util/data');
const path = require('path');
const mqttConfigRegex = new RegExp(`${settings.get().mqtt.base_topic}/bridge/config/\\w+`, 'g');
const mqttDeviceRegex = new RegExp(`${settings.get().mqtt.base_topic}/[\\w\\s\\d.-]+/set`, 'g');
const mqttDevicePrefixRegex = new RegExp(`${settings.get().mqtt.base_topic}/[\\w\\s\\d.-]+/[\\w\\s\\d.-]+/set`, 'g');
const allowedLogLevels = ['error', 'warn', 'info', 'debug'];
/**
* Home Assistant requires ALL attributes to be present in ALL MQTT messages send by the device.
* https://community.home-assistant.io/t/missing-value-with-mqtt-only-last-data-set-is-shown/47070/9
*
* Therefore zigbee2mqtt BY DEFAULT caches all values and resend it with every message.
* advanced.cache_state in configuration.yaml allows to configure this.
* https://github.com/Koenkk/zigbee2mqtt/wiki/Configuration
*/
const cacheState = settings.get().advanced && settings.get().advanced.cache_state === false ? false : true;
if (settings.get().homeassistant && !cacheState) {
logger.warn('In order for Home Assistant integration to work properly set `cache_state: true');
}
// Extensions
const ExtensionPublish = require('./extension/publish');
const ExtensionReceive = require('./extension/receive');
const ExtensionNetworkMap = require('./extension/networkMap');
const ExtensionSoftReset = require('./extension/legacy/softReset');
const ExtensionHomeAssistant = require('./extension/homeassistant');
const ExtensionConfigure = require('./extension/configure');
const ExtensionDeviceGroupMembership = require('./extension/legacy/deviceGroupMembership');
const ExtensionBridgeLegacy = require('./extension/legacy/bridgeLegacy');
const ExtensionBridge = require('./extension/bridge');
const ExtensionGroups = require('./extension/groups');
const ExtensionAvailability = require('./extension/availability');
const ExtensionBind = require('./extension/bind');
const ExtensionReport = require('./extension/report');
const ExtensionOnEvent = require('./extension/onEvent');
const ExtensionOTAUpdate = require('./extension/otaUpdate');
const ExtensionExternalConverters = require('./extension/externalConverters');
class Controller {
constructor() {
this.handleZigbeeMessage = this.handleZigbeeMessage.bind(this);
this.handleMQTTMessage = this.handleMQTTMessage.bind(this);
this.zigbee = new Zigbee(this.handleZigbeeMessage);
this.zigbee = new Zigbee();
this.mqtt = new MQTT();
this.state = new State();
this.configured = [];
this.extensions = [];
}
this.eventBus = new EventBus();
this.state = new State(this.eventBus);
start() {
this.startupLogVersion(() => {
this.zigbee.start((error) => {
if (error) {
logger.error('Failed to start', error);
} else {
// Log zigbee clients on startup and configure.
const devices = this.zigbee.getAllClients();
logger.info(`Currently ${devices.length} devices are joined:`);
devices.forEach((device) => {
logger.info(this.getDeviceStartupLogMessage(device));
this.configureDevice(device);
});
// Enable zigbee join.
if (settings.get().permit_join) {
logger.warn('`permit_join` set to `true` in configuration.yaml.');
logger.warn('Allowing new devices to join.');
logger.warn('Set `permit_join` to `false` once you joined all devices.');
}
this.zigbee.permitJoin(settings.get().permit_join);
// Connect to MQTT broker
const subscriptions = [
`${settings.get().mqtt.base_topic}/+/set`,
`${settings.get().mqtt.base_topic}/+/+/set`,
`${settings.get().mqtt.base_topic}/bridge/config/+`,
];
if (settings.get().homeassistant) {
subscriptions.push('hass/status');
}
this.mqtt.connect(this.handleMQTTMessage, subscriptions, () => this.handleMQTTConnected());
}
});
});
}
handleMQTTConnected() {
// Home Assistant MQTT discovery on MQTT connected.
if (settings.get().homeassistant) {
// MQTT discovery of all paired devices on startup.
this.zigbee.getAllClients().forEach((device) => {
const mappedModel = zigbeeShepherdConverters.findByZigbeeModel(device.modelId);
if (mappedModel) {
homeassistant.discover(device.ieeeAddr, mappedModel.model, this.mqtt, true);
}
});
}
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 ExtensionNetworkMap(this.zigbee, this.mqtt, this.state),
new ExtensionSoftReset(this.zigbee, this.mqtt, this.state),
new ExtensionRouterPollXiaomi(this.zigbee, this.mqtt, this.state),
new ExtensionPublish(...args),
new ExtensionReceive(...args),
new ExtensionDeviceGroupMembership(...args),
new ExtensionConfigure(...args),
new ExtensionNetworkMap(...args),
new ExtensionGroups(...args),
new ExtensionBind(...args),
new ExtensionOnEvent(...args),
new ExtensionOTAUpdate(...args),
];
// Resend all cached states.
this.sendAllCachedStates();
}
sendAllCachedStates() {
this.zigbee.getAllClients().forEach((device) => {
if (this.state.exists(device.ieeeAddr)) {
this.mqttPublishDeviceState(device, this.state.get(device.ieeeAddr), false);
}
});
}
stop(callback) {
this.extensions.filter((e) => e.stop).forEach((e) => e.stop());
this.state.save();
this.mqtt.disconnect();
this.zigbee.stop(callback);
}
configureDevice(device) {
let friendlyName = 'unknown';
const ieeeAddr = device.ieeeAddr;
if (settings.getDevice(ieeeAddr)) {
friendlyName = settings.getDevice(ieeeAddr).friendly_name;
}
if (ieeeAddr && device.modelId && !this.configured.includes(ieeeAddr)) {
const mappedModel = zigbeeShepherdConverters.findByZigbeeModel(device.modelId);
// Call configure function of device.
if (mappedModel && mappedModel.configure) {
mappedModel.configure(ieeeAddr, this.zigbee.shepherd, this.zigbee.getCoordinator(), (ok, msg) => {
if (ok) {
logger.info(`Succesfully configured ${friendlyName} ${ieeeAddr}`);
} else {
logger.error(`Failed to configure ${friendlyName} ${ieeeAddr}`);
}
});
}
// Setup an OnAfIncomingMsg handler if needed.
if (mappedModel && mappedModel.onAfIncomingMsg) {
mappedModel.onAfIncomingMsg.forEach((ep) => this.zigbee.registerOnAfIncomingMsg(ieeeAddr, ep));
}
this.configured.push(ieeeAddr);
}
}
getDeviceStartupLogMessage(device) {
let friendlyName = 'unknown';
let type = 'unknown';
let friendlyDevice = {model: 'unkown', description: 'unknown'};
const mappedModel = zigbeeShepherdConverters.findByZigbeeModel(device.modelId);
if (mappedModel) {
friendlyDevice = mappedModel;
if (settings.get().experimental.new_api) {
this.extensions.push(new ExtensionBridge(...args));
}
if (settings.getDevice(device.ieeeAddr)) {
friendlyName = settings.getDevice(device.ieeeAddr).friendly_name;
if (settings.get().advanced.legacy_api) {
this.extensions.push(new ExtensionBridgeLegacy(...args));
}
if (device.type) {
type = device.type;
if (settings.get().advanced.report) {
this.extensions.push(new ExtensionReport(...args));
}
return `${friendlyName} (${device.ieeeAddr}): ${friendlyDevice.model} - ` +
`${friendlyDevice.vendor} ${friendlyDevice.description} (${type})`;
}
getDeviceInfoForMqtt(device) {
const {type, ieeeAddr, nwkAddr, manufId, manufName, powerSource, modelId, status} = device;
const deviceSettings = settings.getDevice(device.ieeeAddr);
return {
ieeeAddr,
friendlyName: deviceSettings.friendly_name || '',
type,
nwkAddr,
manufId,
manufName,
powerSource,
modelId,
status,
};
}
handleZigbeeMessage(message) {
// Call extensions.
this.extensions.filter((e) => e.handleZigbeeMessage).forEach((e) => e.handleZigbeeMessage(message));
// Log the message.
let logMessage = `Recieved zigbee message of type '${message.type}' ` +
`with data '${JSON.stringify(message.data)}'`;
if (message.endpoints && message.endpoints[0].device) {
const device = message.endpoints[0].device;
logMessage += ` of device '${device.modelId}' (${device.ieeeAddr})`;
}
logger.debug(logMessage);
if (message.type == 'devInterview' && !settings.getDevice(message.data)) {
logger.info('Connecting with device...');
this.mqtt.log('pairing', 'connecting with device');
}
if (message.type == 'devIncoming') {
logger.info('Device incoming...');
this.mqtt.log('pairing', 'device incoming');
}
// We dont handle messages without endpoints.
if (!message.endpoints) {
return;
}
const device = message.endpoints[0].device;
if (!device) {
logger.warn('Message without device!');
return;
}
// Check if this is a new device.
if (!settings.getDevice(device.ieeeAddr)) {
logger.info(`New device with address ${device.ieeeAddr} connected!`);
settings.addDevice(device.ieeeAddr);
this.mqtt.log('device_connected', device.ieeeAddr);
}
// We can't handle devices without modelId.
if (!device.modelId) {
return;
}
// Map Zigbee modelID to vendor modelID.
const modelID = message.endpoints[0].device.modelId;
const mappedModel = zigbeeShepherdConverters.findByZigbeeModel(modelID);
if (!mappedModel) {
logger.warn(`Device with modelID '${modelID}' is not supported.`);
logger.warn(`Please see: https://github.com/Koenkk/zigbee2mqtt/wiki/How-to-support-new-devices`);
return;
}
// Configure device.
this.configureDevice(device);
// Home Assistant MQTT discovery
if (settings.get().homeassistant) {
homeassistant.discover(device.ieeeAddr, mappedModel.model, this.mqtt, false);
this.extensions.push(new ExtensionHomeAssistant(...args));
}
// After this point we cant handle message withoud cid anymore.
if (!message.data || (!message.data.cid && !message.data.cmdId)) {
return;
/* istanbul ignore next */
if (settings.get().advanced.soft_reset_timeout !== 0) {
this.extensions.push(new ExtensionSoftReset(...args));
}
// Find a conveter for this message.
const cid = message.data.cid;
const cmdId = message.data.cmdId;
const converters = mappedModel.fromZigbee.filter((c) => {
if (cid) {
return c.cid === cid && c.type === message.type;
} else if (cmdId) {
return c.cmd === cmdId;
}
return false;
});
if (!converters.length) {
if (cid) {
logger.warn(
`No converter available for '${mappedModel.model}' with cid '${cid}', ` +
`type '${message.type}' and data '${JSON.stringify(message.data)}'`
);
} else if (cmdId) {
logger.warn(
`No converter available for '${mappedModel.model}' with cmd '${cmdId}' ` +
`and data '${JSON.stringify(message.data)}'`
);
}
logger.warn(`Please see: https://github.com/Koenkk/zigbee2mqtt/wiki/How-to-support-new-devices.`);
return;
if (settings.get().advanced.availability_timeout) {
this.extensions.push(new ExtensionAvailability(...args));
}
if (settings.get().external_converters.length) {
this.extensions.push(new ExtensionExternalConverters(...args));
}
// Convert this Zigbee message to a MQTT message.
// Get payload for the message.
// - If a payload is returned publish it to the MQTT broker
// - If NO payload is returned do nothing. This is for non-standard behaviour
// for e.g. click switches where we need to count number of clicks and detect long presses.
converters.forEach((converter) => {
const publish = (payload) => {
// Don't cache messages with following properties:
const dontCacheProperties = ['click', 'action', 'button', 'button_left', 'button_right'];
let cache = true;
dontCacheProperties.forEach((property) => {
if (payload.hasOwnProperty(property)) {
cache = false;
}
});
// Add device linkquality.
if (message.hasOwnProperty('linkquality')) {
payload.linkquality = message.linkquality;
}
this.mqttPublishDeviceState(device, payload, cache);
};
const payload = converter.convert(mappedModel, message, publish, settings.getDevice(device.ieeeAddr));
if (payload) {
publish(payload);
const extensionPath = data.joinPath('extension');
if (fs.existsSync(extensionPath)) {
const extensions = fs.readdirSync(extensionPath).filter((f) => f.endsWith('.js'));
for (const extension of extensions) {
const Extension = require(path.join(extensionPath, extension.split('.')[0]));
this.extensions.push(new Extension(...args, settings, logger));
}
});
}
handleMQTTMessage(topic, message) {
logger.debug(`Recieved mqtt message on topic '${topic}' with data '${message}'`);
// Find extensions that could handle this.
const extensions = this.extensions.filter((e) => e.handleMQTTMessage);
// Call extensions.
const extensionResults = extensions.map((e) => e.handleMQTTMessage(topic, message));
if (topic.match(mqttConfigRegex)) {
this.handleMQTTMessageConfig(topic, message);
} else if (topic.match(mqttDeviceRegex) || topic.match(mqttDevicePrefixRegex)) {
this.handleMQTTMessageDevice(topic, message, topic.match(mqttDevicePrefixRegex));
} else if (topic === 'hass/status') {
if (message.toString().toLowerCase() === 'online') {
const timer = setTimeout(() => {
this.sendAllCachedStates();
clearTimeout(timer);
}, 20000);
}
} else if (!extensionResults.includes(true)) {
logger.warn(`Cannot handle MQTT message with topic '${topic}' and message '${message}'`);
}
}
handleMQTTMessageConfig(topic, message) {
const option = topic.split('/').slice(-1)[0];
if (option === 'permit_join') {
this.zigbee.permitJoin(message.toString().toLowerCase() === 'true');
} else if (option === 'log_level') {
const level = message.toString().toLowerCase();
if (allowedLogLevels.includes(level)) {
logger.info(`Switching log level to '${level}'`);
logger.transports.console.level = level;
logger.transports.file.level = level;
} else {
logger.error(`Could not set log level to '${level}'. Allowed level: '${allowedLogLevels.join(',')}'`);
async start() {
const settingsErrors = settings.validate();
if (settingsErrors) {
logger.error(`Refusing to start, configuration.yaml is not valid, found the following errors:`);
for (const error of settingsErrors) {
logger.error(`\t - ${error}`);
}
} else if (option === 'devices') {
const devices = this.zigbee.getAllClients().map((device) => {
const mappedModel = zigbeeShepherdConverters.findByZigbeeModel(device.modelId);
const friendlyDevice = settings.getDevice(device.ieeeAddr);
return {
ieeeAddr: device.ieeeAddr,
type: device.type,
model: mappedModel ? mappedModel.model : device.modelId,
friendly_name: friendlyDevice ? friendlyDevice.friendly_name : device.ieeeAddr,
};
});
this.mqtt.log('devices', devices);
} else if (option === 'remove') {
message = message.toString();
const IDByFriendlyName = settings.getIDByFriendlyName(message);
const deviceID = IDByFriendlyName ? IDByFriendlyName : message;
const device = this.zigbee.getDevice(deviceID);
const cleanup = () => {
// Clear Home Assistant MQTT discovery message
if (settings.get().homeassistant && device) {
const mappedModel = zigbeeShepherdConverters.findByZigbeeModel(device.modelId);
if (mappedModel) {
homeassistant.clear(deviceID, mappedModel.model, this.mqtt);
}
}
// Remove from configuration.yaml
settings.removeDevice(deviceID);
// Remove from state
this.state.remove(deviceID);
logger.info(`Successfully removed ${deviceID}`);
this.mqtt.log('device_removed', message);
};
// Remove from zigbee network.
if (device) {
this.zigbee.removeDevice(deviceID, (error) => {
if (!error) {
cleanup();
} else {
logger.error(`Failed to remove ${deviceID}`);
}
});
} else {
cleanup();
}
} else if (option === 'rename') {
const invalid = `Invalid rename message format expected {old: 'friendly_name', new: 'new_name} ` +
`got ${message.toString()}`;
let json = null;
try {
json = JSON.parse(message.toString());
} catch (e) {
logger.error(invalid);
return;
}
// Validate message
if (!json.new || !json.old) {
logger.error(invalid);
return;
}
if (settings.changeFriendlyName(json.old, json.new)) {
logger.info(`Successfully renamed - ${json.old} to ${json.new} `);
} else {
logger.error(`Failed to renamed - ${json.old} to ${json.new}`);
return;
}
// Homeassistant rediscover
if (settings.get().homeassistant) {
const ID = settings.getIDByFriendlyName(json.new);
const device = this.zigbee.getDevice(ID);
const mappedModel = zigbeeShepherdConverters.findByZigbeeModel(device.modelId);
if (mappedModel) {
homeassistant.discover(device.ieeeAddr, mappedModel.model, this.mqtt, true);
}
}
} else {
logger.warn(`Cannot handle MQTT config option '${option}' with message '${message}'`);
}
}
handleMQTTMessageDevice(topic, message, withPrefix) {
const friendlyName = topic.split('/').slice(withPrefix ? -3 : -2)[0];
const topicPrefix = withPrefix ? topic.split('/').slice(-2)[0] : '';
// Map friendlyName to deviceID.
const deviceID = settings.getIDByFriendlyName(friendlyName);
if (!deviceID) {
logger.error(`Cannot handle '${topic}' because deviceID of '${friendlyName}' cannot be found`);
return;
logger.error(
`If you don't know how to solve this, read https://www.zigbee2mqtt.io/configuration/configuration.html`,
);
process.exit(1);
}
// Convert the MQTT message to a Zigbee message.
let json = null;
this.state.start();
const info = await utils.getZigbee2mqttVersion();
logger.info(`Starting zigbee2mqtt version ${info.version} (commit #${info.commitHash})`);
// Start zigbee
try {
json = JSON.parse(message);
} catch (e) {
// Cannot be parsed to JSON, assume state message.
json = {state: message.toString()};
await this.zigbee.start();
this.callExtensionMethod('onZigbeeStarted', []);
this.zigbee.on('event', this.onZigbeeEvent.bind(this));
this.zigbee.on('adapterDisconnected', this.onZigbeeAdapterDisconnected);
} catch (error) {
logger.error('Failed to start zigbee');
logger.error('Exiting...');
logger.error(error.stack);
process.exit(1);
}
// Find ep for this device
const device = this.zigbee.getDevice(deviceID);
if (!device) {
logger.error(`Failed to find device with deviceID ${deviceID}`);
return;
// Log zigbee clients on startup
const devices = this.zigbee.getClients();
logger.info(`Currently ${devices.length} devices are joined:`);
for (const device of devices) {
const entity = this.zigbee.resolveEntity(device);
logger.info(
(entity.settings ? entity.settings.friendlyName : entity.device.ieeeAddr) +
` (${entity.device.ieeeAddr}): ` +
(entity.definition ?
`${entity.definition.model} - ${entity.definition.vendor} ${entity.definition.description} ` :
'Not supported ') +
`(${entity.device.type})`,
);
}
const mappedModel = zigbeeShepherdConverters.findByZigbeeModel(device.modelId);
if (!mappedModel) {
logger.warn(`Device with modelID '${device.modelId}' is not supported.`);
logger.warn(`Please see: https://github.com/Koenkk/zigbee2mqtt/wiki/How-to-support-new-devices`);
return;
// Enable zigbee join.
if (settings.get().permit_join) {
logger.warn('`permit_join` set to `true` in configuration.yaml.');
logger.warn('Allowing new devices to join.');
logger.warn('Set `permit_join` to `false` once you joined all devices.');
}
const ep = mappedModel.ep && mappedModel.ep[topicPrefix] ? mappedModel.ep[topicPrefix] : null;
const published = [];
try {
await this.zigbee.permitJoin(settings.get().permit_join);
} catch (error) {
logger.error(`Failed to set permit join to ${settings.get().permit_join}`);
}
Object.keys(json).forEach((key) => {
// Find converter for this key.
const converter = mappedModel.toZigbee.find((c) => c.key === key);
// MQTT
this.mqtt.on('message', this.onMQTTMessage.bind(this));
await this.mqtt.connect();
if (!converter) {
logger.error(`No converter available for '${key}' (${json[key]})`);
return;
}
const message = converter.convert(json[key], json);
if (!message) {
return;
}
const callback = (error) => {
// Devices do not report when they go off, this ensures state (on/off) is always in sync.
if (!error && (key.startsWith('state') || key === 'brightness')) {
const msg = {};
const _key = topicPrefix ? `state_${topicPrefix}` : 'state';
msg[_key] = key === 'brightness' ? 'ON' : json['state'];
this.mqttPublishDeviceState(device, msg, true);
// Send all cached states.
if (settings.get().advanced.cache_state_send_on_startup && settings.get().advanced.cache_state) {
for (const device of this.zigbee.getClients()) {
if (this.state.exists(device.ieeeAddr)) {
this.publishEntityState(device.ieeeAddr, this.state.get(device.ieeeAddr));
}
};
this.zigbee.publish(deviceID, message.cid, message.cmd, message.zclData,
message.cfg, ep, message.type, callback);
published.push({message: message, converter: converter});
});
/**
* After publishing a command to a zigbee device we want to monitor the changed attribute(s) so that
* everything stays in sync.
*/
published.forEach((p) => {
let counter = 0;
let secondsToMonitor = 1;
// In case of a transition we need to monitor for the whole transition time.
if (p.message.zclData.hasOwnProperty('transtime')) {
// Note that: transtime 10 = 0.1 seconds, 100 = 1 seconds, etc.
secondsToMonitor = (p.message.zclData.transtime / 10) + 1;
}
}
const timer = setInterval(() => {
counter++;
// 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);
}
}
// Doing a 'read' will result in the device sending a zigbee message with the current attribute value.
// which will be handled by this.handleZigbeeMessage.
p.converter.attr.forEach((attribute) => {
this.zigbee.read(deviceID, p.message.cid, attribute, ep, () => null);
});
if (counter >= secondsToMonitor) {
clearTimeout(timer);
}
}, 1000);
});
// Call extensions
await this.callExtensionMethod('onMQTTConnected', []);
}
mqttPublishDeviceState(device, payload, cache) {
const deviceID = device.ieeeAddr;
const appSettings = settings.get();
let messagePayload = {...payload};
async stop() {
// Call extensions
await this.callExtensionMethod('stop', []);
if (cacheState) {
// Add cached state to payload
if (this.state.exists(deviceID)) {
messagePayload = objectAssignDeep.noMutate(this.state.get(deviceID), payload);
// Wrap-up
this.state.stop();
await this.mqtt.disconnect();
try {
await this.zigbee.stop();
process.exit(0);
} catch (error) {
logger.error('Failed to stop zigbee');
process.exit(1);
}
}
async onZigbeeAdapterDisconnected() {
logger.error('Adapter disconnected, stopping');
await this.stop();
}
async onZigbeeEvent(type, data) {
const resolvedEntity = this.zigbee.resolveEntity(data.device || data.ieeeAddr);
if (data.device && !resolvedEntity.settings && data.device.type !== 'Coordinator') {
// Only deviceLeave doesn't have a device (not interesting to add to settings)
resolvedEntity.settings = settings.addDevice(data.device.ieeeAddr);
}
const name = resolvedEntity && resolvedEntity.settings ? resolvedEntity.settings.friendlyName : null;
if (type === 'message') {
logger.debug(
`Received Zigbee message from '${name}', type '${data.type}', cluster '${data.cluster}'` +
`, data '${JSON.stringify(data.data)}' from endpoint ${data.endpoint.ID}` +
(data.hasOwnProperty('groupID') ? ` with groupID ${data.groupID}` : ``),
);
} else if (type === 'deviceJoined') {
logger.info(`Device '${name}' joined`);
} else if (type === 'deviceInterview') {
if (data.status === 'successful') {
logger.info(`Successfully interviewed '${name}', device has successfully been paired`);
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`,
);
}
} else if (data.status === 'failed') {
logger.error(`Failed to interview '${name}', device has not successfully been paired`);
} else {
/* istanbul ignore else */
if (data.status === 'started') {
logger.info(`Starting interview of '${name}'`);
}
}
// Update state cache with new state.
if (cache) {
this.state.set(deviceID, payload);
} else if (type === 'deviceAnnounce') {
logger.debug(`Device '${name}' announced itself`);
} else {
/* istanbul ignore else */
if (type === 'deviceLeave') {
logger.warn(`Device '${name || data.ieeeAddr}' left the network`);
}
}
const deviceSettings = settings.getDevice(deviceID);
const friendlyName = deviceSettings ? deviceSettings.friendly_name : deviceID;
// Call extensions
this.callExtensionMethod('onZigbeeEvent', [type, data, resolvedEntity]);
}
onMQTTMessage(payload) {
const {topic, message} = payload;
logger.debug(`Received MQTT message on '${topic}' with data '${message}'`);
// Call extensions
this.callExtensionMethod('onMQTTMessage', [topic, message]);
}
async publishEntityState(IDorName, payload, stateChangeReason=null) {
const resolvedEntity = this.zigbee.resolveEntity(IDorName);
if (!resolvedEntity || !resolvedEntity.settings) {
logger.error(`'${IDorName}' does not exist, skipping publish`);
return;
}
let messagePayload = {...payload};
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(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: deviceSettings ? deviceSettings.retain : false,
qos: deviceSettings && deviceSettings.qos ? deviceSettings.qos : 0,
retain: utils.getObjectsProperty([resolvedEntity.settings, deviceOptions], 'retain', false),
qos: utils.getObjectsProperty([resolvedEntity.settings, deviceOptions], 'qos', 0),
};
if (appSettings.mqtt.include_device_information) {
messagePayload.device = this.getDeviceInfoForMqtt(device);
const retention = utils.getObjectsProperty([resolvedEntity.settings, deviceOptions], 'retention', false);
if (retention !== false) {
options.properties = {messageExpiryInterval: retention};
}
this.mqtt.publish(friendlyName, JSON.stringify(messagePayload), options);
const isDevice = resolvedEntity.type === 'device';
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: resolvedEntity.name,
model: resolvedEntity.definition ? resolvedEntity.definition.model : 'unknown',
};
attributes.forEach((a) => messagePayload.device[a] = resolvedEntity.device[a]);
}
const lastSeen = settings.get().advanced.last_seen;
if (isDevice && lastSeen !== 'disable' && resolvedEntity.device.lastSeen) {
messagePayload.last_seen = utils.formatDate(resolvedEntity.device.lastSeen, lastSeen);
}
// 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]);
}
if (Object.entries(messagePayload).length) {
if (settings.get().experimental.output === 'attribute_and_json') {
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(resolvedEntity.name, JSON.stringify(messagePayload), options);
} else {
/* istanbul ignore else */
if (settings.get().experimental.output === 'attribute') {
await this.iteratePayloadAttributeOutput(`${resolvedEntity.name}/`, messagePayload, options);
}
}
}
this.eventBus.emit('publishEntityState', {payload: messagePayload, entity: resolvedEntity, stateChangeReason});
}
startupLogVersion(callback) {
const git = require('git-last-commit');
const packageJSON = require('../package.json');
const version = packageJSON.version;
async iteratePayloadAttributeOutput(topicRoot, payload, options) {
for (const [key, value] of Object.entries(payload)) {
let subPayload = value;
let message;
git.getLastCommit((err, commit) => {
let commitHash = null;
if (err) {
try {
commitHash = require('../.hash.json').hash;
} catch (error) {
commitHash = 'unknown';
}
} else {
commitHash = commit.shortHash;
// Special cases
if (key === 'color' && utils.objectHasProperties(subPayload, ['r', 'g', 'b'])) {
subPayload = [subPayload.r, subPayload.g, subPayload.b];
}
logger.info(`Starting zigbee2mqtt version ${version} (commit #${commitHash})`);
// Check Array first, since it is also an Object
if (Array.isArray(subPayload)) {
message = subPayload.map((x) => `${x}`).join(',');
} else if (typeof subPayload === 'object') {
return this.iteratePayloadAttributeOutput(`${topicRoot}${key}-`, subPayload, options);
} else {
message = typeof subPayload === 'string' ? subPayload : JSON.stringify(subPayload);
}
callback();
});
await this.mqtt.publish(`${topicRoot}${key}`, message, options);
}
}
async callExtensionMethod(method, parameters) {
for (const extension of this.extensions) {
if (extension[method]) {
try {
await extension[method](...parameters);
} catch (error) {
/* istanbul ignore next */
logger.error(`Failed to call '${extension.constructor.name}' '${method}' (${error.stack})`);
/* istanbul ignore next */
if (process.env.JEST_WORKER_ID !== undefined) {
throw error;
}
}
}
}
}
}
+25
View File
@@ -0,0 +1,25 @@
const events = require('events');
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
'groupMembersChanged', // Members of a group has been changed
];
class EventBus extends events.EventEmitter {
emit(event, data) {
assert(allowedEvents.includes(event), `Event '${event}' not supported`);
super.emit(event, data);
}
on(event, callback) {
assert(allowedEvents.includes(event), `Event '${event}' not supported`);
super.on(event, callback);
}
}
module.exports = EventBus;
+200
View File
@@ -0,0 +1,200 @@
const logger = require('../util/logger');
const settings = require('../util/settings');
const utils = require('../util/utils');
const zigbeeHerdsmanConverters = require('zigbee-herdsman-converters');
const Extension = require('./extension');
// Pingable end devices, some end devices should be pinged
// e.g. E11-G13 https://github.com/Koenkk/zigbee2mqtt/issues/775#issuecomment-453683846
const pingableEndDevices = [
zigbeeHerdsmanConverters.devices.find((d) => d.model === 'E11-G13'),
zigbeeHerdsmanConverters.devices.find((d) => d.model === '53170161'),
];
const Hours25 = 1000 * 60 * 60 * 25;
/**
* This extensions pings devices to check if they are online.
*/
class Availability extends Extension {
constructor(zigbee, mqtt, state, publishEntityState, eventBus) {
super(zigbee, mqtt, state, publishEntityState, eventBus);
this.availability_timeout = settings.get().advanced.availability_timeout;
this.timers = {};
this.state = {};
this.blocklist = settings.get().advanced.availability_blocklist
.concat(settings.get().advanced.availability_blacklist)
.map((e) => settings.getEntity(e).ID);
this.passlist = settings.get().advanced.availability_passlist
.concat(settings.get().advanced.availability_whitelist)
.map((e) => settings.getEntity(e).ID);
}
inPasslistOrNotInBlocklist(device) {
const ieeeAddr = device.ieeeAddr;
const deviceSettings = settings.getDevice(ieeeAddr);
const name = deviceSettings.friendlyName;
// Passlist is not empty and device is in it, enable availability
if (this.passlist.length > 0) {
return this.passlist.includes(ieeeAddr) || (name && this.passlist.includes(name));
}
// Device is on blocklist, disable availability
if (this.blocklist.includes(ieeeAddr) || (name && this.blocklist.includes(name))) {
return false;
}
return true;
}
isPingable(device) {
if (pingableEndDevices.find((d) => d.hasOwnProperty('zigbeeModel') && d.zigbeeModel.includes(device.modelID))) {
return true;
}
// Device is a mains powered router
return utils.isRouter(device) && !utils.isBatteryPowered(device);
}
onMQTTConnected() {
for (const device of this.zigbee.getClients()) {
// Mark all devices as online on start
const ieeeAddr = device.ieeeAddr;
this.publishAvailability(device, this.state.hasOwnProperty(ieeeAddr) ? this.state[ieeeAddr] : true, true);
if (this.inPasslistOrNotInBlocklist(device)) {
if (this.isPingable(device)) {
this.setTimerPingable(device);
} else {
this.timers[ieeeAddr] = setInterval(() => {
this.handleIntervalNotPingable(device);
}, utils.secondsToMilliseconds(300));
}
}
}
}
async handleIntervalPingable(device) {
// When a device is already unavailable, log the ping failed on 'debug' instead of 'error'.
const resolvedEntity = this.zigbee.resolveEntity(device.ieeeAddr);
if (!resolvedEntity) {
logger.debug(`Stop pinging '${device.ieeeAddr}', device is not known anymore`);
return;
}
const level = this.state.hasOwnProperty(device.ieeeAddr) && !this.state[device.ieeeAddr] ? 'debug' : 'error';
try {
await device.ping();
this.publishAvailability(device, true);
logger.debug(`Successfully pinged '${resolvedEntity.name}'`);
} catch (error) {
this.publishAvailability(device, false);
logger[level](`Failed to ping '${resolvedEntity.name}'`);
} finally {
this.setTimerPingable(device);
}
}
async handleIntervalNotPingable(device) {
const resolvedEntity = this.zigbee.resolveEntity(device.ieeeAddr);
if (!resolvedEntity || !device.lastSeen) {
return;
}
const ago = Date.now() - resolvedEntity.device.lastSeen;
logger.debug(`Non-pingable device '${resolvedEntity.name}' was last seen '${ago / 1000}' seconds ago.`);
if (ago > Hours25) {
this.publishAvailability(device, false);
}
}
setTimerPingable(device) {
if (this.timers[device.ieeeAddr]) {
clearTimeout(this.timers[device.ieeeAddr]);
}
this.timers[device.ieeeAddr] = setTimeout(async () => {
await this.handleIntervalPingable(device);
}, utils.secondsToMilliseconds(this.availability_timeout));
}
async stop() {
for (const timer of Object.values(this.timers)) {
clearTimeout(timer);
}
this.zigbee.getClients().forEach((device) => this.publishAvailability(device, false));
}
async onReconnect(device) {
const resolvedEntity = this.zigbee.resolveEntity(device);
if (resolvedEntity && resolvedEntity.definition) {
const used = [];
try {
for (const key of ['state', 'brightness', 'color', 'color_temp']) {
const converter = resolvedEntity.definition.toZigbee.find((tz) => tz.key.includes(key));
if (converter && !used.includes(converter)) {
await converter.convertGet(device.endpoints[0], key, {});
used.push(converter);
}
}
} catch (error) {
logger.error(`Failed to read state of '${resolvedEntity.name}' after reconnect`);
}
}
}
publishAvailability(device, available, force=false) {
const ieeeAddr = device.ieeeAddr;
if (this.state.hasOwnProperty(ieeeAddr) && !this.state[ieeeAddr] && available) {
this.onReconnect(device);
}
const deviceSettings = settings.getDevice(ieeeAddr);
const name = deviceSettings ? deviceSettings.friendlyName : ieeeAddr;
const topic = `${name}/availability`;
const payload = available ? 'online' : 'offline';
if (this.state[ieeeAddr] !== available || force) {
this.state[ieeeAddr] = available;
this.mqtt.publish(topic, payload, {retain: true, qos: 0});
}
}
onZigbeeEvent(type, data, resolvedEntity) {
const device = data.device;
if (!device) {
return;
}
if (this.inPasslistOrNotInBlocklist(device)) {
this.publishAvailability(data.device, true);
if (this.isPingable(device)) {
// When a zigbee message from a device is received we know the device is still alive.
// => reset the timer.
this.setTimerPingable(device);
const online = this.state.hasOwnProperty(device.ieeeAddr) && this.state[device.ieeeAddr];
if (online && type === 'deviceAnnounce' && !utils.isIkeaTradfriDevice(device)) {
/**
* In case the device is powered off AND on within the availability timeout,
* zigbee2qmtt does not detect the device as offline (device is still marked online).
* When a device is turned on again the state could be out of sync.
* https://github.com/Koenkk/zigbee2mqtt/issues/1383#issuecomment-489412168
* deviceAnnounce is typically send when a device comes online.
*
* This isn't needed for TRADFRI devices as they already send the state themself.
*/
this.onReconnect(device);
}
}
}
}
}
module.exports = Availability;
+159
View File
@@ -0,0 +1,159 @@
const settings = require('../util/settings');
const logger = require('../util/logger');
const utils = require('../util/utils');
const legacyTopicRegex = new RegExp(`^${settings.get().mqtt.base_topic}/bridge/(bind|unbind)/.+$`);
const topicRegex = new RegExp(`^${settings.get().mqtt.base_topic}/bridge/request/device/(bind|unbind)`);
const Extension = require('./extension');
const clusters = ['genScenes', 'genOnOff', 'genLevelCtrl', 'lightingColorCtrl', 'closuresWindowCovering'];
// See zigbee-herdsman-converters devices.js
const defaultBindGroup = {type: 'group_number', ID: 901};
class Bind extends Extension {
constructor(zigbee, mqtt, state, publishEntityState, eventBus) {
super(zigbee, mqtt, state, publishEntityState, eventBus);
this.legacyApi = settings.get().advanced.legacy_api;
}
onMQTTConnected() {
/* istanbul ignore else */
if (this.legacyApi) {
this.mqtt.subscribe(`${settings.get().mqtt.base_topic}/bridge/bind/#`);
this.mqtt.subscribe(`${settings.get().mqtt.base_topic}/bridge/unbind/#`);
}
/* istanbul ignore else */
if (settings.get().experimental.new_api) {
this.mqtt.subscribe(`${settings.get().mqtt.base_topic}/bridge/request/device/bind`);
this.mqtt.subscribe(`${settings.get().mqtt.base_topic}/bridge/request/device/unbind`);
}
}
parseMQTTMessage(topic, message) {
let type = null;
let sourceKey = null;
let targetKey = null;
if (this.legacyApi && topic.match(legacyTopicRegex)) {
topic = topic.replace(`${settings.get().mqtt.base_topic}/bridge/`, '');
type = topic.split('/')[0];
sourceKey = topic.replace(`${type}/`, '');
targetKey = message;
} else if (settings.get().experimental.new_api && topic.match(topicRegex)) {
type = topic.endsWith('unbind') ? 'unbind' : 'bind';
message = JSON.parse(message);
sourceKey = message.from;
targetKey = message.to;
}
return {type, sourceKey, targetKey};
}
async onMQTTMessage(topic, message) {
const {type, sourceKey, targetKey} = this.parseMQTTMessage(topic, message);
if (!type) return null;
let error = null;
const source = this.zigbee.resolveEntity(sourceKey);
const target = targetKey === 'default_bind_group' ? defaultBindGroup : this.zigbee.resolveEntity(targetKey);
const responseData = {from: sourceKey, to: targetKey};
if (!source || source.type !== 'device') {
error = `Source device '${sourceKey}' does not exist`;
} else if (!target) {
error = `Target device or group '${targetKey}' does not exist`;
} else {
const sourceName = source.settings.friendlyName;
const targetName = targetKey === 'default_bind_group' ? targetKey : target.settings.friendlyName;
const successfulClusters = [];
const failedClusters = [];
const attemptedClusters = [];
// Find which clusters are supported by both the source and target.
// Groups are assumed to support all clusters.
for (const cluster of clusters) {
const targetValid = target.type === 'group' || target.type === 'group_number' ||
target.device.type === 'Coordinator' || target.endpoint.supportsInputCluster(cluster);
if (source.endpoint.supportsOutputCluster(cluster) && targetValid) {
logger.debug(`${type}ing cluster '${cluster}' from '${sourceName}' to '${targetName}'`);
attemptedClusters.push(cluster);
try {
let bindTarget = null;
if (target.type === 'group') bindTarget = target.group;
else if (target.type === 'group_number') bindTarget = target.ID;
else bindTarget = target.endpoint;
if (type === 'bind') {
await source.endpoint.bind(cluster, bindTarget);
} else {
await source.endpoint.unbind(cluster, bindTarget);
}
successfulClusters.push(cluster);
logger.info(
`Successfully ${type === 'bind' ? 'bound' : 'unbound'} cluster '${cluster}' from ` +
`'${sourceName}' to '${targetName}'`,
);
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `device_${type}`,
message: {from: sourceName, to: targetName, cluster}}),
);
}
} catch (error) {
failedClusters.push(cluster);
logger.error(
`Failed to ${type} cluster '${cluster}' from '${sourceName}' to ` +
`'${targetName}' (${error})`,
);
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `device_${type}_failed`,
message: {from: sourceName, to: targetName, cluster}}),
);
}
}
}
}
if (attemptedClusters.length === 0) {
logger.error(`Nothing to ${type} from '${sourceName}' to '${targetName}'`);
error = `Nothing to ${type}`;
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `device_${type}_failed`, message: {from: sourceName, to: targetName}}),
);
}
} else if (failedClusters.length === attemptedClusters.length) {
error = `Failed to ${type}`;
}
responseData[`clusters`] = successfulClusters;
responseData[`failed`] = failedClusters;
}
const triggeredViaLegacyApi = topic.match(legacyTopicRegex);
if (!triggeredViaLegacyApi) {
const response = utils.getResponse(message, responseData, error);
await this.mqtt.publish(`bridge/response/device/${type}`, JSON.stringify(response));
}
if (error) {
logger.error(error);
}
}
}
module.exports = Bind;
+390
View File
@@ -0,0 +1,390 @@
const logger = require('../util/logger');
const utils = require('../util/utils');
const Extension = require('./extension');
const zigbeeHerdsmanConverters = require('zigbee-herdsman-converters');
const settings = require('../util/settings');
const requestRegex = new RegExp(`${settings.get().mqtt.base_topic}/bridge/request/(.*)`);
class Bridge extends Extension {
constructor(zigbee, mqtt, state, publishEntityState, eventBus) {
super(zigbee, mqtt, state, publishEntityState, eventBus);
this.lastJoinedDeviceIeeeAddr = null;
this.requestLookup = {
'device/options': this.deviceOptions.bind(this),
'device/remove': this.deviceRemove.bind(this),
'device/rename': this.deviceRename.bind(this),
'group/add': this.groupAdd.bind(this),
'group/options': this.groupOptions.bind(this),
'group/remove': this.groupRemove.bind(this),
'group/rename': this.groupRename.bind(this),
'permit_join': this.permitJoin.bind(this),
'config/last_seen': this.configLastSeen.bind(this),
'config/elapsed': this.configElapsed.bind(this),
'config/log_level': this.configLogLevel.bind(this),
'touchlink/factory_reset': this.touchlinkFactoryReset.bind(this),
'health_check': this.healthCheck.bind(this),
};
}
async onMQTTConnected() {
this.zigbee2mqttVersion = await utils.getZigbee2mqttVersion();
this.coordinatorVersion = await this.zigbee.getCoordinatorVersion();
this.eventBus.on(`groupMembersChanged`, () => this.publishGroups());
this.mqtt.subscribe(`${settings.get().mqtt.base_topic}/bridge/request/#`);
await this.publishInfo();
await this.publishDevices();
await this.publishGroups();
}
async onMQTTMessage(topic, message) {
const match = topic.match(requestRegex);
if (match && this.requestLookup[match[1].toLowerCase()]) {
message = utils.parseJSON(message, message);
try {
const response = await this.requestLookup[match[1].toLowerCase()](message);
await this.mqtt.publish(`bridge/response/${match[1]}`, JSON.stringify(response));
} catch (error) {
logger.error(`Request '${topic}' failed with error: '${error.message}'`);
const response = utils.getResponse(message, {}, error.message);
await this.mqtt.publish(`bridge/response/${match[1]}`, JSON.stringify(response));
}
}
}
async onZigbeeEvent(type, data, resolvedEntity) {
if (type === 'deviceJoined' && resolvedEntity) {
this.lastJoinedDeviceIeeeAddr = resolvedEntity.device.ieeeAddr;
}
if (['deviceJoined', 'deviceLeave', 'deviceInterview'].includes(type)) {
let payload;
const ieeeAddress = data.device ? data.device.ieeeAddr : data.ieeeAddr;
if (type === 'deviceJoined') {
payload = {friendly_name: resolvedEntity.settings.friendlyName, ieee_address: ieeeAddress};
} else if (type === 'deviceInterview') {
payload = {
friendly_name: resolvedEntity.settings.friendlyName, status: data.status, ieee_address: ieeeAddress,
};
if (data.status === 'successful') {
payload.supported = !!resolvedEntity.definition;
payload.definition = resolvedEntity.definition ? {
model: resolvedEntity.definition.model,
vendor: resolvedEntity.definition.vendor,
description: resolvedEntity.definition.description,
supports: resolvedEntity.definition.supports,
} : null;
}
} else payload = {ieee_address: ieeeAddress}; // deviceLeave
await this.mqtt.publish(
'bridge/event',
JSON.stringify({type: utils.toSnakeCase(type), data: payload}),
{retain: false, qos: 0},
);
}
if ('deviceLeave' === type || ('deviceInterview' === type && data.status !== 'started')) {
await this.publishDevices();
}
}
/**
* Requests
*/
async deviceOptions(message) {
return this.changeEntityOptions('device', message);
}
async groupOptions(message) {
return this.changeEntityOptions('group', message);
}
async deviceRemove(message) {
return this.removeEntity('device', message);
}
async groupRemove(message) {
return this.removeEntity('group', message);
}
async healthCheck(message) {
return utils.getResponse(message, {healthy: true}, null);
}
async groupAdd(message) {
if (typeof message === 'object' && !message.hasOwnProperty('friendly_name')) {
throw new Error(`Invalid payload`);
}
const friendlyName = typeof message === 'object' ? message.friendly_name : message;
const ID = typeof message === 'object' && message.hasOwnProperty('id') ? message.id : null;
const group = settings.addGroup(friendlyName, ID);
this.zigbee.createGroup(group.ID);
this.publishGroups();
return utils.getResponse(message, {friendly_name: group.friendlyName, id: group.ID}, null);
}
async deviceRename(message) {
return this.renameEntity('device', message);
}
async groupRename(message) {
return this.renameEntity('group', message);
}
async permitJoin(message) {
const value = this.getValue(message);
await this.zigbee.permitJoin(value);
await this.publishInfo();
return utils.getResponse(message, {value: value}, null);
}
configLastSeen(message) {
const allowed = ['disable', 'ISO_8601', 'epoch', 'ISO_8601_local'];
const value = this.getValue(message);
if (!allowed.includes(value)) {
throw new Error(`'${value}' is not an allowed value, allowed: ${allowed}`);
}
settings.set(['advanced', 'last_seen'], message);
return utils.getResponse(message, {value}, null);
}
configElapsed(message) {
const allowed = [true, false];
const value = this.getValue(message);
if (!allowed.includes(value)) {
throw new Error(`'${value}' is not an allowed value, allowed: ${allowed}`);
}
settings.set(['advanced', 'elapsed'], value);
return utils.getResponse(message, {value}, null);
}
configLogLevel(message) {
const allowed = ['error', 'warn', 'info', 'debug'];
const value = this.getValue(message);
if (!allowed.includes(value)) {
throw new Error(`'${value}' is not an allowed value, allowed: ${allowed}`);
}
logger.setLevel(value);
this.publishInfo();
return utils.getResponse(message, {value}, null);
}
async touchlinkFactoryReset(message) {
logger.info('Start touchlink factory reset');
const result = await this.zigbee.touchlinkFactoryReset();
if (result) {
logger.info('Successfully factory reset device through Touchlink');
return utils.getResponse(message, {}, null);
} else {
logger.error('Failed to factory reset device through Touchlink');
throw new Error('Failed to factory reset device through Touchlink');
}
}
/**
* Utils
*/
getValue(message) {
if (typeof message === 'object') {
if (!message.hasOwnProperty('value')) {
throw new Error('No value given');
}
return message.value;
} else {
return message;
}
}
changeEntityOptions(entityType, message) {
if (typeof message !== 'object' || !message.hasOwnProperty('id') || !message.hasOwnProperty('options')) {
throw new Error(`Invalid payload`);
}
const ID = message.id;
const entity = this.getEntity(entityType, ID);
settings.changeEntityOptions(ID, message.options);
const cleanup = (o) => {
delete o.friendlyName; delete o.friendly_name; delete o.ID; delete o.type; delete o.devices;
return o;
};
const oldOptions = cleanup(entity.settings);
const newOptions = cleanup(settings.getEntity(ID));
return utils.getResponse(message, {from: oldOptions, to: newOptions, id: ID}, null);
}
renameEntity(entityType, message) {
const deviceAndHasLast = entityType === 'device' && typeof message === 'object' && message.last === true;
if (typeof message !== 'object' || (!message.hasOwnProperty('from') && !deviceAndHasLast) ||
!message.hasOwnProperty('to')) {
throw new Error(`Invalid payload`);
}
if (deviceAndHasLast && !this.lastJoinedDeviceIeeeAddr) {
throw new Error('No device has joined since start');
}
const from = deviceAndHasLast ? this.lastJoinedDeviceIeeeAddr : message.from;
const to = message.to;
const entity = this.getEntity(entityType, from);
settings.changeFriendlyName(from, to);
if (entity.type === 'device') {
this.publishDevices();
this.eventBus.emit(`deviceRenamed`, {device: entity.device});
} else {
this.publishGroups();
this.eventBus.emit(`groupRenamed`, {group: entity.group});
}
return utils.getResponse(message, {from: entity.settings.friendlyName, to}, null);
}
async removeEntity(entityType, message) {
const ID = typeof message === 'object' ? message.id : message.trim();
const entity = this.getEntity(entityType, ID);
let block = false;
let force = false;
let blockForceLog = '';
if (entityType === 'device' && typeof message === 'object') {
block = !!message.block;
force = !!message.force;
blockForceLog = ` (block: ${block}, force: ${force})`;
} else if (entityType === 'group' && typeof message === 'object') {
force = !!message.force;
blockForceLog = ` (force: ${force})`;
}
try {
logger.info(`Removing ${entity.type} '${entity.settings.friendlyName}'${blockForceLog}`);
if (entity.type === 'device') {
if (block) {
settings.blockDevice(entity.settings.ID);
}
if (force) {
await entity.device.removeFromDatabase();
} else {
await entity.device.removeFromNetwork();
}
} else {
if (force) {
await entity.group.removeFromDatabase();
} else {
await entity.group.removeFromNetwork();
}
}
// Fire event
if (entity.type === 'device') {
this.eventBus.emit('deviceRemoved', {device: entity.device});
}
// Remove from configuration.yaml
if (entity.type === 'device') {
settings.removeDevice(entity.settings.ID);
} else {
settings.removeGroup(entity.settings.ID);
}
// Remove from state
this.state.remove(entity.settings.ID);
logger.info(`Successfully removed ${entity.type} '${entity.settings.friendlyName}'${blockForceLog}`);
if (entity.type === 'device') {
this.publishDevices();
return utils.getResponse(message, {id: ID, block, force}, null);
} else {
this.publishGroups();
return utils.getResponse(message, {id: ID, force: force}, null);
}
} catch (error) {
throw new Error(
`Failed to remove ${entity.type} '${entity.settings.friendlyName}'${blockForceLog} (${error})`,
);
}
}
getEntity(type, ID) {
const entity = this.zigbee.resolveEntity(ID);
if (!entity || entity.type !== type) {
throw new Error(`${utils.capitalize(type)} '${ID}' does not exist`);
}
return entity;
}
async publishInfo() {
const payload = {
version: this.zigbee2mqttVersion.version,
commit: this.zigbee2mqttVersion.commitHash,
coordinator: this.coordinatorVersion,
log_level: logger.getLevel(),
permit_join: await this.zigbee.getPermitJoin(),
};
await this.mqtt.publish('bridge/info', JSON.stringify(payload), {retain: true, qos: 0});
}
async publishDevices() {
const devices = this.zigbee.getClients().map((device) => {
const definition = zigbeeHerdsmanConverters.findByDevice(device);
const resolved = this.zigbee.resolveEntity(device);
const definitionPayload = definition ? {
model: definition.model,
vendor: definition.vendor,
description: definition.description,
supports: definition.supports,
} : null;
return {
ieee_address: device.ieeeAddr,
type: device.type,
network_address: device.networkAddress,
supported: !!definition,
friendly_name: resolved.name,
definition: definitionPayload,
power_source: device.powerSource,
software_build_id: device.softwareBuildID,
date_code: device.dateCode,
interviewing: device.interviewing,
interview_completed: device.interviewCompleted,
};
});
await this.mqtt.publish('bridge/devices', JSON.stringify(devices), {retain: true, qos: 0});
}
async publishGroups() {
const groups = this.zigbee.getGroups().map((group) => {
const resolved = this.zigbee.resolveEntity(group);
return {
id: group.groupID,
friendly_name: resolved.name,
members: group.members.map((m) => {
return {
ieee_address: m.deviceIeeeAddress,
endpoint: m.ID,
};
}),
};
});
await this.mqtt.publish('bridge/groups', JSON.stringify(groups), {retain: true, qos: 0});
}
}
module.exports = Bridge;
+144
View File
@@ -0,0 +1,144 @@
const settings = require('../util/settings');
const utils = require('../util/utils');
const logger = require('../util/logger');
const Extension = require('./extension');
/**
* This extension calls the zigbee-herdsman-converters definition configure() method
*/
class Configure extends Extension {
constructor(zigbee, mqtt, state, publishEntityState, eventBus) {
super(zigbee, mqtt, state, publishEntityState, eventBus);
this.configuring = new Set();
this.attempts = {};
this.topic = `${settings.get().mqtt.base_topic}/bridge/request/device/configure`;
this.legacyTopic = `${settings.get().mqtt.base_topic}/bridge/configure`;
}
shouldConfigure(resolvedEntity) {
if (!resolvedEntity || !resolvedEntity.definition || !resolvedEntity.definition.configure) {
return false;
}
if (resolvedEntity.device.meta &&
resolvedEntity.device.meta.hasOwnProperty('configured') &&
resolvedEntity.device.meta.configured === resolvedEntity.definition.meta.configureKey) {
return false;
}
if (resolvedEntity.device.interviewing === true) {
return false;
}
return true;
}
onMQTTConnected() {
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
this.mqtt.subscribe(this.legacyTopic);
}
/* istanbul ignore else */
if (settings.get().experimental.new_api) {
this.mqtt.subscribe(this.topic);
}
}
async onMQTTMessage(topic, message) {
if (topic === this.legacyTopic) {
const resolvedEntity = this.zigbee.resolveEntity(message);
if (!resolvedEntity || resolvedEntity.type !== 'device') {
logger.error(`Device '${message}' does not exist`);
return;
}
if (!resolvedEntity.definition || !resolvedEntity.definition.configure) {
logger.warn(`Skipping configure of '${resolvedEntity.name}', device does not require this.`);
return;
}
this.configure(resolvedEntity, true);
} else if (topic === this.topic) {
message = utils.parseJSON(message, message);
const ID = typeof message === 'object' && message.hasOwnProperty('id') ? message.id : message;
let error = null;
const resolvedEntity = this.zigbee.resolveEntity(ID);
if (!resolvedEntity || resolvedEntity.type !== 'device') {
error = `Device '${ID}' does not exist`;
} else if (!resolvedEntity.definition || !resolvedEntity.definition.configure) {
error = `Device '${resolvedEntity.name}' cannot be configured`;
} else {
try {
await this.configure(resolvedEntity, true, true);
} catch (e) {
error = `Failed to configure (${e.message})`;
}
}
const response = utils.getResponse(message, {id: ID}, error);
await this.mqtt.publish(`bridge/response/device/configure`, JSON.stringify(response));
}
}
async onZigbeeStarted() {
this.coordinatorEndpoint = this.zigbee.getDevicesByType('Coordinator')[0].getEndpoint(1);
for (const device of this.zigbee.getClients()) {
const resolvedEntity = this.zigbee.resolveEntity(device);
if (this.shouldConfigure(resolvedEntity)) {
await this.configure(resolvedEntity);
}
}
}
onZigbeeEvent(type, data, resolvedEntity) {
const device = data.device;
if (type === 'deviceJoined' && device.meta.hasOwnProperty('configured')) {
delete device.meta.configured;
device.save();
}
if (this.shouldConfigure(resolvedEntity)) {
this.configure(resolvedEntity);
}
}
async configure(resolvedEntity, force=false, thowError=false) {
const device = resolvedEntity.device;
if (this.configuring.has(device.ieeeAddr) || (this.attempts[device.ieeeAddr] >= 3 && !force)) {
return false;
}
this.configuring.add(device.ieeeAddr);
if (!this.attempts.hasOwnProperty(device.ieeeAddr)) {
this.attempts[device.ieeeAddr] = 0;
}
logger.info(`Configuring '${resolvedEntity.name}'`);
try {
await resolvedEntity.definition.configure(device, this.coordinatorEndpoint);
logger.info(`Successfully configured '${resolvedEntity.name}'`);
device.meta.configured = resolvedEntity.definition.meta.configureKey;
device.save();
} catch (error) {
this.attempts[device.ieeeAddr]++;
const attempt = this.attempts[device.ieeeAddr];
const msg = `Failed to configure '${resolvedEntity.name}', attempt ${attempt} (${error.stack})`;
logger.error(msg);
if (thowError) {
throw error;
}
}
this.configuring.delete(device.ieeeAddr);
}
}
module.exports = Configure;
+52
View File
@@ -0,0 +1,52 @@
class Extension {
/**
* Besides intializing variables, the constructor should do nothing!
*
* @param {Zigbee} zigbee Zigbee controller
* @param {MQTT} mqtt MQTT controller
* @param {State} state State controller
* @param {Function} publishEntityState Method to publish device state to MQTT.
* @param {EventBus} eventBus The event bus
*/
constructor(zigbee, mqtt, state, publishEntityState, eventBus) {
this.zigbee = zigbee;
this.mqtt = mqtt;
this.state = state;
this.publishEntityState = publishEntityState;
this.eventBus = eventBus;
}
/**
* This method is called by the controller once Zigbee has been started.
*/
// onZigbeeStarted() {}
/**
* This method is called by the controller once connected to the MQTT server.
*/
// onMQTTConnected() {}
/**
* 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?} resolvedEntity Resolved entity returned from this.zigbee.resolveEntity()
* @param {Object?} settingsDevice Device settings
*/
// onZigbeeEvent(type, data, resolvedEntity) {}
/**
* Is called when a MQTT message is received
* @param {string} topic Topic on which the message was received
* @param {Object} message The received message
* @return {boolean} if the message was handled
*/
// onMQTTMessage(topic, message) {}
/**
* Is called once the extension has to stop
*/
// stop() {}
}
module.exports = Extension;
+18
View File
@@ -0,0 +1,18 @@
const zigbeeHerdsmanConverters = require('zigbee-herdsman-converters');
const settings = require('../util/settings');
const Extension = require('./extension');
const utils = require('../util/utils');
class ExternalConverters extends Extension {
constructor(zigbee, mqtt, state, publishEntityState, eventBus) {
super(zigbee, mqtt, state, publishEntityState, eventBus);
for (const definition of utils.getExternalConvertersDefinitions(settings)) {
const toAdd = {...definition};
delete toAdd['homeassistant'];
zigbeeHerdsmanConverters.addDeviceDefinition(toAdd);
}
}
}
module.exports = ExternalConverters;
+332
View File
@@ -0,0 +1,332 @@
const settings = require('../util/settings');
const logger = require('../util/logger');
const Extension = require('./extension');
const utils = require('../util/utils');
const postfixes = utils.getEndpointNames();
const topicRegex =
new RegExp(`^${settings.get().mqtt.base_topic}/bridge/request/group/members/(remove|add|remove_all)$`);
const legacyTopicRegex = new RegExp(`^${settings.get().mqtt.base_topic}/bridge/group/(.+)/(remove|add|remove_all)$`);
const legacyTopicRegexRemoveAll = new RegExp(`^${settings.get().mqtt.base_topic}/bridge/group/remove_all$`);
class Groups extends Extension {
constructor(zigbee, mqtt, state, publishEntityState, eventBus) {
super(zigbee, mqtt, state, publishEntityState, eventBus);
this.onStateChange = this.onStateChange.bind(this);
this.legacyApi = settings.get().advanced.legacy_api;
}
onMQTTConnected() {
/* istanbul ignore else */
if (this.legacyApi) {
this.mqtt.subscribe(`${settings.get().mqtt.base_topic}/bridge/group/remove_all`);
for (let step = 1; step < 20; step++) {
const topic = `${settings.get().mqtt.base_topic}/bridge/group/${'+/'.repeat(step)}`;
this.mqtt.subscribe(`${topic}remove`);
this.mqtt.subscribe(`${topic}add`);
this.mqtt.subscribe(`${topic}remove_all`);
}
}
/* istanbul ignore else */
if (settings.get().experimental.new_api) {
this.mqtt.subscribe(`${settings.get().mqtt.base_topic}/bridge/request/group/members/add`);
this.mqtt.subscribe(`${settings.get().mqtt.base_topic}/bridge/request/group/members/remove`);
this.mqtt.subscribe(`${settings.get().mqtt.base_topic}/bridge/request/group/members/remove_all`);
}
}
async onZigbeeStarted() {
await this.syncGroupsWithSettings();
this.eventBus.on('stateChange', this.onStateChange);
}
async syncGroupsWithSettings() {
const settingsGroups = settings.getGroups();
const zigbeeGroups = this.zigbee.getGroups();
for (const settingGroup of settingsGroups) {
const groupID = settingGroup.ID;
const zigbeeGroup = zigbeeGroups.find((g) => g.groupID === groupID) || this.zigbee.createGroup(groupID);
const settingsEntity = settingGroup.devices.map((d) => {
const entity = this.zigbee.resolveEntity(d);
if (!entity) logger.error(`Cannot find '${d}' of group '${settingGroup.friendlyName}'`);
return entity;
}).filter((e) => e != null);
// In settings but not in zigbee
for (const entity of settingsEntity) {
if (!zigbeeGroup.hasMember(entity.endpoint)) {
logger.info(`Adding '${entity.name}' to group '${settingGroup.friendlyName}'`);
await entity.endpoint.addToGroup(zigbeeGroup);
}
}
// In zigbee but not in settings
for (const endpoint of zigbeeGroup.members) {
if (!settingsEntity.find((e) => e.endpoint === endpoint)) {
const deviceSettings = settings.getDevice(endpoint.getDevice().ieeeAddr);
logger.info(`Removing '${deviceSettings.friendlyName}' from group '${settingGroup.friendlyName}'`);
await endpoint.removeFromGroup(zigbeeGroup);
}
}
}
// eslint-disable-next-line
for (const zigbeeGroup of zigbeeGroups) {
if (!settingsGroups.find((g) => g.ID === zigbeeGroup.groupID)) {
for (const endpoint of zigbeeGroup.members) {
const deviceSettings = settings.getDevice(endpoint.getDevice().ieeeAddr);
logger.info(`Removing '${deviceSettings.friendlyName}' from group ${zigbeeGroup.groupID}`);
await endpoint.removeFromGroup(zigbeeGroup);
}
}
}
}
async onStateChange(data) {
const reason = 'group_optimistic';
if (data.reason === reason) {
return;
}
const properties = ['state', 'brightness', 'color_temp', 'color'];
const payload = {};
properties.forEach((prop) => {
if (data.to.hasOwnProperty(prop)) {
payload[prop] = data.to[prop];
}
});
if (Object.keys(payload).length) {
const resolvedEntity = this.zigbee.resolveEntity(data.ID);
const zigbeeGroups = this.zigbee.getGroups().filter((zigbeeGroup) => {
const settingsGroup = settings.getGroup(zigbeeGroup.groupID);
return settingsGroup && settingsGroup.optimistic;
});
if (resolvedEntity.type === 'device') {
for (const zigbeeGroup of zigbeeGroups) {
if (zigbeeGroup.hasMember(resolvedEntity.endpoint)) {
if (!payload || payload.state !== 'OFF' || this.areAllMembersOff(zigbeeGroup)) {
await this.publishEntityState(zigbeeGroup.groupID, payload, reason);
}
}
}
} else {
const groupIDsToPublish = new Set();
for (const member of resolvedEntity.group.members) {
await this.publishEntityState(member.getDevice().ieeeAddr, payload, reason);
for (const zigbeeGroup of zigbeeGroups) {
if (zigbeeGroup.hasMember(member)) {
if (!payload || payload.state !== 'OFF' || this.areAllMembersOff(zigbeeGroup)) {
groupIDsToPublish.add(zigbeeGroup.groupID);
}
}
}
}
groupIDsToPublish.delete(resolvedEntity.group.groupID);
for (const groupID of groupIDsToPublish) {
await this.publishEntityState(groupID, payload, reason);
}
}
}
}
areAllMembersOff(zigbeeGroup) {
for (const member of zigbeeGroup.members) {
const device = member.getDevice();
if (this.state.exists(device.ieeeAddr)) {
const state = this.state.get(device.ieeeAddr);
if (state && state.state === 'ON') {
return false;
}
}
}
return true;
}
parseMQTTMessage(topic, message) {
let type = null;
let resolvedEntityGroup = null;
let resolvedEntityDevice = null;
let hasEndpointName = null;
let error = null;
let groupKey = null;
let deviceKey = null;
let triggeredViaLegacyApi = false;
/* istanbul ignore else */
const topicRegexMatch = topic.match(topicRegex);
const legacyTopicRegexRemoveAllMatch = topic.match(legacyTopicRegexRemoveAll);
const legacyTopicRegexMatch = topic.match(legacyTopicRegex);
if (this.legacyApi && (legacyTopicRegexMatch || legacyTopicRegexRemoveAllMatch)) {
triggeredViaLegacyApi = true;
if (legacyTopicRegexMatch) {
resolvedEntityGroup = this.zigbee.resolveEntity(legacyTopicRegexMatch[1]);
type = legacyTopicRegexMatch[2];
if (!resolvedEntityGroup || resolvedEntityGroup.type !== 'group') {
logger.error(`Group '${legacyTopicRegexMatch[1]}' does not exist`);
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const payload = {
friendly_name: message, group: legacyTopicRegexMatch[1], error: 'group doesn\'t exists',
};
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `device_group_${type}_failed`, message: payload}),
);
}
return {};
}
} else {
type = 'remove_all';
}
resolvedEntityDevice = this.zigbee.resolveEntity(message);
if (!resolvedEntityDevice || !resolvedEntityDevice.type === 'device') {
logger.error(`Device '${message}' does not exist`);
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const payload = {
friendly_name: message, group: legacyTopicRegexMatch[1], error: 'entity doesn\'t exists',
};
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `device_group_${type}_failed`, message: payload}),
);
}
return {};
}
hasEndpointName = postfixes.find((p) => message.endsWith(`/${p}`));
} else if (topicRegexMatch) {
type = topicRegexMatch[1];
message = JSON.parse(message);
deviceKey = message.device;
if (type !== 'remove_all') {
groupKey = message.group;
resolvedEntityGroup = this.zigbee.resolveEntity(message.group);
if (!resolvedEntityGroup || resolvedEntityGroup.type !== 'group') {
error = `Group '${message.group}' does not exist`;
}
}
resolvedEntityDevice = this.zigbee.resolveEntity(message.device);
if (!error && (!resolvedEntityDevice || !resolvedEntityDevice.type === 'device')) {
error = `Device '${message.device}' does not exist`;
}
hasEndpointName = postfixes.find((p) => message.device.endsWith(`/${p}`));
}
return {
resolvedEntityGroup, resolvedEntityDevice, type, hasEndpointName, error, groupKey, deviceKey,
triggeredViaLegacyApi,
};
}
async onMQTTMessage(topic, message) {
let {
resolvedEntityGroup, resolvedEntityDevice, type, hasEndpointName, error, triggeredViaLegacyApi,
groupKey, deviceKey,
} = this.parseMQTTMessage(topic, message);
if (!type) return;
const responseData = {device: deviceKey};
if (groupKey) {
responseData.group = groupKey;
}
if (!error) {
try {
const keys = [
`${resolvedEntityDevice.device.ieeeAddr}/${resolvedEntityDevice.endpoint.ID}`,
`${resolvedEntityDevice.name}/${resolvedEntityDevice.endpoint.ID}`,
];
const definition = resolvedEntityDevice.definition;
const endpoints = definition && definition.endpoint ?
definition.endpoint(resolvedEntityDevice.device) : null;
const endpointName = endpoints ?
Object.entries(endpoints).find((e) => e[1] === resolvedEntityDevice.endpoint.ID)[0] : null;
if (endpointName) {
keys.push(`${resolvedEntityDevice.device.ieeeAddr}/${endpointName}`);
keys.push(`${resolvedEntityDevice.name}/${endpointName}`);
}
if (!hasEndpointName) {
keys.push(resolvedEntityDevice.name);
keys.push(resolvedEntityDevice.device.ieeeAddr);
}
if (type === 'add') {
logger.info(`Adding '${resolvedEntityDevice.name}' to '${resolvedEntityGroup.name}'`);
await resolvedEntityDevice.endpoint.addToGroup(resolvedEntityGroup.group);
settings.addDeviceToGroup(resolvedEntityGroup.settings.ID, keys);
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const payload = {friendly_name: resolvedEntityDevice.name, group: resolvedEntityGroup.name};
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `device_group_add`, message: payload}),
);
}
} else if (type === 'remove') {
logger.info(`Removing '${resolvedEntityDevice.name}' from '${resolvedEntityGroup.name}'`);
await resolvedEntityDevice.endpoint.removeFromGroup(resolvedEntityGroup.group);
settings.removeDeviceFromGroup(resolvedEntityGroup.settings.ID, keys);
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const payload = {friendly_name: resolvedEntityDevice.name, group: resolvedEntityGroup.name};
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `device_group_remove`, message: payload}),
);
}
} else { // remove_all
logger.info(`Removing '${resolvedEntityDevice.name}' from all groups`);
await resolvedEntityDevice.endpoint.removeFromAllGroups();
for (const settingsGroup of settings.getGroups()) {
settings.removeDeviceFromGroup(settingsGroup.ID, keys);
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const payload = {friendly_name: resolvedEntityDevice.name};
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `device_group_remove_all`, message: payload}),
);
}
}
}
} catch (e) {
error = `Failed to ${type} from group (${e.message})`;
}
}
if (!triggeredViaLegacyApi) {
const response = utils.getResponse(message, responseData, error);
await this.mqtt.publish(`bridge/response/group/members/${type}`, JSON.stringify(response));
}
if (error) {
logger.error(error);
} else {
this.eventBus.emit('groupMembersChanged', {group: resolvedEntityGroup});
}
}
}
module.exports = Groups;
File diff suppressed because it is too large Load Diff
+470
View File
@@ -0,0 +1,470 @@
const settings = require('../../util/settings');
const logger = require('../../util/logger');
const zigbeeHerdsmanConverters = require('zigbee-herdsman-converters');
const utils = require('../../util/utils');
const assert = require('assert');
const Extension = require('../extension');
const configRegex =
new RegExp(`${settings.get().mqtt.base_topic}/bridge/config/((?:\\w+/get)|(?:\\w+/factory_reset)|(?:\\w+))`);
const allowedLogLevels = ['error', 'warn', 'info', 'debug'];
class BridgeLegacy extends Extension {
constructor(zigbee, mqtt, state, publishEntityState, eventBus) {
super(zigbee, mqtt, state, publishEntityState, eventBus);
// Bind functions
this.permitJoin = this.permitJoin.bind(this);
this.lastSeen = this.lastSeen.bind(this);
this.elapsed = this.elapsed.bind(this);
this.reset = this.reset.bind(this);
this.logLevel = this.logLevel.bind(this);
this.devices = this.devices.bind(this);
this.groups = this.groups.bind(this);
this.rename = this.rename.bind(this);
this.renameLast = this.renameLast.bind(this);
this.remove = this.remove.bind(this);
this.forceRemove = this.forceRemove.bind(this);
this.ban = this.ban.bind(this);
this.deviceOptions = this.deviceOptions.bind(this);
this.addGroup = this.addGroup.bind(this);
this.removeGroup = this.removeGroup.bind(this);
this.whitelist = this.whitelist.bind(this);
this.touchlinkFactoryReset = this.touchlinkFactoryReset.bind(this);
this.lastJoinedDeviceName = null;
// Set supported options
this.supportedOptions = {
'permit_join': this.permitJoin,
'last_seen': this.lastSeen,
'elapsed': this.elapsed,
'reset': this.reset,
'log_level': this.logLevel,
'devices': this.devices,
'groups': this.groups,
'devices/get': this.devices,
'rename': this.rename,
'rename_last': this.renameLast,
'remove': this.remove,
'force_remove': this.forceRemove,
'ban': this.ban,
'device_options': this.deviceOptions,
'add_group': this.addGroup,
'remove_group': this.removeGroup,
'force_remove_group': this.removeGroup,
'whitelist': this.whitelist,
'touchlink/factory_reset': this.touchlinkFactoryReset,
};
}
whitelist(topic, message) {
try {
const entity = settings.getEntity(message);
assert(entity, `Entity '${message}' does not exist`);
settings.whitelistDevice(entity.ID);
logger.info(`Whitelisted '${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}'`);
}
}
deviceOptions(topic, message) {
let json = null;
try {
json = JSON.parse(message);
} catch (e) {
logger.error('Failed to parse message as JSON');
return;
}
if (!json.hasOwnProperty('friendly_name') || !json.hasOwnProperty('options')) {
logger.error('Invalid JSON message, should contain "friendly_name" and "options"');
return;
}
const entity = settings.getEntity(json.friendly_name);
assert(entity, `Entity '${json.friendly_name}' does not exist`);
settings.changeEntityOptions(entity.ID, json.options);
logger.info(`Changed device specific options of '${json.friendly_name}' (${JSON.stringify(json.options)})`);
}
async permitJoin(topic, message) {
await this.zigbee.permitJoin(message.toLowerCase() === 'true');
this.publish();
}
async reset(topic, message) {
try {
await this.zigbee.reset('soft');
logger.info('Soft resetted ZNP');
} catch (error) {
logger.error('Soft reset failed');
}
}
lastSeen(topic, message) {
const allowed = ['disable', 'ISO_8601', 'epoch', 'ISO_8601_local'];
if (!allowed.includes(message)) {
logger.error(`${message} is not an allowed value, possible: ${allowed}`);
return;
}
settings.set(['advanced', 'last_seen'], message);
logger.info(`Set last_seen to ${message}`);
}
elapsed(topic, message) {
const allowed = ['true', 'false'];
if (!allowed.includes(message)) {
logger.error(`${message} is not an allowed value, possible: ${allowed}`);
return;
}
settings.set(['advanced', 'elapsed'], message === 'true');
logger.info(`Set elapsed to ${message}`);
}
logLevel(topic, message) {
const level = message.toLowerCase();
if (allowedLogLevels.includes(level)) {
logger.info(`Switching log level to '${level}'`);
logger.setLevel(level);
} else {
logger.error(`Could not set log level to '${level}'. Allowed level: '${allowedLogLevels.join(',')}'`);
}
this.publish();
}
async devices(topic, message) {
const coordinator = await this.zigbee.getCoordinatorVersion();
const devices = this.zigbee.getDevices().map((device) => {
const payload = {
ieeeAddr: device.ieeeAddr,
type: device.type,
networkAddress: device.networkAddress,
};
if (device.type !== 'Coordinator') {
const definition = zigbeeHerdsmanConverters.findByDevice(device);
const friendlyDevice = settings.getDevice(device.ieeeAddr);
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;
payload.powerSource = device.powerSource;
payload.modelID = device.modelID;
payload.hardwareVersion = device.hardwareVersion;
payload.softwareBuildID = device.softwareBuildID;
payload.dateCode = device.dateCode;
payload.lastSeen = device.lastSeen;
} else {
payload.friendly_name = 'Coordinator';
payload.softwareBuildID = coordinator.type;
payload.dateCode = coordinator.meta.revision.toString();
payload.lastSeen = Date.now();
}
return payload;
});
if (topic.split('/').pop() == 'get') {
this.mqtt.publish(`bridge/config/devices`, JSON.stringify(devices), {});
} else {
this.mqtt.publish('bridge/log', JSON.stringify({type: 'devices', message: devices}));
}
}
groups(topic, message) {
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) {
const invalid =
`Invalid rename message format expected {"old": "friendly_name", "new": "new_name"} got ${message}`;
let json = null;
try {
json = JSON.parse(message);
} catch (e) {
logger.error(invalid);
return;
}
// Validate message
if (!json.new || !json.old) {
logger.error(invalid);
return;
}
this._renameInternal(json.old, json.new);
}
renameLast(topic, message) {
if (!this.lastJoinedDeviceName) {
logger.error(`Cannot rename last joined device, no device has joined during this session`);
return;
}
this._renameInternal(this.lastJoinedDeviceName, message);
}
_renameInternal(from, to) {
try {
const isGroup = settings.getGroup(from) !== null;
settings.changeFriendlyName(from, to);
logger.info(`Successfully renamed - ${from} to ${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}`);
}
}
addGroup(topic, message) {
let id = null;
let name = null;
try {
// json payload with id and friendly_name
const json = JSON.parse(message);
if (json.hasOwnProperty('id')) {
id = json.id;
name = `group_${id}`;
}
if (json.hasOwnProperty('friendly_name')) {
name = json.friendly_name;
}
} catch (e) {
// just friendly_name
name = message;
}
if (name == null) {
logger.error('Failed to add group, missing friendly_name!');
return;
}
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}'`);
}
removeGroup(topic, message) {
const name = message;
const entity = this.zigbee.resolveEntity(message);
assert(entity && entity.type === 'group', `Group '${message}' does not exist`);
if (topic.includes('force')) {
entity.group.removeFromDatabase();
} else {
entity.group.removeFromNetwork();
}
settings.removeGroup(message);
this.mqtt.publish('bridge/log', JSON.stringify({type: `group_removed`, message}));
logger.info(`Removed group '${name}'`);
}
async forceRemove(topic, message) {
await this.removeForceRemoveOrBan('force_remove', message);
}
async remove(topic, message) {
await this.removeForceRemoveOrBan('remove', message);
}
async ban(topic, message) {
await this.removeForceRemoveOrBan('ban', message);
}
async removeForceRemoveOrBan(action, message) {
const entity = this.zigbee.resolveEntity(message.trim());
const lookup = {
ban: ['banned', 'Banning', 'ban'],
force_remove: ['force_removed', 'Force removing', 'force remove'],
remove: ['removed', 'Removing', 'remove'],
};
if (!entity) {
logger.error(`Cannot ${lookup[action][2]}, device '${message}' does not exist`);
this.mqtt.publish('bridge/log', JSON.stringify({type: `device_${lookup[action][0]}_failed`, message}));
return;
}
const cleanup = () => {
// Fire event
this.eventBus.emit('deviceRemoved', {device: entity.device});
// Remove from configuration.yaml
settings.removeDevice(entity.settings.ID);
// Remove from state
this.state.remove(entity.settings.ID);
logger.info(`Successfully ${lookup[action][0]} ${entity.settings.friendlyName}`);
this.mqtt.publish('bridge/log', JSON.stringify({type: `device_${lookup[action][0]}`, message}));
};
try {
logger.info(`${lookup[action][1]} '${entity.settings.friendlyName}'`);
if (action === 'force_remove') {
await entity.device.removeFromDatabase();
} else {
await entity.device.removeFromNetwork();
}
cleanup();
} catch (error) {
logger.error(`Failed to ${lookup[action][2]} ${entity.settings.friendlyName} (${error})`);
// eslint-disable-next-line
logger.error(`See https://www.zigbee2mqtt.io/information/mqtt_topics_and_message_structure.html#zigbee2mqttbridgeconfigremove for more info`);
this.mqtt.publish('bridge/log', JSON.stringify({type: `device_${lookup[action][0]}_failed`, message}));
}
if (action === 'ban') {
settings.banDevice(entity.settings.ID);
}
}
async onMQTTConnected() {
this.mqtt.subscribe(`${settings.get().mqtt.base_topic}/bridge/config/+`);
this.mqtt.subscribe(`${settings.get().mqtt.base_topic}/bridge/config/+/+`);
await this.publish();
}
async onMQTTMessage(topic, message) {
if (!topic.match(configRegex)) {
return false;
}
const option = topic.match(configRegex)[1];
if (!this.supportedOptions.hasOwnProperty(option)) {
return false;
}
await this.supportedOptions[option](topic, message);
return true;
}
async publish() {
const info = await utils.getZigbee2mqttVersion();
const coordinator = await this.zigbee.getCoordinatorVersion();
const topic = `bridge/config`;
const payload = {
version: info.version,
commit: info.commitHash,
coordinator,
log_level: logger.getLevel(),
permit_join: await this.zigbee.getPermitJoin(),
};
await this.mqtt.publish(topic, JSON.stringify(payload), {retain: true, qos: 0});
}
onZigbeeEvent(type, data, resolvedEntity) {
if (type === 'deviceJoined' && resolvedEntity) {
this.lastJoinedDeviceName = resolvedEntity.name;
}
if (type === 'deviceJoined') {
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 = BridgeLegacy;
@@ -0,0 +1,46 @@
/* istanbul ignore file */
const settings = require('../../util/settings');
const logger = require('../../util/logger');
const Extension = require('../extension');
const topicRegex = new RegExp(`^${settings.get().mqtt.base_topic}/bridge/device/(.+)/get_group_membership$`);
class DeviceGroupMembership extends Extension {
onMQTTConnected() {
for (let step = 1; step < 20; step++) {
const topic = `${settings.get().mqtt.base_topic}/bridge/device/${'+/'.repeat(step)}get_group_membership`;
this.mqtt.subscribe(topic);
}
}
async onMQTTMessage(topic, message) {
const match = topic.match(topicRegex);
if (!match) {
return null;
}
const entity = this.zigbee.resolveEntity(match[1]);
if (!entity || entity.type !== 'device') {
logger.error(`Device '${match[1]}' does not exist`);
return;
}
const response = await entity.endpoint.command(
`genGroups`, 'getMembership', {groupcount: 0, grouplist: []}, {}, true,
);
const {grouplist, capacity} = response;
const msgGroupList = `${entity.device.ieeeAddr} is in groups [${grouplist}]`;
let msgCapacity;
if (capacity === 254) {
msgCapacity = 'it can be a part of at least 1 more group';
} else {
msgCapacity = `its remaining group capacity is ${capacity === 255 ? 'unknown' : capacity}`;
}
logger.info(`${msgGroupList} and ${msgCapacity}`);
this.publishEntityState(entity.device.ieeeAddr, {group_list: grouplist, group_capacity: capacity});
}
}
module.exports = DeviceGroupMembership;
+66
View File
@@ -0,0 +1,66 @@
/* istanbul ignore file */
// DEPRECATED
const settings = require('../../util/settings');
const logger = require('../../util/logger');
const utils = require('../../util/utils');
const Extension = require('../extension');
/**
* This extensions soft resets the ZNP after a certain timeout.
*/
class SoftReset extends Extension {
constructor(zigbee, mqtt, state, publishEntityState, eventBus) {
super(zigbee, mqtt, state, publishEntityState, eventBus);
this.timer = null;
this.timeout = utils.secondsToMilliseconds(settings.get().advanced.soft_reset_timeout);
}
onZigbeeStarted() {
logger.debug(`Soft reset timeout set to ${utils.millisecondsToSeconds(this.timeout)} seconds`);
this.resetTimer();
}
clearTimer() {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
}
resetTimer() {
if (this.timeout === 0) {
return;
}
this.clearTimer();
this.timer = setTimeout(() => this.handleTimeout(), this.timeout);
}
async handleTimeout() {
logger.warn('Soft reset timeout triggered');
try {
await this.zigbee.reset('soft');
logger.warn('Soft resetted ZNP due to timeout');
} catch (error) {
logger.warn('Soft reset failed, trying stop/start');
await this.zigbee.stop();
logger.warn('Zigbee stopped');
try {
await this.zigbee.start();
} catch (error) {
logger.error('Failed to restart!');
}
}
this.resetTimer();
}
onZigbeeEvent() {
this.resetTimer();
}
}
module.exports = SoftReset;
+250 -44
View File
@@ -1,87 +1,293 @@
const settings = require('../util/settings');
const zigbeeShepherdConverters = require('zigbee-shepherd-converters');
const utils = require('../util/utils');
const logger = require('../util/logger');
const Extension = require('./extension');
class NetworkMap {
constructor(zigbee, mqtt, state) {
this.zigbee = zigbee;
this.mqtt = mqtt;
this.state = state;
/**
* This extension creates a network map
*/
class NetworkMap extends Extension {
constructor(zigbee, mqtt, state, publishEntityState, eventBus) {
super(zigbee, mqtt, state, publishEntityState, eventBus);
// Subscribe to topic.
this.topic = `${settings.get().mqtt.base_topic}/bridge/networkmap`;
this.mqtt.subscribe(this.topic);
this.legacyApi = settings.get().advanced.legacy_api;
this.legacyTopic = `${settings.get().mqtt.base_topic}/bridge/networkmap`;
this.legacyTopicRoutes = `${settings.get().mqtt.base_topic}/bridge/networkmap/routes`;
this.topic = `${settings.get().mqtt.base_topic}/bridge/request/networkmap`;
// Bind
this.raw = this.raw.bind(this);
this.graphviz = this.graphviz.bind(this);
this.plantuml = this.plantuml.bind(this);
// Set supported formats
this.supportedFormats = {
'raw': this.raw,
'graphviz': this.graphviz,
'plantuml': this.plantuml,
};
}
handleMQTTMessage(topic, message) {
message = message.toString();
onMQTTConnected() {
/* istanbul ignore else */
if (this.legacyApi) {
this.mqtt.subscribe(this.legacyTopic);
this.mqtt.subscribe(this.legacyTopicRoutes);
}
if (topic === this.topic && this.supportedFormats.hasOwnProperty(message)) {
this.zigbee.networkScan((result)=> {
const converted = this.supportedFormats[message](this.zigbee, result);
this.mqtt.publish(`bridge/networkmap/${message}`, converted, {});
});
return true;
if (settings.get().experimental.new_api) {
this.mqtt.subscribe(this.topic);
}
}
raw(zigbee, topology) {
async onMQTTMessage(topic, message) {
/* istanbul ignore else */
if (this.legacyApi) {
if ((topic === this.legacyTopic || topic === this.legacyTopicRoutes) &&
this.supportedFormats.hasOwnProperty(message)) {
const includeRoutes = topic === this.legacyTopicRoutes;
const topology = await this.networkScan(includeRoutes);
const converted = this.supportedFormats[message](topology);
this.mqtt.publish(`bridge/networkmap/${message}`, converted, {});
}
}
if (settings.get().experimental.new_api && topic === this.topic) {
try {
message = utils.parseJSON(message, message);
const type = typeof message === 'object' ? message.type : message;
if (!this.supportedFormats.hasOwnProperty(type)) {
throw new Error(`Type '${type}' not supported, allowed are: ${Object.keys(this.supportedFormats)}`);
}
const routes = typeof message === 'object' && message.routes;
const topology = await this.networkScan(routes);
const value = this.supportedFormats[type](topology);
await this.mqtt.publish(
'bridge/response/networkmap',
JSON.stringify(utils.getResponse(message, {routes, type, value}, null)),
);
} catch (error) {
await this.mqtt.publish(
'bridge/response/networkmap',
JSON.stringify(utils.getResponse(message, {}, error.message)),
);
}
}
}
raw(topology) {
return JSON.stringify(topology);
}
graphviz(zigbee, topology) {
let text = 'digraph G {\nnode[shape=record];\n';
const lqiDevices = new Map(topology.map((d) => [d.ieeeAddr, d]));
graphviz(topology) {
const colors = settings.get().map_options.graphviz.colors;
zigbee.getDevices().forEach((device) => {
let text = 'digraph G {\nnode[shape=record];\n';
let style = '';
topology.nodes.forEach((node) => {
const labels = [];
const friendlyDevice = settings.getDevice(device.ieeeAddr);
const friendlyName = friendlyDevice ? friendlyDevice.friendly_name : device.ieeeAddr;
// Add friendly name
labels.push(friendlyName);
labels.push(`${node.friendlyName}`);
// Add the device type
labels.push(device.type);
// Add the device short network address, ieeaddr and scan note (if any)
labels.push(
`${node.ieeeAddr} (${node.networkAddress})` +
((node.failed && node.failed.length) ? `failed: ${node.failed.join(',')}` : ''),
);
// Add the device model
const mappedModel = zigbeeShepherdConverters.findByZigbeeModel(device.modelId);
if (mappedModel) {
labels.push(`${mappedModel.vendor} ${mappedModel.description} (${mappedModel.model})`);
} else {
// This model is not supported by zigbee-shepherd-converters, add zigbee model information, if available
const zigbeeModel = [device.manufName, device.modelId].filter((a) => a).join(' ');
labels.push(zigbeeModel ? zigbeeModel : 'No model information available');
if (node.type !== 'Coordinator') {
const definition = this.zigbee.resolveEntity(node.ieeeAddr).definition;
if (definition) {
labels.push(`${definition.vendor} ${definition.description} (${definition.model})`);
} else {
// This model is not supported by zigbee-herdsman-converters, add zigbee model information
labels.push(`${node.manufacturerName} ${node.modelID}`);
}
}
// Add the device status (online/offline)
labels.push(device.status);
// Add the device last_seen timestamp
let lastSeen = 'unknown';
const date = node.type === 'Coordinator' ? Date.now() : node.lastSeen;
if (date) {
lastSeen = utils.formatDate(date, 'relative');
}
labels.push(lastSeen);
// Shape the record according to device type
if (node.type == 'Coordinator') {
style = `style="bold, filled", fillcolor="${colors.fill.coordinator}", ` +
`fontcolor="${colors.font.coordinator}"`;
} else if (node.type == 'Router') {
style = `style="rounded, filled", fillcolor="${colors.fill.router}", ` +
`fontcolor="${colors.font.router}"`;
} else {
style = `style="rounded, dashed, filled", fillcolor="${colors.fill.enddevice}", ` +
`fontcolor="${colors.font.enddevice}"`;
}
// Add the device with its labels to the graph as a node.
text += ` "${device.ieeeAddr}" [label="{${labels.join('|')}}"];\n`;
text += ` "${node.ieeeAddr}" [`+style+`, label="{${labels.join('|')}}"];\n`;
/**
* Add an edge between the device and its parent to the graph
* Add an edge between the device and its child to the graph
* NOTE: There are situations where a device is NOT in the topology, this can be e.g.
* due to not responded to the lqi scan. In that case we do not add an edge for this device.
*/
const lqiDevice = lqiDevices.get(device.ieeeAddr);
if (lqiDevice != undefined) {
text += ` "${device.ieeeAddr}" -> "${lqiDevice.parent}" [label="${lqiDevice.lqi}"]\n`;
}
topology.links.filter((e) => (e.source.ieeeAddr === node.ieeeAddr)).forEach((e) => {
const lineStyle = (node.type=='EndDevice') ? 'penwidth=1, ' :
(!e.routes.length) ? 'penwidth=0.5, ' : 'penwidth=2, ';
const lineWeight = (!e.routes.length) ? `weight=0, color="${colors.line.inactive}", ` :
`weight=1, color="${colors.line.active}", `;
const textRoutes = e.routes.map((r) => r.destinationAddress);
const lineLabels = (!e.routes.length) ? `label="${e.linkquality}"` :
`label="${e.linkquality} (routes: ${textRoutes.join(',')})"`;
text += ` "${node.ieeeAddr}" -> "${e.target.ieeeAddr}"`;
text += ` [${lineStyle}${lineWeight}${lineLabels}]\n`;
});
});
text += '}';
return text.replace(/\0/g, '');
}
plantuml(topology) {
const text = [];
text.push(`' paste into: https://www.planttext.com/`);
text.push(``);
text.push('@startuml');
topology.nodes.sort((a, b) => a.friendlyName.localeCompare(b.friendlyName)).forEach((node) => {
// Add friendly name
text.push(`card ${node.ieeeAddr} [`);
text.push(`${node.friendlyName}`);
text.push(`---`);
// Add the device short network address, ieeaddr and scan note (if any)
text.push(
`${node.ieeeAddr} (${node.networkAddress})` +
((node.failed && node.failed.length) ? ` failed: ${node.failed.join(',')}` : ''),
);
// Add the device model
if (node.type !== 'Coordinator') {
text.push(`---`);
const definition = this.zigbee.resolveEntity(node.ieeeAddr).definition;
if (definition) {
text.push(`${definition.vendor} ${definition.description} (${definition.model})`);
} else {
// This model is not supported by zigbee-herdsman-converters, add zigbee model information
text.push(`${node.manufacturerName} ${node.modelID}`);
}
}
// Add the device last_seen timestamp
let lastSeen = 'unknown';
const date = node.type === 'Coordinator' ? Date.now() : node.lastSeen;
if (date) {
lastSeen = utils.formatDate(date, 'relative');
}
text.push(`---`);
text.push(lastSeen);
text.push(`]`);
text.push(``);
});
/**
* Add edges between the devices
* NOTE: There are situations where a device is NOT in the topology, this can be e.g.
* due to not responded to the lqi scan. In that case we do not add an edge for this device.
*/
topology.links.forEach((link) => {
text.push(`${link.sourceIeeeAddr} --> ${link.targetIeeeAddr}: ${link.lqi}`);
});
text.push('');
text.push(`@enduml`);
return text.join(`\n`);
}
async networkScan(includeRoutes) {
logger.info(`Starting network scan (includeRoutes '${includeRoutes}')`);
const devices = this.zigbee.getDevices().filter((d) => d.type !== 'GreenPower');
const lqis = new Map();
const routingTables = new Map();
const failed = new Map();
for (const device of devices.filter((d) => d.type != 'EndDevice')) {
failed.set(device, []);
const resolvedEntity = this.zigbee.resolveEntity(device);
try {
const result = await device.lqi();
lqis.set(device, result);
logger.debug(`LQI succeeded for '${resolvedEntity.name}'`);
} catch (error) {
failed.get(device).push('lqi');
logger.error(`Failed to execute LQI for '${resolvedEntity.name}'`);
}
if (includeRoutes) {
try {
const result = await device.routingTable();
routingTables.set(device, result);
logger.debug(`Routing table succeeded for '${resolvedEntity.name}'`);
} catch (error) {
failed.get(device).push('routingTable');
logger.error(`Failed to execute routing table for '${resolvedEntity.name}'`);
}
}
}
logger.info(`Network scan finished`);
const networkMap = {nodes: [], links: []};
// Add nodes
for (const device of devices) {
const resolvedEntity = this.zigbee.resolveEntity(device);
networkMap.nodes.push({
ieeeAddr: device.ieeeAddr, friendlyName: resolvedEntity.name, type: device.type,
networkAddress: device.networkAddress, manufacturerName: device.manufacturerName,
modelID: device.modelID, failed: failed.get(device), lastSeen: device.lastSeen,
});
}
// Add links
lqis.forEach((lqi, device) => {
for (const neighbor of lqi.neighbors) {
if (neighbor.relationship > 3) {
// Relationship is not active, skip it
continue;
}
const link = {
source: {ieeeAddr: neighbor.ieeeAddr, networkAddress: neighbor.networkAddress},
target: {ieeeAddr: device.ieeeAddr, networkAddress: device.networkAddress},
linkquality: neighbor.linkquality, depth: neighbor.depth, routes: [],
// DEPRECATED:
sourceIeeeAddr: neighbor.ieeeAddr, targetIeeeAddr: device.ieeeAddr,
sourceNwkAddr: neighbor.networkAddress, lqi: neighbor.linkquality,
relationship: neighbor.relationship,
};
const routingTable = routingTables.get(device);
if (routingTable) {
link.routes = routingTable.table
.filter((t) => t.status === 'ACTIVE' && t.nextHop === neighbor.networkAddress);
}
networkMap.links.push(link);
}
});
return networkMap;
}
}
module.exports = NetworkMap;
+37
View File
@@ -0,0 +1,37 @@
const Extension = require('./extension');
const zigbeeHerdsmanConverters = require('zigbee-herdsman-converters');
/**
* This extension calls the zigbee-herdsman-converters onEvent.
*/
class OnEvent extends Extension {
async onZigbeeStarted() {
for (const device of this.zigbee.getClients()) {
const resolvedEntity = this.zigbee.resolveEntity(device);
this.callOnEvent(resolvedEntity, 'start', {});
}
}
onZigbeeEvent(type, data, resolvedEntity) {
if (resolvedEntity && resolvedEntity.type === 'device') {
this.callOnEvent(resolvedEntity, type, data);
}
}
async stop() {
for (const device of this.zigbee.getClients()) {
const resolvedEntity = this.zigbee.resolveEntity(device);
this.callOnEvent(resolvedEntity, 'stop', {});
}
}
callOnEvent(resolvedEntity, type, data) {
zigbeeHerdsmanConverters.onEvent(type, data, resolvedEntity.device);
if (resolvedEntity.definition && resolvedEntity.definition.onEvent) {
resolvedEntity.definition.onEvent(type, data, resolvedEntity.device);
}
}
}
module.exports = OnEvent;
+236
View File
@@ -0,0 +1,236 @@
const settings = require('../util/settings');
const logger = require('../util/logger');
const utils = require('../util/utils');
const legacyTopicRegex = new RegExp(`^${settings.get().mqtt.base_topic}/bridge/ota_update/.+$`);
const topicRegex =
new RegExp(`^${settings.get().mqtt.base_topic}/bridge/request/device/ota_update/(update|check)`, 'i');
const Extension = require('./extension');
const MINUTES_10 = 1000 * 60 * 10;
class OTAUpdate extends Extension {
constructor(zigbee, mqtt, state, publishEntityState, eventBus) {
super(zigbee, mqtt, state, publishEntityState, eventBus);
this.inProgress = new Set();
this.lastChecked = {};
this.legacyApi = settings.get().advanced.legacy_api;
}
onMQTTConnected() {
/* istanbul ignore else */
if (this.legacyApi) {
this.mqtt.subscribe(`${settings.get().mqtt.base_topic}/bridge/ota_update/check`);
this.mqtt.subscribe(`${settings.get().mqtt.base_topic}/bridge/ota_update/update`);
}
/* istanbul ignore else */
if (settings.get().experimental.new_api) {
this.mqtt.subscribe(`${settings.get().mqtt.base_topic}/bridge/request/device/ota_update/check`);
this.mqtt.subscribe(`${settings.get().mqtt.base_topic}/bridge/request/device/ota_update/update`);
}
}
async onZigbeeEvent(type, data, resolvedEntity) {
if (data.type !== 'commandQueryNextImageRequest' || !resolvedEntity || !resolvedEntity.definition) 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 resolvedEntity.definition.ota.isUpdateAvailable(data.device, logger, data.data);
this.publishEntityState(data.device.ieeeAddr, {update_available: available});
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'));
if (endpoint) {
// Some devices send OTA requests without defining OTA cluster as input cluster.
await endpoint.commandResponse('genOta', 'queryNextImageResponse', {status: supportsOTA ? 0x95 : 0x98});
}
}
async readSoftwareBuildIDAndDateCode(device, update) {
try {
const endpoint = device.endpoints.find((e) => e.supportsInputCluster('genBasic'));
const result = await endpoint.read('genBasic', ['dateCode', 'swBuildId']);
if (update) {
device.softwareBuildID = result.swBuildId;
device.dateCode = result.dateCode;
device.save();
}
return {softwareBuildID: result.swBuildId, dateCode: result.dateCode};
} catch (e) {
return null;
}
}
async onMQTTMessage(topic, message) {
if ((!this.legacyApi || !topic.match(legacyTopicRegex)) && !topic.match(topicRegex)) {
return null;
}
message = utils.parseJSON(message, message);
const ID = typeof message === 'object' && message.hasOwnProperty('id') ? message.id : message;
const resolvedEntity = this.zigbee.resolveEntity(ID);
const type = topic.substring(topic.lastIndexOf('/') + 1);
const responseData = {id: ID};
let error = null;
if (!resolvedEntity || resolvedEntity.type !== 'device') {
error = `Device '${ID}' does not exist`;
} else if (!resolvedEntity.definition || !resolvedEntity.definition.ota) {
error = `Device '${resolvedEntity.name}' does not support OTA updates`;
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const meta = {status: `not_supported`, device: resolvedEntity.name};
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `ota_update`, message: error, meta}),
);
}
} else if (this.inProgress.has(resolvedEntity.device.ieeeAddr)) {
error = `Update or check for update already in progress for '${resolvedEntity.name}'`;
} else {
this.inProgress.add(resolvedEntity.device.ieeeAddr);
if (type === 'check') {
const msg = `Checking if update available for '${resolvedEntity.name}'`;
logger.info(msg);
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const meta = {status: `checking_if_available`, device: resolvedEntity.name};
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `ota_update`, message: msg, meta}),
);
}
try {
const available = await resolvedEntity.definition.ota.isUpdateAvailable(
resolvedEntity.device, logger,
);
const msg = `${available ? 'Update' : 'No update'} available for '${resolvedEntity.name}'`;
logger.info(msg);
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const meta = {status: available ? 'available' : 'not_available', device: resolvedEntity.name};
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `ota_update`, message: msg, meta}),
);
}
this.publishEntityState(resolvedEntity.device.ieeeAddr, {update_available: available});
this.lastChecked[resolvedEntity.device.ieeeAddr] = Date.now();
responseData.updateAvailable = available;
} catch (e) {
error = `Failed to check if update available for '${resolvedEntity.name}' (${e.message})`;
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const meta = {status: `check_failed`, device: resolvedEntity.name};
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `ota_update`, message: error, meta}),
);
}
}
} else { // type === 'update'
const msg = `Updating '${resolvedEntity.name}' to latest firmware`;
logger.info(msg);
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const meta = {status: `update_in_progress`, device: resolvedEntity.name};
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `ota_update`, msg, meta}),
);
}
try {
const onProgress = (progress, remaining) => {
let msg = `Update of '${resolvedEntity.name}' at ${progress.toFixed(2)}%`;
if (remaining) {
msg += `, +- ${Math.round(remaining / 60)} minutes remaining`;
}
logger.info(msg);
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const meta = {status: `update_progress`, device: resolvedEntity.name, progress};
this.mqtt.publish('bridge/log', JSON.stringify({type: `ota_update`, message: msg, meta}));
}
};
const from_ = await this.readSoftwareBuildIDAndDateCode(resolvedEntity.device, false);
await resolvedEntity.definition.ota.updateToLatest(resolvedEntity.device, logger, onProgress);
const to = await this.readSoftwareBuildIDAndDateCode(resolvedEntity.device, true);
const [fromS, toS] = [JSON.stringify(from_), JSON.stringify(to)];
const msg = `Finished update of '${resolvedEntity.name}'` +
(to ? `, from '${fromS}' to '${toS}'` : ``);
logger.info(msg);
this.publishEntityState(resolvedEntity.device.ieeeAddr, {update_available: false});
responseData.from = from_ ? utils.toSnakeCase(from_) : null;
responseData.to = to ? utils.toSnakeCase(to) : null;
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const meta = {status: `update_succeeded`, device: resolvedEntity.name, from: from_, to};
this.mqtt.publish('bridge/log', JSON.stringify({type: `ota_update`, message, meta}));
}
} catch (e) {
error = `Update of '${resolvedEntity.name}' failed (${e.message})`;
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const meta = {status: `update_failed`, device: resolvedEntity.name};
this.mqtt.publish('bridge/log', JSON.stringify({type: `ota_update`, message: error, meta}));
}
}
}
this.inProgress.delete(resolvedEntity.device.ieeeAddr);
}
const triggeredViaLegacyApi = topic.match(legacyTopicRegex);
if (!triggeredViaLegacyApi) {
const response = utils.getResponse(message, responseData, error);
await this.mqtt.publish(`bridge/response/device/ota_update/${type}`, JSON.stringify(response));
}
if (error) {
logger.error(error);
}
}
}
module.exports = OTAUpdate;
+256
View File
@@ -0,0 +1,256 @@
const settings = require('../util/settings');
const zigbeeHerdsmanConverters = require('zigbee-herdsman-converters');
const logger = require('../util/logger');
const utils = require('../util/utils');
const assert = require('assert');
const Extension = require('./extension');
const topicRegex = new RegExp(`^(.+?)(?:/(${utils.getEndpointNames().join('|')}))?/(get|set)(?:/(.+))?`);
const groupConverters = [
zigbeeHerdsmanConverters.toZigbeeConverters.light_onoff_brightness,
zigbeeHerdsmanConverters.toZigbeeConverters.light_colortemp,
zigbeeHerdsmanConverters.toZigbeeConverters.light_color,
zigbeeHerdsmanConverters.toZigbeeConverters.light_alert,
zigbeeHerdsmanConverters.toZigbeeConverters.ignore_transition,
zigbeeHerdsmanConverters.toZigbeeConverters.cover_position_tilt,
zigbeeHerdsmanConverters.toZigbeeConverters.thermostat_occupied_heating_setpoint,
zigbeeHerdsmanConverters.toZigbeeConverters.tint_scene,
zigbeeHerdsmanConverters.toZigbeeConverters.light_brightness_move,
zigbeeHerdsmanConverters.toZigbeeConverters.light_colortemp_move,
];
class EntityPublish extends Extension {
onMQTTConnected() {
// Subscribe to topics.
const baseTopic = settings.get().mqtt.base_topic;
for (let step = 1; step < 20; step++) {
const topic = `${baseTopic}/${'+/'.repeat(step)}`;
this.mqtt.subscribe(`${topic}set`);
this.mqtt.subscribe(`${topic}set/+`);
this.mqtt.subscribe(`${topic}get`);
this.mqtt.subscribe(`${topic}get/+`);
}
}
parseTopic(topic) {
const match = topic.match(topicRegex);
if (!match) {
return null;
}
const ID = match[1].replace(`${settings.get().mqtt.base_topic}/`, '');
// If we didn't replace base_topic we received something we don't care about
if (ID === match[1] || ID.match(/bridge/)) {
return null;
}
return {ID: ID, endpointName: match[2] || '', type: match[3], attribute: match[4]};
}
async onMQTTMessage(topic, message) {
topic = this.parseTopic(topic);
if (!topic) {
return false;
}
const entityKey = `${topic.ID}` + (topic.endpointName ? `/${topic.endpointName}` : '');
const resolvedEntity = this.zigbee.resolveEntity(entityKey);
if (!resolvedEntity) {
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const message = {friendly_name: entityKey};
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `entity_not_found`, message}),
);
}
logger.error(`Entity '${entityKey}' is unknown`);
return;
}
// Get entity details
let converters = null;
let target = null;
let options = {};
let device = null;
let definition = null;
assert(resolvedEntity.type === 'device' || resolvedEntity.type === 'group');
if (resolvedEntity.type === 'device') {
if (!resolvedEntity.definition) {
logger.warn(`Device with modelID '${resolvedEntity.device.modelID}' is not supported.`);
logger.warn(`Please see: https://www.zigbee2mqtt.io/how_tos/how_to_support_new_devices.html`);
return;
}
device = resolvedEntity.device;
definition = resolvedEntity.definition;
target = resolvedEntity.endpoint;
converters = resolvedEntity.definition.toZigbee;
options = {...settings.get().device_options, ...resolvedEntity.settings};
} else {
converters = groupConverters;
target = resolvedEntity.group;
options = {...settings.get().device_options, ...resolvedEntity.settings};
definition = resolvedEntity.group.members.map((e) => zigbeeHerdsmanConverters.findByDevice(e.getDevice()));
}
// Convert the MQTT message to a Zigbee message.
let json = {};
if (topic.hasOwnProperty('attribute') && topic.attribute) {
json[topic.attribute] = message;
} else {
try {
json = JSON.parse(message);
} catch (e) {
// Cannot be parsed to JSON, assume state message.
json = {state: message};
}
}
/**
* Home Assistant always publishes 'state', even when e.g. only setting
* the color temperature. This would lead to 2 zigbee publishes, where the first one
* (state) is probably unecessary.
*/
const deviceState = this.state.get(resolvedEntity.settings.ID) || {};
if (settings.get().homeassistant) {
const hasColorTemp = json.hasOwnProperty('color_temp');
const hasColor = json.hasOwnProperty('color');
const hasBrightness = json.hasOwnProperty('brightness');
const isOn = deviceState && deviceState.state === 'ON' ? true : false;
if (isOn && (hasColorTemp || hasColor) && !hasBrightness) {
delete json.state;
logger.debug('Skipping state because of Home Assistant');
}
}
/**
* Order state & brightness based on current bulb state
*
* Not all bulbs support setting the color/color_temp while it is off
* this results in inconsistant behavior between different vendors.
*
* bulb on => move state & brightness to the back
* bulb off => move state & brightness to the front
*/
const entries = Object.entries(json);
const sorter = typeof json.state === 'string' && json.state.toLowerCase() === 'off' ? 1 : -1;
entries.sort((a, b) => (['state', 'brightness', 'brightness_percent'].includes(a[0]) ? sorter : sorter * -1));
// For each attribute call the corresponding converter
const usedConverters = {};
for (let [key, value] of entries) {
let endpointName = topic.endpointName;
let actualTarget = target;
// When the key has a endpointName included (e.g. state_right), this will override the target.
if (resolvedEntity.type === 'device' && key.includes('_')) {
const underscoreIndex = key.lastIndexOf('_');
const possibleEndpointName = key.substring(underscoreIndex + 1, key.length);
if (utils.getEndpointNames().includes(possibleEndpointName)) {
endpointName = possibleEndpointName;
key = key.substring(0, underscoreIndex);
const device = target.getDevice();
actualTarget = device.getEndpoint(definition.endpoint(device)[endpointName]);
if (!actualTarget) {
logger.error(`Device '${resolvedEntity.name}' has no endpoint '${endpointName}'`);
continue;
}
}
}
const endpointOrGroupID = actualTarget.constructor.name == 'Group' ? actualTarget.groupID : actualTarget.ID;
if (!usedConverters.hasOwnProperty(endpointOrGroupID)) usedConverters[endpointOrGroupID] = [];
const converter = converters.find((c) => c.key.includes(key));
if (usedConverters[endpointOrGroupID].includes(converter)) {
// Use a converter only once (e.g. light_onoff_brightness converters can convert state and brightness)
continue;
}
if (!converter) {
logger.error(`No converter available for '${key}' (${json[key]})`);
continue;
}
// Converter didn't return a result, skip
const meta = {
endpoint_name: endpointName,
options,
message: json,
logger,
device,
state: deviceState,
mapped: definition,
};
try {
if (topic.type === 'set' && converter.convertSet) {
logger.debug(`Publishing '${topic.type}' '${key}' to '${resolvedEntity.name}'`);
const result = await converter.convertSet(actualTarget, key, value, meta);
if (result && result.state) {
const msg = result.state;
if (endpointName) {
for (const key of ['state', 'brightness', 'color', 'color_temp']) {
if (msg.hasOwnProperty(key)) {
msg[`${key}_${endpointName}`] = msg[key];
delete msg[key];
}
}
}
this.publishEntityState(resolvedEntity.settings.ID, msg);
}
// It's possible for devices to get out of sync when writing an attribute that's not reportable.
// So here we re-read the value after a specified timeout, this timeout could for example be the
// transition time of a color change or for forcing a state read for devices that don't
// automatically report a new state when set.
// When reporting is requested for a device (report: true in device-specific settings) we won't
// ever issue a read here, as we assume the device will properly report changes.
// Only do this when the retrieve_state option is enabled for this device.
if (
resolvedEntity.type === 'device' && result && result.hasOwnProperty('readAfterWriteTime') &&
resolvedEntity.settings.retrieve_state
) {
setTimeout(() => converter.convertGet(actualTarget, key, meta), result.readAfterWriteTime);
}
} else if (topic.type === 'get' && converter.convertGet) {
logger.debug(`Publishing get '${topic.type}' '${key}' to '${resolvedEntity.name}'`);
await converter.convertGet(actualTarget, key, meta);
} else {
logger.error(`No converter available for '${topic.type}' '${key}' (${json[key]})`);
continue;
}
} catch (error) {
const message =
`Publish '${topic.type}' '${key}' to '${resolvedEntity.name}' failed: '${error}'`;
logger.error(message);
logger.debug(error.stack);
/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const meta = {friendly_name: resolvedEntity.name};
this.mqtt.publish(
'bridge/log',
JSON.stringify({type: `zigbee_publish_error`, message, meta}),
);
}
}
usedConverters[endpointOrGroupID].push(converter);
}
return true;
}
}
module.exports = EntityPublish;
+180
View File
@@ -0,0 +1,180 @@
const settings = require('../util/settings');
const logger = require('../util/logger');
const utils = require('../util/utils');
const debounce = require('debounce');
const Extension = require('./extension');
class Receive extends Extension {
constructor(zigbee, mqtt, state, publishEntityState, eventBus) {
super(zigbee, mqtt, state, publishEntityState, eventBus);
this.elapsed = {};
this.debouncers = {};
this.eventBus.on('publishEntityState', (data) => this.onPublishEntityState(data));
}
async onZigbeeStarted() {
this.coordinator = this.zigbee.getDevicesByType('Coordinator')[0];
}
async onPublishEntityState(data) {
/**
* Prevent that outdated properties are being published.
* In case that e.g. the state is currently held back by a debounce and a new state is published
* remove it from the to be send debounced message.
*/
if (data.entity.type === 'device' && this.debouncers[data.entity.device.ieeeAddr] &&
data.stateChangeReason !== 'publishDebounce') {
for (const key of Object.keys(data.payload)) {
delete this.debouncers[data.entity.device.ieeeAddr].payload[key];
}
}
}
publishDebounce(ieeeAddr, payload, time, debounceIgnore) {
if (!this.debouncers[ieeeAddr]) {
this.debouncers[ieeeAddr] = {
payload: {},
publish: debounce(() => {
this.publishEntityState(ieeeAddr, this.debouncers[ieeeAddr].payload, 'publishDebounce');
this.debouncers[ieeeAddr].payload = {};
}, time * 1000),
};
}
if (this.isPayloadConflicted(payload, this.debouncers[ieeeAddr].payload, debounceIgnore)) {
// publish previous payload immediately
this.debouncers[ieeeAddr].publish.flush();
}
// extend debounced payload with current
this.debouncers[ieeeAddr].payload = {...this.debouncers[ieeeAddr].payload, ...payload};
this.debouncers[ieeeAddr].publish();
}
// if debounce_ignore are specified (Array of strings)
// then all newPayload values with key present in debounce_ignore
// should equal or be undefined in oldPayload
// otherwise payload is conflicted
isPayloadConflicted(newPayload, oldPayload, debounceIgnore) {
let result = false;
Object.keys(oldPayload)
.filter((key) => (debounceIgnore || []).includes(key))
.forEach((key) => {
if (typeof newPayload[key] !== 'undefined' && newPayload[key] !== oldPayload[key]) {
result = true;
}
});
return result;
}
shouldProcess(type, data, resolvedEntity) {
if (type !== 'message' || !resolvedEntity) {
return false;
}
if (data.device.ieeeAddr === this.coordinator.ieeeAddr) {
logger.debug('Ignoring message from coordinator');
return false;
}
/**
* Don't handle re-transmitted Xiaomi messages.
* https://github.com/Koenkk/zigbee2mqtt/issues/1238
*
* Some Xiaomi router devices re-transmit messages from Xiaomi end devices.
* The source address of these message is set to the one of the Xiaomi router.
* Therefore it looks like if the message came from the Xiaomi router, while in
* fact it came from the end device.
* Handling these message would result in false state updates.
* The group ID attribute of these message defines the source address of the end device.
* As the same message is also received directly from the end device, it makes no sense
* to handle these messages.
*/
const hasGroupID = data.hasOwnProperty('groupID') && !!data.groupID;
if (utils.isXiaomiDevice(data.device) && utils.isRouter(data.device) && hasGroupID) {
logger.debug('Skipping re-transmitted Xiaomi message');
return false;
}
if (!resolvedEntity.definition) {
if (data.device.interviewing) {
logger.debug(`Skipping message, definition is undefined and still interviewing`);
} else {
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;
}
return true;
}
onZigbeeEvent(type, data, resolvedEntity) {
if (!this.shouldProcess(type, data, resolvedEntity)) {
return;
}
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;
});
// Check if there is an available converter, genOta messages are not interesting.
if (!converters.length && data.cluster !== 'genOta' && data.cluster !== 'genTime') {
logger.debug(
`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
// - If NO payload is returned do nothing. This is for non-standard behaviour
// for e.g. click switches where we need to count number of clicks and detect long presses.
const publish = (payload) => {
// Add device linkquality.
if (data.hasOwnProperty('linkquality')) {
payload.linkquality = data.linkquality;
}
if (settings.get().advanced.elapsed) {
const now = Date.now();
if (this.elapsed[data.device.ieeeAddr]) {
payload.elapsed = now - this.elapsed[data.device.ieeeAddr];
}
this.elapsed[data.device.ieeeAddr] = now;
}
// Check if we have to debounce
if (debounce) {
this.publishDebounce(data.device.ieeeAddr, payload, debounce, debounceIgnore);
} else {
this.publishEntityState(data.device.ieeeAddr, payload);
}
};
const meta = {device: data.device, logger};
let payload = {};
converters.forEach((converter) => {
const options = {...settings.get().device_options, ...settings.getDevice(data.device.ieeeAddr)};
const converted = converter.convert(resolvedEntity.definition, data, publish, options, meta);
if (converted) {
payload = {...payload, ...converted};
}
});
if (Object.keys(payload).length) {
publish(payload);
}
}
}
module.exports = Receive;
+257
View File
@@ -0,0 +1,257 @@
const zigbeeHerdsmanConverters = require('zigbee-herdsman-converters');
const logger = require('../util/logger');
const ZNLDP12LM = zigbeeHerdsmanConverters.devices.find((d) => d.model === 'ZNLDP12LM');
const utils = require('../util/utils');
const Extension = require('./extension');
const debounce = require('debounce');
const ZigbeeHerdsman = require('zigbee-herdsman');
const defaultConfiguration = {
minimumReportInterval: 3, maximumReportInterval: 300, reportableChange: 1,
};
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'),
zigbeeHerdsmanConverters.devices.find((d) => d.model === 'TS0001'),
];
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},
],
'genLevelCtrl': [
{attribute: 'currentLevel', ...defaultConfiguration},
],
'lightingColorCtrl': [
{
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},
{attribute: 'currentPositionTiltPercentage', ...defaultConfiguration},
],
};
const pollOnMessage = [
{
// Key is used this.pollDebouncers uniqueness
key: 1,
// On messages that have the cluster and type of below
cluster: {
manuSpecificPhilips: [
{type: 'commandHueNotification', data: {button: 2}},
{type: 'commandHueNotification', data: {button: 3}},
],
genLevelCtrl: [
{type: 'commandStep', data: {}},
{type: 'commandStepWithOnOff', data: {}},
{type: 'commandStop', data: {}},
{type: 'commandMoveWithOnOff', data: {}},
{type: 'commandStopWithOnOff', data: {}},
{type: 'commandMove', data: {}},
],
},
// Read the following attributes
read: {cluster: 'genLevelCtrl', attributes: ['currentLevel']},
// When the bound devices/members of group have the following manufacturerID
manufacturerID: ZigbeeHerdsman.Zcl.ManufacturerCode.Philips,
},
{
key: 2,
cluster: {
genOnOff: [
{type: 'commandOn', data: {}},
{type: 'commandOff', data: {}},
{type: 'commandOffWithEffect', data: {}},
],
manuSpecificPhilips: [
{type: 'commandHueNotification', data: {button: 1}},
{type: 'commandHueNotification', data: {button: 4}},
],
},
read: {cluster: 'genOnOff', attributes: ['onOff']},
manufacturerID: ZigbeeHerdsman.Zcl.ManufacturerCode.Philips,
},
];
class Report extends Extension {
constructor(zigbee, mqtt, state, publishEntityState, eventBus) {
super(zigbee, mqtt, state, publishEntityState, eventBus);
this.queue = new Set();
this.failed = new Set();
this.pollDebouncers = {};
}
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;
}
return false;
}
async setupReporting(resolvedEntity) {
const {device, definition} = resolvedEntity;
if (this.queue.has(device.ieeeAddr) || this.failed.has(device.ieeeAddr)) return;
this.queue.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, 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, items);
logger.info(
`Successfully setup reporting for '${device.ieeeAddr}' - ${ep.ID} - ${cluster}`,
);
}
}
}
// eslint-disable-next-line
device.meta.reporting = reportKey;
} catch (error) {
logger.error(
`Failed to setup reporting for '${device.ieeeAddr}' - ${error.stack}`,
);
this.failed.add(device.ieeeAddr);
}
device.save();
this.queue.delete(device.ieeeAddr);
}
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.
// Re-setup reporting.
// https://github.com/Koenkk/zigbee2mqtt/issues/966
if (messageType === 'deviceAnnounce' && utils.isIkeaTradfriDevice(device)) return true;
if (resolvedEntity.device.interviewing === true) return false;
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(definition) || definition.vendor === 'Gledopto') return false;
return true;
}
async onZigbeeStarted() {
this.coordinatorEndpoint = this.zigbee.getDevicesByType('Coordinator')[0].getEndpoint(1);
for (const device of this.zigbee.getClients()) {
const resolvedEntity = this.zigbee.resolveEntity(device);
if (this.shouldSetupReporting(resolvedEntity, null)) {
await this.setupReporting(resolvedEntity);
}
}
}
async onZigbeeEvent(type, data, resolvedEntity) {
if (this.shouldSetupReporting(resolvedEntity, type)) {
await this.setupReporting(resolvedEntity);
}
if (type === 'message') {
this.poll(data);
}
}
poll(message) {
/**
* This method poll bound endpoints and group members for state changes.
*
* A use case is e.g. a Hue Dimmer switch bound to a Hue bulb.
* Hue bulbs only report their on/off state.
* When dimming the bulb via the dimmer switch the state is therefore not reported.
* When we receive a message from a Hue dimmer we read the brightness from the bulb (if bound).
*/
const polls = pollOnMessage.filter((p) =>
p.cluster[message.cluster] && p.cluster[message.cluster].find((c) => c.type === message.type &&
utils.equalsPartial(message.data, c.data)),
);
if (polls.length) {
let toPoll = [];
// Add bound devices
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);
// If message is published to a group, add members of the group
const group = message.groupID !== 0 ? this.zigbee.getGroupByID(message.groupID) : null;
if (group) {
toPoll = toPoll.concat(group.members);
}
toPoll = new Set(toPoll);
for (const endpoint of toPoll) {
for (const poll of polls) {
if (poll.manufacturerID !== endpoint.getDevice().manufacturerID) {
continue;
}
const key = `${endpoint.deviceIeeeAddress}_${endpoint.ID}_${poll.key}`;
if (!this.pollDebouncers[key]) {
this.pollDebouncers[key] = debounce(async () => {
await endpoint.read(poll.read.cluster, poll.read.attributes);
}, 1000);
}
this.pollDebouncers[key]();
}
}
}
}
}
module.exports = Report;
-40
View File
@@ -1,40 +0,0 @@
const utils = require('../util/utils');
const interval = utils.secondsToMilliseconds(60);
/**
* This extensions polls Xiaomi Zigbee routers to keep them awake.
*/
class RouterPollXiaomi {
constructor(zigbee, mqtt, state) {
this.zigbee = zigbee;
this.timer = null;
this.startTimer();
}
startTimer() {
this.clearTimer();
this.timer = setInterval(() => this.handleInterval(), interval);
}
clearTimer() {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
}
stop() {
this.clearTimer();
}
handleInterval() {
this.zigbee.getAllClients()
.filter((d) => utils.isXiaomiDevice(d)) // Filter Xiaomi devices
.filter((d) => d.type === 'Router') // Filter routers
.filter((d) => d.powerSource && d.powerSource !== 'Battery') // Remove battery powered devices
.forEach((d) => this.zigbee.ping(d.ieeeAddr)); // Ping devices.
}
}
module.exports = RouterPollXiaomi;
-66
View File
@@ -1,66 +0,0 @@
const settings = require('../util/settings');
const logger = require('../util/logger');
const utils = require('../util/utils');
/**
* This extensions soft resets the ZNP after a certain timeout.
*/
class SoftReset {
constructor(zigbee, mqtt, state) {
this.zigbee = zigbee;
this.timer = null;
this.timeout = utils.secondsToMilliseconds(settings.get().advanced.soft_reset_timeout);
if (this.timeout === 0) {
logger.debug(`Soft reset timeout disabled`);
} else {
logger.debug(`Soft reset timeout set to ${utils.millisecondsToSeconds(this.timeout)} seconds`);
}
this.resetTimer();
}
clearTimer() {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
}
resetTimer() {
if (this.timeout === 0) {
return;
}
this.clearTimer();
this.timer = setTimeout(() => this.handleTimeout(), this.timeout);
}
handleTimeout() {
logger.warn('Soft reset timeout triggered');
this.zigbee.softReset((error) => {
if (error) {
logger.warn('Soft reset failed, trying stop/start');
this.zigbee.stop((error) => {
logger.warn('Zigbee stopped');
this.zigbee.start((error) => {
if (error) {
logger.error('Failed to restart!');
}
});
});
} else {
logger.warn('Soft resetted ZNP due to timeout');
}
this.resetTimer();
});
}
handleZigbeeMessage(message) {
this.resetTimer();
}
}
module.exports = SoftReset;
-420
View File
@@ -1,420 +0,0 @@
const settings = require('./util/settings');
const configurations = {
// Binary sensor
'binary_sensor_occupancy': {
type: 'binary_sensor',
object_id: 'occupancy',
discovery_payload: {
payload_on: true,
payload_off: false,
value_template: '{{ value_json.occupancy }}',
device_class: 'motion',
json_attributes: ['battery', 'voltage'],
},
},
'binary_sensor_contact': {
type: 'binary_sensor',
object_id: 'contact',
discovery_payload: {
payload_on: false,
payload_off: true,
value_template: '{{ value_json.contact }}',
device_class: 'door',
json_attributes: ['battery', 'voltage'],
},
},
'binary_sensor_water_leak': {
type: 'binary_sensor',
object_id: 'water_leak',
discovery_payload: {
payload_on: true,
payload_off: false,
value_template: '{{ value_json.water_leak }}',
device_class: 'moisture',
json_attributes: ['battery', 'voltage'],
},
},
'binary_sensor_smoke': {
type: 'binary_sensor',
object_id: 'smoke',
discovery_payload: {
payload_on: true,
payload_off: false,
value_template: '{{ value_json.smoke }}',
device_class: 'smoke',
json_attributes: ['battery', 'voltage'],
},
},
'binary_sensor_gas': {
type: 'binary_sensor',
object_id: 'gas',
discovery_payload: {
payload_on: true,
payload_off: false,
value_template: '{{ value_json.gas }}',
device_class: 'gas',
json_attributes: ['sensitivity'],
},
},
'binary_sensor_router': {
type: 'binary_sensor',
object_id: 'router',
discovery_payload: {
payload_on: true,
payload_off: false,
value_template: '{{ value_json.state }}',
device_class: 'connectivity',
json_attributes: ['description', 'type', 'rssi'],
},
},
// Sensor
'sensor_illuminance': {
type: 'sensor',
object_id: 'illuminance',
discovery_payload: {
unit_of_measurement: 'lx',
icon: 'mdi:theme-light-dark',
value_template: '{{ value_json.illuminance }}',
json_attributes: ['battery', 'voltage'],
},
},
'sensor_humidity': {
type: 'sensor',
object_id: 'humidity',
discovery_payload: {
unit_of_measurement: '%',
icon: 'mdi:water-percent',
value_template: '{{ value_json.humidity }}',
json_attributes: ['battery', 'voltage'],
},
},
'sensor_temperature': {
type: 'sensor',
object_id: 'temperature',
discovery_payload: {
unit_of_measurement: '°C',
icon: 'mdi:temperature-celsius',
value_template: '{{ value_json.temperature }}',
json_attributes: ['battery', 'voltage'],
},
},
'sensor_pressure': {
type: 'sensor',
object_id: 'pressure',
discovery_payload: {
unit_of_measurement: 'Pa',
icon: 'mdi:speedometer',
value_template: '{{ value_json.pressure }}',
json_attributes: ['battery', 'voltage'],
},
},
'sensor_click': {
type: 'sensor',
object_id: 'click',
discovery_payload: {
icon: 'mdi:toggle-switch',
value_template: '{{ value_json.click }}',
json_attributes: ['battery', 'voltage', 'action', 'duration'],
force_update: true,
},
},
'sensor_power': {
type: 'sensor',
object_id: 'power',
discovery_payload: {
unit_of_measurement: 'Watt',
icon: 'mdi:flash',
value_template: '{{ value_json.power }}',
json_attributes: ['voltage', 'temperature', 'consumption', 'current', 'power_factor'],
},
},
'sensor_action': {
type: 'sensor',
object_id: 'action',
discovery_payload: {
icon: 'mdi:gesture-double-tap',
value_template: '{{ value_json.action }}',
json_attributes: [
'battery', 'voltage', 'angle', 'side', 'from_side', 'to_side', 'brightness',
'angle_x_absolute', 'angle_y_absolute', 'angle_z', 'angle_y', 'angle_x', 'unknown_data',
],
force_update: true,
},
},
'sensor_brightness': {
type: 'sensor',
object_id: 'brightness',
discovery_payload: {
unit_of_measurement: 'brightness',
icon: 'mdi:brightness-5',
value_template: '{{ value_json.brightness }}',
json_attributes: [],
},
},
'sensor_lock': {
type: 'sensor',
object_id: 'lock',
discovery_payload: {
icon: 'mdi:lock',
value_template: '{{ value_json.inserted }}',
json_attributes: ['forgotten', 'keyerror'],
},
},
// Light
'light_brightness_colortemp_xy': {
type: 'light',
object_id: 'light',
discovery_payload: {
brightness: true,
color_temp: true,
xy: true,
platform: 'mqtt_json',
command_topic: true,
},
},
'light_brightness_xy': {
type: 'light',
object_id: 'light',
discovery_payload: {
brightness: true,
xy: true,
platform: 'mqtt_json',
command_topic: true,
},
},
'light_brightness_colortemp': {
type: 'light',
object_id: 'light',
discovery_payload: {
brightness: true,
color_temp: true,
platform: 'mqtt_json',
command_topic: true,
},
},
'light_brightness': {
type: 'light',
object_id: 'light',
discovery_payload: {
brightness: true,
platform: 'mqtt_json',
command_topic: true,
},
},
// Switch
'switch': {
type: 'switch',
object_id: 'switch',
discovery_payload: {
payload_off: 'OFF',
payload_on: 'ON',
value_template: '{{ value_json.state }}',
command_topic: true,
},
},
};
const switchWithPostfix = (postfix) => {
return {
type: 'switch',
object_id: `switch_${postfix}`,
discovery_payload: {
payload_off: 'OFF',
payload_on: 'ON',
value_template: `{{ value_json.state_${postfix} }}`,
command_topic: true,
command_topic_prefix: postfix,
json_attributes: [`button_${postfix}`],
},
};
};
// Map homeassitant configurations to devices.
const mapping = {
'WXKG01LM': [configurations.sensor_click],
'WXKG11LM': [configurations.sensor_click],
'WXKG12LM': [configurations.sensor_click],
'WXKG03LM': [configurations.sensor_click],
'WXKG02LM': [configurations.sensor_click],
'QBKG04LM': [configurations.switch],
'QBKG03LM': [switchWithPostfix('left'), switchWithPostfix('right')],
'WSDCGQ01LM': [configurations.sensor_temperature, configurations.sensor_humidity],
'WSDCGQ11LM': [configurations.sensor_temperature, configurations.sensor_humidity, configurations.sensor_pressure],
'RTCGQ01LM': [configurations.binary_sensor_occupancy],
'RTCGQ11LM': [configurations.binary_sensor_occupancy, configurations.sensor_illuminance],
'MCCGQ01LM': [configurations.binary_sensor_contact],
'MCCGQ11LM': [configurations.binary_sensor_contact],
'SJCGQ11LM': [configurations.binary_sensor_water_leak],
'MFKZQ01LM': [configurations.sensor_action],
'ZNCZ02LM': [configurations.switch, configurations.sensor_power],
'QBCZ11LM': [configurations.switch, configurations.sensor_power],
'LED1545G12': [configurations.light_brightness_colortemp],
'LED1623G12': [configurations.light_brightness],
'LED1622G12': [configurations.light_brightness],
'LED1537R6': [configurations.light_brightness_colortemp],
'LED1650R5': [configurations.light_brightness],
'LED1536G5': [configurations.light_brightness_colortemp],
'7299760PH': [configurations.light_brightness_xy],
'7146060PH': [configurations.light_brightness_colortemp_xy],
'F7C033': [configurations.light_brightness],
'JTYJ-GD-01LM/BW': [configurations.binary_sensor_smoke],
'PLUG EDP RE:DY': [configurations.switch, configurations.sensor_power],
'CC2530.ROUTER': [configurations.binary_sensor_router],
'AA70155': [configurations.light_brightness_colortemp],
'4058075816718': [configurations.light_brightness_colortemp_xy],
'AA69697': [configurations.light_brightness_colortemp_xy],
'HALIGHTDIMWWE27': [configurations.light_brightness],
'AB3257001NJ': [configurations.switch],
'8718696449691': [configurations.light_brightness],
'RB 185 C': [configurations.light_brightness_colortemp_xy],
'9290012573A': [configurations.light_brightness_colortemp_xy],
'LED1624G9': [configurations.light_brightness_xy],
'73742': [configurations.light_brightness_colortemp],
'73740': [configurations.light_brightness_colortemp],
'22670': [configurations.light_brightness],
'ICTC-G-1': [configurations.sensor_brightness],
'ICPSHC24-30EU-IL-1': [configurations.light_brightness],
'45852GE': [configurations.light_brightness],
'E11-G13': [configurations.light_brightness],
'LED1649C5': [configurations.light_brightness],
'ICPSHC24-10EU-IL-1': [configurations.light_brightness],
'LED1546G12': [configurations.light_brightness_colortemp],
'L1527': [configurations.light_brightness_colortemp],
'L1529': [configurations.light_brightness_colortemp],
'L1528': [configurations.light_brightness_colortemp],
'RB 165': [configurations.light_brightness],
'RB 175 W': [configurations.light_brightness],
'RS 125': [configurations.light_brightness],
'RB 145': [configurations.light_brightness],
'PL 110': [configurations.light_brightness],
'ST 110': [configurations.light_brightness],
'UC 110': [configurations.light_brightness],
'DL 110 N': [configurations.light_brightness],
'DL 110 W': [configurations.light_brightness],
'SL 110 N': [configurations.light_brightness],
'SL 110 M': [configurations.light_brightness],
'SL 110 W': [configurations.light_brightness],
'AA68199': [configurations.light_brightness_colortemp],
'QBKG11LM': [configurations.switch, configurations.sensor_power],
'QBKG12LM': [switchWithPostfix('left'), switchWithPostfix('right'), configurations.sensor_power],
'K2RGBW01': [configurations.light_brightness_colortemp_xy],
'9290011370': [configurations.light_brightness],
'DNCKATSW001': [configurations.switch],
'Z809A': [configurations.switch, configurations.sensor_power],
'NL08-0800': [configurations.light_brightness],
'915005106701': [configurations.light_brightness_colortemp_xy],
'AB32840': [configurations.light_brightness_colortemp],
'8718696485880': [configurations.light_brightness_colortemp_xy],
'8718696598283': [configurations.light_brightness_colortemp],
'73693': [configurations.light_brightness_colortemp_xy],
'324131092621': [configurations.sensor_action],
'9290012607': [
configurations.binary_sensor_occupancy, configurations.sensor_temperature,
configurations.sensor_illuminance,
],
'GL-C-008': [configurations.light_brightness_colortemp_xy],
'STSS-MULT-001': [configurations.binary_sensor_contact],
'E11-G23': [configurations.light_brightness],
'AC03645': [configurations.light_brightness_colortemp_xy],
'AC03641': [configurations.light_brightness],
'FB56+ZSW05HG1.2': [configurations.switch],
'72922-A': [configurations.switch],
'AC03642': [configurations.light_brightness_colortemp],
'DNCKATSW002': [switchWithPostfix('left'), switchWithPostfix('right')],
'DNCKATSW003': [switchWithPostfix('left'), switchWithPostfix('right'), switchWithPostfix('center')],
'DNCKATSW004': [
switchWithPostfix('bottom_left'), switchWithPostfix('bottom_right'),
switchWithPostfix('top_left'), switchWithPostfix('top_right'),
],
'BY 165': [configurations.light_brightness],
'ZLED-2709': [configurations.light_brightness],
'8718696548738': [configurations.light_brightness_colortemp],
'4052899926110': [configurations.light_brightness_colortemp_xy],
'Z01-CIA19NAE26': [configurations.light_brightness],
'E11-N1EA': [configurations.light_brightness_colortemp_xy],
'74283': [configurations.light_brightness],
'JTQJ-BF-01LM/BW': [configurations.binary_sensor_gas],
'50045': [configurations.light_brightness],
'AV2010/22': [configurations.binary_sensor_occupancy],
'3210-L': [configurations.switch],
'7299355PH': [configurations.light_brightness_xy],
'45857GE': [configurations.light_brightness],
'A6121': [configurations.sensor_lock],
'433714': [configurations.light_brightness],
'3261030P7': [configurations.light_brightness_colortemp],
'DJT11LM': [configurations.sensor_action],
'E1603': [configurations.switch],
'7199960PH': [configurations.light_brightness_xy],
'74696': [configurations.light_brightness],
'AB35996': [configurations.light_brightness_colortemp_xy],
'AB401130055': [configurations.light_brightness_colortemp],
'74282': [configurations.light_brightness_colortemp],
};
// A map of all discoverd devices
const discovered = {};
function discover(deviceID, model, mqtt, force) {
// Check if already discoverd and check if there are configs.
const discover = force || !discovered[deviceID];
if (!discover || !mapping[model] || !settings.getDevice(deviceID)) {
return;
}
const friendlyName = settings.getDevice(deviceID).friendly_name;
mapping[model].forEach((config) => {
const topic = `${config.type}/${deviceID}/${config.object_id}/config`;
const payload = {...config.discovery_payload};
payload.state_topic = `${settings.get().mqtt.base_topic}/${friendlyName}`;
payload.availability_topic = `${settings.get().mqtt.base_topic}/bridge/state`;
// Set unique names in cases this device produces multiple entities in homeassistant.
payload.name = mapping[model].length > 1 ? `${friendlyName}_${config.object_id}` : friendlyName;
// Only set unique_id when user did not set a friendly_name yet,
// see https://github.com/Koenkk/zigbee2mqtt/issues/138
if (deviceID === friendlyName) {
payload.unique_id = `${deviceID}_${config.object_id}_${settings.get().mqtt.base_topic}`;
}
if (payload.command_topic) {
payload.command_topic = `${settings.get().mqtt.base_topic}/${friendlyName}/`;
if (payload.command_topic_prefix) {
payload.command_topic += `${payload.command_topic_prefix}/`;
}
payload.command_topic += 'set';
}
mqtt.publish(topic, JSON.stringify(payload), {retain: true, qos: 0}, null, 'homeassistant');
});
discovered[deviceID] = true;
}
function clear(deviceID, model, mqtt) {
// Check if there are configs.
if (!mapping[model]) {
return;
}
mapping[model].forEach((config) => {
const topic = `${config.type}/${deviceID}/${config.object_id}/config`;
const payload = '';
mqtt.publish(topic, payload, {retain: true, qos: 0}, null, 'homeassistant');
});
discovered[deviceID] = false;
}
module.exports = {
mapping: mapping,
discover: (deviceID, model, mqtt, force) => discover(deviceID, model, mqtt, force),
clear: (deviceID, model, mqtt) => clear(deviceID, model, mqtt),
};
+56 -46
View File
@@ -1,25 +1,48 @@
const mqtt = require('mqtt');
const logger = require('./util/logger');
const settings = require('./util/settings');
const fs = require('fs');
const events = require('events');
class MQTT {
class MQTT extends events.EventEmitter {
constructor() {
this.handleConnect = this.handleConnect.bind(this);
this.handleMessage = this.handleMessage.bind(this);
super();
this.onMessage = this.onMessage.bind(this);
}
connect(onMessage, subscriptions, callback) {
async connect() {
const mqttSettings = settings.get().mqtt;
logger.info(`Connecting to MQTT server at ${mqttSettings.server}`);
const options = {
will: {
topic: this.prefixTopic('bridge/state'),
topic: `${settings.get().mqtt.base_topic}/bridge/state`,
payload: 'offline',
retain: true,
},
};
if (mqttSettings.version) {
options.protocolVersion = mqttSettings.version;
}
if (mqttSettings.keepalive) {
logger.debug(`Using MQTT keepalive: ${mqttSettings.keepalive}`);
options.keepalive = mqttSettings.keepalive;
}
if (mqttSettings.ca) {
logger.debug(`MQTT SSL/TLS: Path to CA certificate = ${mqttSettings.ca}`);
options.ca = fs.readFileSync(mqttSettings.ca);
}
if (mqttSettings.key && mqttSettings.cert) {
logger.debug(`MQTT SSL/TLS: Path to client key = ${mqttSettings.key}`);
logger.debug(`MQTT SSL/TLS: Path to client certificate = ${mqttSettings.cert}`);
options.key = fs.readFileSync(mqttSettings.key);
options.cert = fs.readFileSync(mqttSettings.cert);
}
if (mqttSettings.user && mqttSettings.password) {
options.username = mqttSettings.user;
options.password = mqttSettings.password;
@@ -35,16 +58,6 @@ class MQTT {
options.rejectUnauthorized = false;
}
this.client = mqtt.connect(mqttSettings.server, options);
// Register callbacks.
this.client.on('connect', () => {
this.handleConnect();
callback();
});
this.client.on('message', this.handleMessage);
// Set timer at interval to check if connected to MQTT server.
const interval = 10 * 1000; // seconds * 1000.
this.connectionTimer = setInterval(() => {
@@ -53,57 +66,54 @@ class MQTT {
}
}, interval);
this.onMessage = onMessage;
this.subscriptions = subscriptions;
}
return new Promise((resolve) => {
this.client = mqtt.connect(mqttSettings.server, options);
disconnect() {
clearTimeout(this.connectionTimer);
this.connectionTimer = null;
this.client.on('connect', () => {
logger.info('Connected to MQTT server');
this.publish('bridge/state', 'online', {retain: true, qos: 0});
resolve();
});
this.publish('bridge/state', 'offline', {retain: true, qos: 0}, () => {
logger.info('Disconnecting from MQTT server');
this.client.end();
this.client.on('message', this.onMessage);
});
}
handleConnect() {
logger.info('Connected to MQTT server');
this.publish('bridge/state', 'online', {retain: true, qos: 0});
this.subscriptions.forEach((topic) => this.subscribe(topic));
async disconnect() {
clearTimeout(this.connectionTimer);
this.connectionTimer = null;
await this.publish('bridge/state', 'offline', {retain: true, qos: 0});
logger.info('Disconnecting from MQTT server');
this.client.end();
}
subscribe(topic) {
this.client.subscribe(topic);
}
handleMessage(topic, message) {
if (this.onMessage) {
this.onMessage(topic, message);
}
onMessage(topic, message) {
this.emit('message', {topic, message: message.toString()});
}
publish(topic, payload, options, callback, baseTopic) {
topic = this.prefixTopic(topic, baseTopic);
isConnected() {
return this.client && !this.client.reconnecting;
}
if (!this.client || this.client.reconnecting) {
async publish(topic, payload, options, base=settings.get().mqtt.base_topic) {
topic = `${base}/${topic}`;
options = {qos: 0, retain: false, ...options};
if (!this.isConnected()) {
logger.error(`Not connected to MQTT server!`);
logger.error(`Cannot send message: topic: '${topic}', payload: '${payload}`);
return;
}
logger.info(`MQTT publish, topic: '${topic}', payload: '${payload}'`);
this.client.publish(topic, payload, options, callback);
}
logger.info(`MQTT publish: topic '${topic}', payload '${payload}'`);
prefixTopic(topic, baseTopic) {
baseTopic = baseTopic ? baseTopic : settings.get().mqtt.base_topic;
return `${baseTopic}/${topic}`;
}
log(type, message) {
const payload = {type: type, message: message};
this.publish('bridge/log', JSON.stringify(payload), {retain: false});
return new Promise((resolve) => {
this.client.publish(topic, payload, options, () => resolve());
});
}
}
+49 -7
View File
@@ -1,19 +1,45 @@
const logger = require('./util/logger');
const data = require('./util/data');
const settings = require('./util/settings');
const fs = require('fs');
const objectAssignDeep = require('object-assign-deep');
const saveInterval = 1000 * 60 * 5; // 5 minutes
const dontCacheProperties = [
'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 {
constructor() {
constructor(eventBus) {
this.state = {};
this.file = data.joinPath('state.json');
this.timer = null;
this.eventBus = eventBus;
}
start() {
this._load();
// Save the state on every interval
this.clearTimer();
this.timer = setInterval(() => this.save(), saveInterval);
}
clearTimer() {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
}
stop() {
this.clearTimer();
this.save();
}
_load() {
if (fs.existsSync(this.file)) {
try {
@@ -23,14 +49,18 @@ class State {
logger.debug(`Failed to load state from file ${this.file} (corrupt file?)`);
}
} else {
logger.debug(`Can't load state from file ${this.file} (doesn't exsist)`);
logger.debug(`Can't load state from file ${this.file} (doesn't exist)`);
}
}
save() {
logger.debug(`Saving state to file ${this.file}`);
const json = JSON.stringify(this.state, null, 4);
fs.writeFileSync(this.file, json, 'utf8');
if (settings.get().advanced.cache_state_persistent) {
logger.debug(`Saving state to file ${this.file}`);
const json = JSON.stringify(this.state, null, 4);
fs.writeFileSync(this.file, json, 'utf8');
} else {
logger.debug(`Not saving state`);
}
}
exists(ID) {
@@ -41,8 +71,20 @@ class State {
return this.state[ID];
}
set(ID, state) {
this.state[ID] = state;
set(ID, state, reason=null) {
const toState = objectAssignDeep.noMutate(state);
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.eventBus.emit('stateChange', {ID, from: fromState, to: toState, reason});
}
remove(ID) {
+12 -5
View File
@@ -2,14 +2,21 @@ const path = require('path');
let dataPath = null;
if (process.env.ZIGBEE2MQTT_DATA) {
dataPath = process.env.ZIGBEE2MQTT_DATA;
} else {
dataPath = path.join(__dirname, '..', '..', 'data');
dataPath = path.normalize(dataPath);
function load() {
if (process.env.ZIGBEE2MQTT_DATA) {
dataPath = process.env.ZIGBEE2MQTT_DATA;
} else {
dataPath = path.join(__dirname, '..', '..', 'data');
dataPath = path.normalize(dataPath);
}
}
load();
module.exports = {
joinPath: (file) => path.join(dataPath, file),
getPath: () => dataPath,
// For test only.
_reload: () => load(),
};
+116 -44
View File
@@ -5,58 +5,130 @@ const path = require('path');
const fs = require('fs');
const fx = require('mkdir-recursive');
const rimraf = require('rimraf');
const colorizer = winston.format.colorize();
const assert = require('assert');
// What transports to enable
const output = settings.get().advanced.log_output;
// Directory to log to
const timestamp = moment(Date.now()).format('YYYY-MM-DD.HH-mm-ss');
const directory = settings.get().advanced.log_directory.replace('%TIMESTAMP%', timestamp);
const logFilename = settings.get().advanced.log_file.replace('%TIMESTAMP%', timestamp);
// Make sure that log directoy exsists when not logging to stdout only
if (output.includes('file')) {
fx.mkdirSync(directory);
}
// Determine the log level.
const level = settings.get().advanced.log_level;
const validLevels = ['info', 'error', 'warn', 'debug'];
assert(validLevels.includes(level), `'${level}' is not a valid log_level, use one of '${validLevels.join(', ')}'`);
// Directoy to log to
const timestamp = moment(Date.now()).format('YYYY-MM-DD.HH-mm-ss');
const directory = settings.get().advanced.log_directory.replace('%TIMESTAMP%', timestamp);
const levelWithCompensatedLength = {
'info': 'info ',
'error': 'error',
'warn': 'warn ',
'debug': 'debug',
};
// Make sure that log directoy exsists
fx.mkdirSync(directory);
/* istanbul ignore next */
const timestampFormat = () => moment().format(settings.get().advanced.timestamp_format);
// Create logger
const logger = new (winston.Logger)({
transports: [
new (winston.transports.File)({
filename: path.join(directory, 'log.txt'),
json: false,
level: level,
maxFiles: 3, // Keep last 3 files
maxsize: 10000000, // 10MB
timestamp: () => new Date().toLocaleString(),
// Setup default console logger
const transportsToUse = [
new winston.transports.Console({
level,
silent: !output.includes('console'),
format: winston.format.combine(
winston.format.timestamp({format: timestampFormat}),
winston.format.printf(/* istanbul ignore next */(info) => {
let {timestamp, level, message} = info;
level = level === 'warning' ? 'warn' : level;
const prefix = colorizer.colorize(level, `zigbee2mqtt:${levelWithCompensatedLength[level]}`);
return `${prefix} ${timestamp.split('.')[0]}: ${message}`;
}),
),
}),
];
// 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) => {
let {timestamp, level, message} = info;
level = level === 'warning' ? 'warn' : level;
return `${levelWithCompensatedLength[level]} ${timestamp.split('.')[0]}: ${message}`;
}),
new (winston.transports.Console)({
timestamp: () => new Date().toLocaleString(),
formatter: function(options) {
return winston.config.colorize(options.level, ' zigbee2mqtt:' + options.level.toLowerCase()) + ' ' +
options.timestamp() + ' ' + (options.message ? options.message : '') +
(options.meta && Object.keys(options.meta).length ? '\n\t'+ JSON.stringify(options.meta) : '' );
},
}),
],
});
),
};
logger.info(`Logging to directory: '${directory}'`);
logger.transports.console.level = level;
// Cleanup any old log directory.
if (settings.get().advanced.log_directory.includes('%TIMESTAMP%')) {
const rootDirectory = path.join(directory, '..');
let directories = fs.readdirSync(rootDirectory).map((d) => {
d = path.join(rootDirectory, d);
return {path: d, birth: fs.statSync(d).birthtimeMs};
});
directories.sort((a, b) => b.birth - a.birth);
directories = directories.slice(10, directories.length);
directories.forEach((dir) => {
logger.debug(`Removing old log directory '${dir.path}'`);
rimraf.sync(dir.path);
});
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(transportFileOptions));
}
/* istanbul ignore next */
if (output.includes('syslog')) {
require('winston-syslog').Syslog;
const options = {app_name: 'zigbee2mqtt', ...settings.get().advanced.log_syslog};
if (options.hasOwnProperty('type')) options.type = options.type.toString();
transportsToUse.push(new winston.transports.Syslog(options));
}
// Create logger
const logger = winston.createLogger({transports: transportsToUse, levels: winston.config.syslog.levels});
// Cleanup any old log directory.
function cleanup() {
if (settings.get().advanced.log_directory.includes('%TIMESTAMP%')) {
const rootDirectory = path.join(directory, '..');
let directories = fs.readdirSync(rootDirectory).map((d) => {
d = path.join(rootDirectory, d);
return {path: d, birth: fs.statSync(d).mtime};
});
directories.sort((a, b) => b.birth - a.birth);
directories = directories.slice(10, directories.length);
directories.forEach((dir) => {
logger.debug(`Removing old log directory '${dir.path}'`);
rimraf.sync(dir.path);
});
}
}
logger.cleanup = cleanup;
logger.getLevel = () => transportsToUse[0].level;
logger.setLevel = (level) => {
transportsToUse.forEach((transport) => transport.level = level);
};
// Print to user what logging is enabled
if (output.includes('file')) {
if (output.includes('console')) {
logger.info(`Logging to console and directory: '${directory}' filename: ${logFilename}`);
} else {
logger.info(`Logging to directory: '${directory}' filename: ${logFilename}`);
}
logger.cleanup();
} else if (output.includes('console')) {
logger.info(`Logging to console only'`);
}
// winston.config.syslog.levels doesnt have warn, but is required for syslog.
/* istanbul ignore next */
logger.warn = (message) => logger.warning(message);
module.exports = logger;
+696 -41
View File
@@ -1,78 +1,733 @@
const yaml = require('js-yaml');
const fs = require('fs');
const data = require('./data');
const file = data.joinPath('configuration.yaml');
const utils = require('./utils');
const file = process.env.ZIGBEE2MQTT_CONFIG || data.joinPath('configuration.yaml');
const objectAssignDeep = require(`object-assign-deep`);
const path = require('path');
const yaml = require('./yaml');
const Ajv = require('ajv');
const ajv = new Ajv({allErrors: true});
const defaults = {
passlist: [],
blocklist: [],
// Deprecated: use block/passlist
whitelist: [],
ban: [],
permit_join: false,
advanced: {
log_directory: path.join(data.getPath(), 'log', '%TIMESTAMP%'),
log_level: process.env.DEBUG ? 'debug' : 'info',
soft_reset_timeout: 0,
mqtt: {
include_device_information: false,
},
serial: {
disable_led: false,
},
device_options: {},
map_options: {
graphviz: {
colors: {
fill: {
enddevice: '#fff8ce',
coordinator: '#e04e5d',
router: '#4ea3e0',
},
font: {
coordinator: '#ffffff',
router: '#ffffff',
enddevice: '#000000',
},
line: {
active: '#009900',
inactive: '#994444',
},
},
},
},
experimental: {
// json or attribute or attribute_and_json
output: 'json',
new_api: false,
},
advanced: {
legacy_api: true,
log_rotation: true,
log_output: ['console', 'file'],
log_directory: path.join(data.getPath(), 'log', '%TIMESTAMP%'),
log_file: 'log.txt',
log_level: /* istanbul ignore next */ process.env.DEBUG ? 'debug' : 'info',
log_syslog: {},
soft_reset_timeout: 0,
pan_id: 0x1a62,
ext_pan_id: [0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD],
channel: 11,
adapter_concurrent: null,
// Availability timeout in seconds, disabled by default.
availability_timeout: 0,
availability_blocklist: [],
availability_passlist: [],
// Deprecated, use block/passlist
availability_blacklist: [],
availability_whitelist: [],
/**
* Home Assistant requires ALL attributes to be present in ALL MQTT messages send by the device.
* https://community.home-assistant.io/t/missing-value-with-mqtt-only-last-data-set-is-shown/47070/9
*
* Therefore zigbee2mqtt BY DEFAULT caches all values and resend it with every message.
* advanced.cache_state in configuration.yaml allows to configure this.
* https://www.zigbee2mqtt.io/configuration/configuration.html
*/
cache_state: true,
cache_state_persistent: true,
cache_state_send_on_startup: true,
/**
* Add a last_seen attribute to mqtt messages, contains date/time of zigbee message arrival
* "ISO_8601": ISO 8601 format
* "ISO_8601_local": Local ISO 8601 format (instead of UTC-based)
* "epoch": milliseconds elapsed since the UNIX epoch
* "disable": no last_seen attribute (default)
*/
last_seen: 'disable',
// Optional: Add an elapsed attribute to MQTT messages, contains milliseconds since the previous msg
elapsed: false,
/**
* https://github.com/Koenkk/zigbee2mqtt/issues/685#issuecomment-449112250
*
* Network key will serve as the encryption key of your network.
* Changing this will require you to repair your devices.
*/
network_key: [1, 3, 5, 7, 9, 11, 13, 15, 0, 2, 4, 6, 8, 10, 12, 13],
/**
* Enables reporting feature
*/
report: false,
/**
* Home Assistant discovery topic
*/
homeassistant_discovery_topic: 'homeassistant',
/**
* Home Assistant status topic
*/
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
*/
timestamp_format: 'YYYY-MM-DD HH:mm:ss',
},
external_converters: [],
};
let settings = read();
const schema = {
type: 'object',
properties: {
device_options: {type: 'object'},
homeassistant: {type: 'boolean'},
permit_join: {type: 'boolean'},
mqtt: {
type: 'object',
properties: {
base_topic: {type: 'string'},
server: {type: 'string'},
keepalive: {type: 'number'},
ca: {type: 'string'},
key: {type: 'string'},
cert: {type: 'string'},
user: {type: 'string'},
password: {type: 'string'},
client_id: {type: 'string'},
reject_unauthorized: {type: 'boolean'},
include_device_information: {type: 'boolean'},
version: {type: 'number'},
},
required: ['base_topic', 'server'],
},
serial: {
type: 'object',
properties: {
port: {type: ['string', 'null']},
disable_led: {type: 'boolean'},
adapter: {type: 'string', enum: ['deconz', 'zstack']},
},
},
blocklist: {type: 'array', items: {type: 'string'}},
passlist: {type: 'array', items: {type: 'string'}},
// Deprecated: use block/passlist
whitelist: {type: 'array', items: {type: 'string'}},
ban: {type: 'array', items: {type: 'string'}},
experimental: {
type: 'object',
properties: {
transmit_power: {type: 'number'},
output: {type: 'string', enum: ['attribute_and_json', 'attribute', 'json']},
},
},
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'},
cache_state_persistent: {type: 'boolean'},
cache_state_send_on_startup: {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'},
log_file: {type: 'string'},
baudrate: {type: 'number'},
rtscts: {type: 'boolean'},
soft_reset_timeout: {type: 'number', minimum: 0},
network_key: {type: ['array', 'string'], items: {type: 'number'}},
last_seen: {type: 'string', enum: ['disable', 'ISO_8601', 'ISO_8601_local', 'epoch']},
elapsed: {type: 'boolean'},
availability_timeout: {type: 'number', minimum: 0},
availability_blocklist: {type: 'array', items: {type: 'string'}},
availability_passlist: {type: 'array', items: {type: 'string'}},
// Deprecated, use block/passlist
availability_blacklist: {type: 'array', items: {type: 'string'}},
availability_whitelist: {type: 'array', items: {type: 'string'}},
report: {type: 'boolean'},
homeassistant_discovery_topic: {type: 'string'},
homeassistant_status_topic: {type: 'string'},
timestamp_format: {type: 'string'},
adapter_concurrent: {type: 'number'},
},
},
map_options: {
type: 'object',
properties: {
graphviz: {
type: 'object',
properties: {
colors: {
type: 'object',
properties: {
fill: {
type: 'object',
properties: {
enddevice: {type: 'string'},
coordinator: {type: 'string'},
router: {type: 'string'},
},
},
font: {
type: 'object',
properties: {
enddevice: {type: 'string'},
coordinator: {type: 'string'},
router: {type: 'string'},
},
},
line: {
type: 'object',
properties: {
active: {type: 'string'},
inactive: {type: 'string'},
},
},
},
},
},
},
},
},
devices: {
type: 'object',
propertyNames: {
pattern: '^0x[\\d\\w]{16}$',
},
patternProperties: {
'^.*$': {
type: 'object',
properties: {
friendly_name: {type: 'string'},
retain: {type: 'boolean'},
retention: {type: 'number'},
qos: {type: 'number'},
filtered_attributes: {type: 'array', items: {type: 'string'}},
},
required: ['friendly_name'],
},
},
},
groups: {
type: 'object',
propertyNames: {
pattern: '^[\\w].*$',
},
patternProperties: {
'^.*$': {
type: 'object',
properties: {
friendly_name: {type: 'string'},
retain: {type: 'boolean'},
devices: {type: 'array', items: {type: 'string'}},
optimistic: {type: 'boolean'},
qos: {type: 'number'},
filtered_attributes: {type: 'array', items: {type: 'string'}},
},
required: ['friendly_name'],
},
},
},
},
external_converters: {
type: 'array',
items: {type: 'string'},
},
required: ['homeassistant', 'permit_join', 'mqtt'],
};
function writeRead() {
write();
settings = read();
}
let _settings;
let _settingsWithDefaults;
function write() {
fs.writeFileSync(file, yaml.safeDump(settings));
const settings = get();
const toWrite = objectAssignDeep.noMutate(settings);
// Read settings to check if we have to split devices/groups into separate file.
const actual = yaml.read(file);
// In case the setting is defined in a separte file (e.g. !secret network_key) update it there.
for (const path of [['mqtt', 'user'], ['mqtt', 'password'], ['advanced', 'network_key']]) {
if (actual[path[0]] && actual[path[0]][path[1]]) {
const match = /!(.*) (.*)/g.exec(actual[path[0]][path[1]]);
if (match) {
yaml.updateIfChanged(data.joinPath(`${match[1]}.yaml`), match[2], toWrite[path[0]][path[1]]);
toWrite[path[0]][path[1]] = actual[path[0]][path[1]];
}
}
}
if (typeof actual.devices === 'string') {
yaml.writeIfChanged(data.joinPath(actual.devices), settings.devices);
toWrite.devices = actual.devices;
}
if (typeof actual.groups === 'string') {
yaml.writeIfChanged(data.joinPath(actual.groups), settings.groups);
toWrite.groups = actual.groups;
}
yaml.writeIfChanged(file, toWrite);
_settings = read();
_settingsWithDefaults = objectAssignDeep.noMutate(defaults, get());
}
function validate() {
const validate = ajv.compile(schema);
const valid = validate(_settings);
if (_settings.advanced && _settings.advanced.network_key && typeof _settings.advanced.network_key === 'string' &&
_settings.advanced.network_key !== 'GENERATE') {
throw new Error(`advanced.network_key: should be array or 'GENERATE' (is '${_settings.advanced.network_key}')`);
}
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);
};
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');
checkAvailabilityList(settingsWithDefaults.advanced.availability_blocklist, 'availability_blocklist');
checkAvailabilityList(settingsWithDefaults.advanced.availability_passlist, 'availability_passlist');
return !valid ? validate.errors.map((v) => `${v.dataPath.substring(1)} ${v.message}`) : null;
}
function read() {
return yaml.safeLoad(fs.readFileSync(file, 'utf8'));
const s = yaml.read(file);
// Read !secret MQTT username and password if set
const interpetValue = (value) => {
const re = /!(.*) (.*)/g;
const match = re.exec(value);
if (match) {
const file = data.joinPath(`${match[1]}.yaml`);
const key = match[2];
return yaml.read(file)[key];
} else {
return value;
}
};
if (s.mqtt && s.mqtt.user && s.mqtt.password) {
s.mqtt.user = interpetValue(s.mqtt.user);
s.mqtt.password = interpetValue(s.mqtt.password);
}
if (s.advanced && s.advanced.network_key) {
s.advanced.network_key = interpetValue(s.advanced.network_key);
}
// Read devices/groups configuration from separate file.
if (typeof s.devices === 'string') {
const file = data.joinPath(s.devices);
s.devices = yaml.readIfExists(file) || {};
}
if (typeof s.groups === 'string') {
const file = data.joinPath(s.groups);
s.groups = yaml.readIfExists(file) || {};
}
return s;
}
function addDevice(id) {
function get() {
if (!_settings) {
_settings = read();
}
return _settings;
}
function getWithDefaults() {
if (!_settingsWithDefaults) {
_settingsWithDefaults = objectAssignDeep.noMutate(defaults, get());
}
if (!_settingsWithDefaults.devices) {
_settingsWithDefaults.devices = {};
}
if (!_settingsWithDefaults.groups) {
_settingsWithDefaults.groups = {};
}
return _settingsWithDefaults;
}
function set(path, value) {
let settings = get();
for (let i = 0; i < path.length; i++) {
const key = path[i];
if (i === path.length - 1) {
settings[key] = value;
} else {
if (!settings[key]) {
settings[key] = {};
}
settings = settings[key];
}
}
write();
}
function getGroup(IDorName) {
const settings = getWithDefaults();
const byID = settings.groups[IDorName];
if (byID) {
return {optimistic: true, devices: [], ...byID, ID: Number(IDorName), friendlyName: byID.friendly_name};
}
for (const [ID, group] of Object.entries(settings.groups)) {
if (group.friendly_name === IDorName) {
return {optimistic: true, devices: [], ...group, ID: Number(ID), friendlyName: group.friendly_name};
}
}
return null;
}
function getGroups() {
const settings = getWithDefaults();
return Object.entries(settings.groups).map(([ID, group]) => {
return {optimistic: true, devices: [], ...group, ID: Number(ID), friendlyName: group.friendly_name};
});
}
function getGroupThrowIfNotExists(IDorName) {
const group = getGroup(IDorName);
if (!group) {
throw new Error(`Group '${IDorName}' does not exist`);
}
return group;
}
function getDevice(IDorName) {
const settings = getWithDefaults();
const byID = settings.devices[IDorName];
if (byID) {
return {...byID, ID: IDorName, friendlyName: byID.friendly_name};
}
for (const [ID, device] of Object.entries(settings.devices)) {
if (device.friendly_name === IDorName) {
return {...device, ID, friendlyName: device.friendly_name};
}
}
return null;
}
function getDeviceThrowIfNotExists(IDorName) {
const device = getDevice(IDorName);
if (!device) {
throw new Error(`Device '${IDorName}' does not exist`);
}
return device;
}
function getEntity(IDorName) {
const device = getDevice(IDorName);
if (device) {
return {...device, type: 'device'};
}
const group = getGroup(IDorName);
if (group) {
return {...group, type: 'group'};
}
return null;
}
function addDevice(ID) {
if (getDevice(ID)) {
throw new Error(`Device '${ID}' already exists`);
}
const settings = get();
if (!settings.devices) {
settings.devices = {};
}
settings.devices[id] = {friendly_name: id, retain: false};
writeRead();
settings.devices[ID] = {friendly_name: ID};
write();
return getDevice(ID);
}
function removeDevice(id) {
if (settings.devices && settings.devices[id]) {
delete settings.devices[id];
writeRead();
// Legacy: can be removed after bridgeLegacy has been removed
function whitelistDevice(ID) {
const settings = get();
if (!settings.whitelist) {
settings.whitelist = [];
}
if (settings.whitelist.includes(ID)) {
throw new Error(`Device '${ID}' already whitelisted`);
}
settings.whitelist.push(ID);
write();
}
function blockDevice(ID) {
const settings = get();
if (!settings.blocklist) {
settings.blocklist = [];
}
settings.blocklist.push(ID);
write();
}
function banDevice(ID) {
const settings = get();
if (!settings.ban) {
settings.ban = [];
}
settings.ban.push(ID);
write();
}
function removeDevice(IDorName) {
const device = getDeviceThrowIfNotExists(IDorName);
const settings = get();
delete settings.devices[device.ID];
write();
}
function addGroup(name, ID=null) {
if (getGroup(name) || getDevice(name)) {
throw new Error(`friendly_name '${name}' is already in use`);
}
const settings = get();
if (!settings.groups) {
settings.groups = {};
}
if (ID == null) {
// look for free ID
ID = '1';
while (settings.groups.hasOwnProperty(ID)) {
ID = (Number.parseInt(ID) + 1).toString();
}
} else {
// ensure provided ID is not in use
ID = ID.toString();
if (settings.groups.hasOwnProperty(ID)) {
throw new Error(`group id '${ID}' is already in use`);
}
}
settings.groups[ID] = {friendly_name: name};
write();
return getGroup(ID);
}
function groupHasDevice(group, keys) {
for (const device of group.devices) {
const index = keys.indexOf(device);
if (index != -1) {
return keys[index];
}
}
return false;
}
function addDeviceToGroup(groupIDorName, keys) {
const groupID = getGroupThrowIfNotExists(groupIDorName).ID;
const settings = get();
const group = settings.groups[groupID];
if (!group.devices) {
group.devices = [];
}
if (!groupHasDevice(group, keys)) {
group.devices.push(keys[0]);
write();
}
}
function getIDByFriendlyName(friendlyName) {
if (!settings.devices) {
return null;
function removeDeviceFromGroup(groupIDorName, keys) {
const groupID = getGroupThrowIfNotExists(groupIDorName).ID;
const settings = get();
const group = settings.groups[groupID];
if (!group.devices) {
group.devices = [];
}
return Object.keys(settings.devices).find((id) =>
settings.devices[id].friendly_name === friendlyName
);
const key = groupHasDevice(group, keys);
if (key) {
group.devices = group.devices.filter((d) => d != key);
write();
}
}
function changeFriendlyName(old, new_) {
const ID = getIDByFriendlyName(old);
function removeGroup(groupIDorName) {
const groupID = getGroupThrowIfNotExists(groupIDorName).ID;
const settings = get();
delete settings.groups[groupID];
write();
}
if (!ID) {
return false;
function changeEntityOptions(IDorName, newOptions) {
const settings = get();
delete newOptions.friendly_name;
delete newOptions.devices;
if (getDevice(IDorName)) {
objectAssignDeep(settings.devices[getDevice(IDorName).ID], newOptions);
} else if (getGroup(IDorName)) {
objectAssignDeep(settings.groups[getGroup(IDorName).ID], newOptions);
} else {
throw new Error(`Device or group '${IDorName}' does not exist`);
}
settings.devices[ID].friendly_name = new_;
writeRead();
return true;
write();
}
function changeFriendlyName(IDorName, newName) {
if (getGroup(newName) || getDevice(newName)) {
throw new Error(`friendly_name '${newName}' is already in use`);
}
const settings = get();
if (getDevice(IDorName)) {
settings.devices[getDevice(IDorName).ID].friendly_name = newName;
} else if (getGroup(IDorName)) {
settings.groups[getGroup(IDorName).ID].friendly_name = newName;
} else {
throw new Error(`Device or group '${IDorName}' does not exist`);
}
write();
}
module.exports = {
get: () => objectAssignDeep.noMutate(defaults, settings),
write: () => write(),
getDevice: (id) => settings.devices ? settings.devices[id] : null,
addDevice: (id) => addDevice(id),
removeDevice: (id) => removeDevice(id),
getIDByFriendlyName: (friendlyName) => getIDByFriendlyName(friendlyName),
changeFriendlyName: (old, new_) => changeFriendlyName(old, new_),
validate,
get: getWithDefaults,
set,
getDevice,
getGroup,
getGroups,
getEntity,
whitelistDevice,
banDevice,
blockDevice,
addDevice,
removeDevice,
addGroup,
removeGroup,
addDeviceToGroup,
removeDeviceFromGroup,
changeEntityOptions,
changeFriendlyName,
// For tests only
_write: write,
_reRead: () => {
_settings = read();
_settingsWithDefaults = objectAssignDeep.noMutate(defaults, get());
},
_getDefaults: () => defaults,
};
+201 -1
View File
@@ -1,8 +1,208 @@
const zigbeeHerdsmanConverters = require('zigbee-herdsman-converters');
const equals = require('fast-deep-equal/es6');
const humanizeDuration = require('humanize-duration');
const data = require('./data');
// Xiaomi uses 4151 and 4447 (lumi.plug) as manufacturer ID.
const xiaomiManufacturerID = [4151, 4447];
const ikeaTradfriManufacturerID = [4476];
// construct a local ISO8601 string (instead of UTC-based)
// Example:
// - ISO8601 (UTC) = 2019-03-01T15:32:45.941+0000
// - ISO8601 (local) = 2019-03-01T16:32:45.941+0100 (for timezone GMT+1)
function toLocalISOString(dDate) {
const tzOffset = -dDate.getTimezoneOffset();
const plusOrMinus = tzOffset >= 0 ? '+' : '-';
const pad = function(num) {
const norm = Math.floor(Math.abs(num));
return (norm < 10 ? '0' : '') + norm;
};
return dDate.getFullYear() +
'-' + pad(dDate.getMonth() + 1) +
'-' + pad(dDate.getDate()) +
'T' + pad(dDate.getHours()) +
':' + pad(dDate.getMinutes()) +
':' + pad(dDate.getSeconds()) +
plusOrMinus + pad(tzOffset / 60) +
':' + pad(tzOffset % 60);
}
const endpointNames = [
'left', 'right', 'center', 'bottom_left', 'bottom_right', 'default',
'top_left', 'top_right', 'white', 'rgb', 'cct', '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',
'button_1', 'button_2', 'button_3', 'button_4', 'button_5',
'button_6', 'button_7', 'button_8', 'button_9', 'button_10',
'button_11', 'button_12', 'button_13', 'button_14', 'button_15',
'button_16', 'button_17', 'button_18', 'button_19', 'button_20',
];
function flatten(arr) {
return arr.reduce((flat, toFlatten) => {
return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
}, []);
}
function capitalize(s) {
return s[0].toUpperCase() + s.slice(1);
}
const forceEndDevice = flatten(
['QBKG03LM', 'QBKG04LM', 'ZNMS13LM', 'ZNMS12LM']
.map((model) => zigbeeHerdsmanConverters.devices.find((d) => d.model === model))
.filter((definition) => definition.hasOwnProperty('zigbeeModel'))
.map((definition) => definition.zigbeeModel));
async function getZigbee2mqttVersion() {
return new Promise((resolve, reject) => {
const git = require('git-last-commit');
const packageJSON = require('../../package.json');
const version = packageJSON.version;
git.getLastCommit((err, commit) => {
let commitHash = null;
if (err) {
try {
commitHash = require('../../.hash.json').hash;
} catch (error) {
commitHash = 'unknown';
}
} else {
commitHash = commit.shortHash;
}
resolve({commitHash, version});
});
});
}
function formatDate(date, type) {
let result;
switch (type) {
case 'ISO_8601':
result = new Date(date).toISOString();
break;
case 'ISO_8601_local':
result = toLocalISOString(new Date(date));
break;
case 'epoch':
result = date;
break;
case 'relative':
// https://github.com/EvanHahn/HumanizeDuration.js#options
result = humanizeDuration(Date.now() - date, {language: 'en', largest: 2, round: true}) + ' ago';
break;
default:
throw new Error(`Unsupported type '${type}'`);
}
return result;
}
function objectHasProperties(object, properties) {
for (const property of properties) {
if (!object.hasOwnProperty(property)) {
return false;
}
}
return true;
}
function equalsPartial(object, expected) {
for (const [key, value] of Object.entries(expected)) {
if (!equals(object[key], value)) {
return false;
}
}
return true;
}
function getObjectsProperty(objects, key, defaultValue) {
for (const object of objects) {
if (object.hasOwnProperty(key)) {
return object[key];
}
}
return defaultValue;
}
function getResponse(request, data, error) {
const response = {data, status: error ? 'error' : 'ok'};
if (error) response.error = error;
if (typeof request === 'object' && request.hasOwnProperty('transaction')) {
response.transaction = request.transaction;
}
return response;
}
function parseJSON(value, failedReturnValue) {
try {
return JSON.parse(value);
} catch (e) {
return failedReturnValue;
}
}
function* getExternalConvertersDefinitions(settings) {
const externalConverters = settings.get().external_converters;
for (const moduleName of externalConverters) {
let converterModule = moduleName;
if (moduleName.endsWith('.js')) {
converterModule = data.joinPath(moduleName.split('.')[0]);
}
const converter = require(converterModule);
if (Array.isArray(converter)) {
for (const item of converter) {
yield item;
}
} else {
yield converter;
}
}
}
function toSnakeCase(value) {
if (typeof value === 'object') {
for (const key of Object.keys(value)) {
value[toSnakeCase(key)] = value[key];
delete value[key];
}
return value;
} else {
return value.replace(/\.?([A-Z])/g, (x, y) => '_' + y.toLowerCase()).replace(/^_/, '').replace('_i_d', '_id');
}
}
module.exports = {
millisecondsToSeconds: (milliseconds) => milliseconds / 1000,
secondsToMilliseconds: (seconds) => seconds * 1000,
isXiaomiDevice: (device) => xiaomiManufacturerID.includes(device.manufId),
getZigbee2mqttVersion,
objectHasProperties,
toSnakeCase,
getObjectsProperty,
getEndpointNames: () => endpointNames,
isXiaomiDevice: (device) => {
return device.modelID !== 'lumi.router' && xiaomiManufacturerID.includes(device.manufacturerID) &&
(!device.manufacturerName || !device.manufacturerName.startsWith('Trust'));
},
isIkeaTradfriDevice: (device) => ikeaTradfriManufacturerID.includes(device.manufacturerID),
isRouter: (device) => device.type === 'Router' && !forceEndDevice.includes(device.modelID),
isBatteryPowered: (device) => device.powerSource && device.powerSource === 'Battery',
formatDate: (date, type) => formatDate(date, type),
equalsPartial,
getResponse,
capitalize,
parseJSON,
getExternalConvertersDefinitions,
};
+44
View File
@@ -0,0 +1,44 @@
const yaml = require('js-yaml');
const fs = require('fs');
const equals = require('fast-deep-equal/es6');
function read(file) {
try {
return yaml.safeLoad(fs.readFileSync(file, 'utf8'));
} catch (error) {
if (error.name === 'YAMLException') {
error.message =
`\n\n\n` +
`\t====================================================================\n` +
`\tYour YAML file '${file}' is invalid\n` +
`\tUse e.g. https://jsonformatter.org/yaml-validator to find and fix the issue.\n` +
`\t====================================================================\n` +
`\n\n` +
error.message;
}
throw error;
}
}
function readIfExists(file) {
return fs.existsSync(file) ? read(file) : null;
}
function writeIfChanged(file, content) {
const before = readIfExists(file);
if (!equals(before, content)) {
fs.writeFileSync(file, yaml.safeDump(content));
}
}
function updateIfChanged(file, key, value) {
const content = read(file);
if (content[key] !== value) {
content[key] = value;
writeIfChanged(file, content);
}
}
module.exports = {read, readIfExists, writeIfChanged, updateIfChanged};
+231 -215
View File
@@ -1,267 +1,283 @@
const ZShepherd = require('zigbee-shepherd');
const ZigbeeHerdsman = require('zigbee-herdsman');
const logger = require('./util/logger');
const settings = require('./util/settings');
const data = require('./util/data');
const zclPacket = require('zcl-packet');
const assert = require('assert');
const utils = require('./util/utils');
const events = require('events');
const objectAssignDeep = require('object-assign-deep');
const zigbeeHerdsmanConverters = require('zigbee-herdsman-converters');
const advancedSettings = settings.get().advanced;
const endpointNames = utils.getEndpointNames();
const keyEndpointByNumber = new RegExp(`.*/([0-9]*)$`);
const shepherdSettings = {
net: {
panId: advancedSettings && advancedSettings.pan_id ? advancedSettings.pan_id : 0x1a62,
channelList: [advancedSettings && advancedSettings.channel ? advancedSettings.channel : 11],
},
dbPath: data.joinPath('database.db'),
sp: {
baudRate: advancedSettings && advancedSettings.baudrate ? advancedSettings.baudrate : 115200,
rtscts: advancedSettings && (typeof(advancedSettings.rtscts) === 'boolean') ? advancedSettings.rtscts : true,
},
};
logger.debug(`Using zigbee-shepherd with settings: '${JSON.stringify(shepherdSettings)}'`);
class Zigbee {
constructor(onMessage) {
this.onMessage = onMessage;
this.handleReady = this.handleReady.bind(this);
this.handleMessage = this.handleMessage.bind(this);
this.handleError = this.handleError.bind(this);
class Zigbee extends events.EventEmitter {
constructor() {
super();
this.acceptJoiningDeviceHandler = this.acceptJoiningDeviceHandler.bind(this);
}
start(callback) {
logger.info(`Starting zigbee-shepherd`);
async start() {
logger.info(`Starting zigbee-herdsman...`);
const herdsmanSettings = {
network: {
panID: settings.get().advanced.pan_id,
extendedPanID: settings.get().advanced.ext_pan_id,
channelList: [settings.get().advanced.channel],
networkKey: settings.get().advanced.network_key,
},
databasePath: data.joinPath('database.db'),
databaseBackupPath: data.joinPath('database.db.backup'),
backupPath: data.joinPath('coordinator_backup.json'),
serialPort: {
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,
},
};
this.shepherd = new ZShepherd(settings.get().serial.port, shepherdSettings);
const herdsmanSettingsLog = objectAssignDeep.noMutate(herdsmanSettings);
herdsmanSettingsLog.network.networkKey = 'HIDDEN';
logger.debug(`Using zigbee-herdsman with settings: '${JSON.stringify(herdsmanSettingsLog)}'`);
this.shepherd.start((error) => {
if (error) {
logger.info('Error while starting zigbee-shepherd, attemping to fix... (takes 60 seconds)');
this.shepherd.controller._znp.close((() => null));
if (herdsmanSettings.network.networkKey === 'GENERATE') {
const newKey = Array.from({length: 16}, () => Math.floor(Math.random() * 255));
settings.set(['advanced', 'network_key'], newKey);
herdsmanSettings.network.networkKey = newKey;
}
setTimeout(() => {
logger.info(`Starting zigbee-shepherd`);
this.shepherd.start((error) => {
if (error) {
logger.error('Error while starting zigbee-shepherd!');
logger.error(
'Press the reset button on the stick (the one closest to the USB) and start again'
);
callback(error);
} else {
this._logStartupInfo();
callback(null);
}
});
}, 60 * 1000);
} else {
this._logStartupInfo();
callback(null);
}
});
try {
herdsmanSettings.acceptJoiningDeviceHandler = this.acceptJoiningDeviceHandler;
this.herdsman = new ZigbeeHerdsman.Controller(herdsmanSettings);
await this.herdsman.start();
} catch (error) {
logger.error(`Error while starting zigbee-herdsman`);
throw error;
}
// Register callbacks.
this.shepherd.on('ready', this.handleReady);
this.shepherd.on('ind', this.handleMessage);
this.shepherd.on('error', this.handleError);
}
this.herdsman.on('adapterDisconnected', () => this.emit('adapterDisconnected'));
this.herdsman.on('deviceAnnounce', (data) => this.emit('event', 'deviceAnnounce', data));
this.herdsman.on('deviceInterview', (data) => this.emit('event', 'deviceInterview', data));
this.herdsman.on('deviceJoined', (data) => this.emit('event', 'deviceJoined', data));
this.herdsman.on('deviceLeave', (data) => this.emit('event', 'deviceLeave', data));
this.herdsman.on('message', (data) => this.emit('event', 'message', data));
_logStartupInfo() {
logger.info('zigbee-shepherd started');
logger.info(`Coordinator firmware version: '${this.shepherd.info().firmware.revision}'`);
logger.debug(`zigbee-shepherd info: ${JSON.stringify(this.shepherd.info())}`);
}
logger.info('zigbee-herdsman started');
logger.info(`Coordinator firmware version: '${JSON.stringify(await this.getCoordinatorVersion())}'`);
logger.debug(`Zigbee network parameters: ${JSON.stringify(await this.herdsman.getNetworkParameters())}`);
softReset(callback) {
this.shepherd.reset('soft', callback);
}
stop(callback) {
this.shepherd.stop((error) => {
logger.info('zigbee-shepherd stopped');
callback(error);
});
}
handleReady() {
// Set all Xiaomi devices to be online, so shepherd won't try
// to query info from devices (which would fail because they go to sleep).
const devices = this.getAllClients();
devices.forEach((d) => {
if (utils.isXiaomiDevice(d)) {
const device = this.shepherd.find(d.ieeeAddr, 1);
if (device) {
device.getDevice().update({
status: 'online',
joinTime: Math.floor(Date.now() / 1000),
});
for (const device of this.getClients()) {
// If a passlist is used, all other device will be removed from the network.
const passlist = settings.get().passlist.concat(settings.get().whitelist);
const blocklist = settings.get().blocklist.concat(settings.get().ban);
if (passlist.length > 0) {
if (!passlist.includes(device.ieeeAddr)) {
logger.warn(`Device which is not on passlist connected (${device.ieeeAddr}), removing...`);
device.removeFromNetwork();
}
} else if (blocklist.includes(device.ieeeAddr)) {
logger.warn(`Device on blocklist is connected (${device.ieeeAddr}), removing...`);
device.removeFromNetwork();
}
});
}
// Check if we have to turn off the led
if (settings.get().serial.disable_led) {
this.shepherd.controller.request('UTIL', 'ledControl', {ledid: 3, mode: 0});
await this.herdsman.setLED(false);
}
logger.info('zigbee-shepherd ready');
// Check if we have to set a transmit power
if (settings.get().experimental.hasOwnProperty('transmit_power')) {
const transmitPower = settings.get().experimental.transmit_power;
await this.herdsman.setTransmitPower(transmitPower);
logger.info(`Set transmit power to '${transmitPower}'`);
}
}
handleError(message) {
// This event may appear if zigbee-shepherd cannot decode bad packets (invalid checksum).
logger.error(message);
async getCoordinatorVersion() {
return this.herdsman.getCoordinatorVersion();
}
permitJoin(permit) {
if (permit) {
logger.info('Zigbee: allowing new devices to join.');
} else {
async reset(type) {
await this.herdsman.reset(type);
}
async stop() {
await this.herdsman.stop();
logger.info('zigbee-herdsman stopped');
}
async permitJoin(permit) {
permit ?
logger.info('Zigbee: allowing new devices to join.') :
logger.info('Zigbee: disabling joining new devices.');
}
this.shepherd.permitJoin(permit ? 255 : 0, (error) => {
if (error) {
logger.info(error);
}
});
await this.herdsman.permitJoin(permit);
}
getAllClients() {
return this.getDevices().filter((device) => device.type !== 'Coordinator');
async getPermitJoin() {
return this.herdsman.getPermitJoin();
}
removeDevice(deviceID, callback) {
this.shepherd.remove(deviceID, (error) => {
if (error) {
logger.warn(`Failed to remove '${deviceID}', trying force remove...`);
this._forceRemove(deviceID, callback);
} else {
callback(null);
}
});
}
_forceRemove(deviceID, callback) {
const device = this.shepherd._findDevByAddr(deviceID);
if (device) {
return this.shepherd._unregisterDev(device, (error) => callback(error));
} else {
logger.warn(`Could not find ${deviceID} for force removal`);
callback(true);
}
}
ping(deviceID) {
let friendlyName = 'unknown';
const device = this.shepherd._findDevByAddr(deviceID);
const ieeeAddr = device.ieeeAddr;
if (settings.getDevice(ieeeAddr)) {
friendlyName = settings.getDevice(ieeeAddr).friendly_name;
}
if (device) {
// Note: checkOnline has the callback argument but does not call callback
logger.debug(`Check online ${friendlyName} ${deviceID}`);
this.shepherd.controller.checkOnline(device);
}
}
handleMessage(message) {
if (this.onMessage) {
this.onMessage(message);
}
getClients() {
return this.herdsman.getDevices().filter((device) => device.type !== 'Coordinator');
}
getDevices() {
return this.shepherd.list();
return this.herdsman.getDevices();
}
getDevice(deviceID) {
return this.getDevices().find((d) => d.ieeeAddr === deviceID);
getDeviceByIeeeAddr(ieeeAddr) {
return this.herdsman.getDeviceByIeeeAddr(ieeeAddr);
}
getCoordinator() {
const device = this.getDevices().find((d) => d.type === 'Coordinator');
return this.shepherd.find(device.ieeeAddr, 1);
getDevicesByType(type) {
return this.herdsman.getDevicesByType(type);
}
publish(deviceID, cid, cmd, zclData, cfg, ep, type, callback) {
const device = this._findDevice(deviceID, ep);
if (!device) {
logger.error(`Zigbee cannot publish message to device because '${deviceID}' not known by zigbee-shepherd`);
return;
}
logger.info(
`Zigbee publish to '${deviceID}', ${cid} - ${cmd} - ` +
`${JSON.stringify(zclData)} - ${JSON.stringify(cfg)} - ${ep}`
/**
* @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' ||
key.constructor.name === 'Device' || key.constructor.name === 'Group',
`Wrong type '${typeof key}'`,
);
const callback_ = (error) => {
if (error) {
logger.error(
`Zigbee publish to '${deviceID}', ${cid} - ${cmd} - ${JSON.stringify(zclData)} ` +
`- ${JSON.stringify(cfg)} - ${ep} ` +
`failed with error ${error}`);
if (typeof key === 'string' || typeof key === 'number') {
if (typeof key === 'number') {
key = key.toString();
}
callback(error);
};
if (type === 'functional') {
device.functional(cid, cmd, zclData, cfg, callback_);
} else if (type === 'foundation') {
device.foundation(cid, cmd, [zclData], cfg, callback_);
} else {
logger.error(`Unknown zigbee publish type ${type}`);
}
}
read(deviceID, cid, attr, ep, callback) {
const device = this._findDevice(deviceID, ep);
if (!device) {
logger.error(`Zigbee cannot read attribute from device because '${deviceID}' not known by zigbee-shepherd`);
return;
}
device.read(cid, attr, callback);
}
networkScan(callback) {
logger.info('Starting network scan...');
this.shepherd.lqiScan().then((result) => {
logger.info('Network scan completed');
callback(result);
});
}
registerOnAfIncomingMsg(ieeeAddr, ep) {
const device = this._findDevice(ieeeAddr, ep);
device.onAfIncomingMsg = (message) => {
// Parse the message
zclPacket.parse(message.data, message.clusterid, (error, zclData) => {
const message = {
endpoints: [device],
data: zclData,
if (typeof key === 'string' && key.toLowerCase() === 'coordinator') {
const coordinator = this.getDevicesByType('Coordinator')[0];
return {
type: 'device',
device: coordinator,
endpoint: coordinator.getEndpoint(1),
settings: {friendlyName: 'Coordinator'},
name: 'Coordinator',
};
}
this.handleMessage(message);
});
};
let endpointKey = endpointNames.find((p) => key.endsWith(`/${p}`));
const endpointByNumber = key.match(keyEndpointByNumber);
if (!endpointKey && endpointByNumber) {
endpointKey = Number(endpointByNumber[1]);
}
if (endpointKey) {
key = key.replace(`/${endpointKey}`, '');
}
const entity = settings.getEntity(key);
if (!entity) {
return null;
} else if (entity.type === 'device') {
const device = this.getDeviceByIeeeAddr(entity.ID);
if (!device) {
return null;
}
const definition = zigbeeHerdsmanConverters.findByDevice(device);
const endpoints = definition && definition.endpoint ? definition.endpoint(device) : null;
let endpoint;
if (endpointKey) {
if (endpointByNumber) {
endpoint = device.getEndpoint(endpointKey);
} else {
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']) {
endpoint = device.getEndpoint(endpoints['default']);
} else {
endpoint = device.endpoints[0];
}
return {
type: 'device', device, endpoint, settings: entity, name: entity.friendlyName, definition,
};
} else {
let group = this.getGroupByID(entity.ID);
if (!group) group = this.createGroup(entity.ID);
return {type: 'group', group, settings: entity, name: entity.friendlyName};
}
} else if (key.constructor.name === 'Device') {
const setting = settings.getEntity(key.ieeeAddr);
return {
type: 'device',
device: key,
endpoint: key.endpoints[0],
settings: setting,
name: setting ? setting.friendlyName : (key.type === 'Coordinator' ? 'Coordinator' : key.ieeeAddr),
definition: zigbeeHerdsmanConverters.findByDevice(key),
};
} else { // Group
const setting = settings.getEntity(key.groupID);
return {
type: 'group',
group: key,
settings: setting,
name: setting ? setting.friendlyName : key.groupID,
};
}
}
_findDevice(deviceID, ep) {
// Find device in zigbee-shepherd
let device = this.getDevice(deviceID);
if (!device || !device.epList || !device.epList.length) {
logger.error(`Zigbee cannot determine endpoint for '${deviceID}'`);
return null;
}
getGroupByID(ID) {
return this.herdsman.getGroupByID(ID);
}
ep = ep ? ep : device.epList[0];
device = this.shepherd.find(deviceID, ep);
return device;
getGroups() {
return this.herdsman.getGroups();
}
createGroup(groupID) {
return this.herdsman.createGroup(groupID);
}
acceptJoiningDeviceHandler(ieeeAddr) {
// If passlist is set, all devices not on passlist will be rejected to join the network
const passlist = settings.get().passlist.concat(settings.get().whitelist);
const blocklist = settings.get().blocklist.concat(settings.get().ban);
if (passlist.length > 0) {
if (passlist.includes(ieeeAddr)) {
logger.info(`Accepting joining device which is on passlist '${ieeeAddr}'`);
return true;
} else {
logger.info(`Rejecting joining not in passlist device '${ieeeAddr}'`);
return false;
}
} else if (blocklist.length > 0) {
if (blocklist.includes(ieeeAddr)) {
logger.info(`Rejecting joining device which is on blocklist '${ieeeAddr}'`);
return false;
} else {
logger.info(`Accepting joining not in blocklist device '${ieeeAddr}'`);
return true;
}
} else {
return true;
}
}
async touchlinkFactoryReset() {
return this.herdsman.touchlinkFactoryReset();
}
}
+18035 -4243
View File
File diff suppressed because it is too large Load Diff
+42 -26
View File
@@ -1,12 +1,15 @@
{
"name": "zigbee2mqtt",
"version": "0.1.7",
"description": "Zigbee to MQTT bridge using zigbee-shepherd",
"version": "1.14.2",
"description": "Zigbee to MQTT bridge using Zigbee-herdsman",
"main": "index.js",
"repository": {
"type": "git",
"url": "git+https://github.com/Koenkk/zigbee2mqtt.git"
},
"engines": {
"node": "^10 || ^12 || ^13 || ^14"
},
"keywords": [
"xiaomi",
"tradfri",
@@ -17,41 +20,54 @@
"cc2531"
],
"scripts": {
"coverage": "nyc --all report --reporter=text mocha --recursive --timeout=3000",
"docgen": "node support/docgen.js",
"eslint": "node_modules/.bin/eslint .",
"test-with-coverage": "jest test --coverage",
"eslint": "node_modules/.bin/eslint lib/",
"start": "node index.js",
"test": "mocha --recursive",
"verify-homeassistant-mapping": "node support/verify-homeassistant-mapping.js"
"test": "jest test",
"test-watch": "jest test --watch"
},
"author": "Koen Kanters",
"license": "GPL-3.0",
"bugs": {
"url": "https://github.com/Koenkk/zigbee2mqtt/issues"
},
"homepage": "https://github.com/Koenkk/zigbee2mqtt/wiki",
"homepage": "https://koenkk.github.io/zigbee2mqtt",
"dependencies": {
"git-last-commit": "*",
"js-yaml": "*",
"json2yaml": "*",
"mkdir-recursive": "*",
"moment": "*",
"mqtt": "*",
"object-assign-deep": "*",
"rimraf": "*",
"winston": "2.4.2",
"zcl-packet": "git+https://github.com/Koenkk/zcl-packet.git#fbd8c936bbd4be0597ad3e934be0ca722b0128a6",
"zigbee-shepherd": "git+https://github.com/Koenkk/zigbee-shepherd.git#c3fdef2c30267573aa5821a0f2c51f21a700eff2",
"zigbee-shepherd-converters": "4.0.3"
"ajv": "^6.12.3",
"debounce": "^1.2.0",
"fast-deep-equal": "^3.1.3",
"git-last-commit": "^1.0.0",
"humanize-duration": "^3.23.1",
"js-yaml": "^3.14.0",
"mkdir-recursive": "^0.4.0",
"moment": "^2.27.0",
"mqtt": "^4.1.0",
"object-assign-deep": "^0.4.0",
"rimraf": "^3.0.2",
"semver": "^7.3.2",
"winston": "^3.3.3",
"winston-syslog": "^2.4.4",
"zigbee-herdsman": "0.12.108",
"zigbee-herdsman-converters": "12.0.147"
},
"devDependencies": {
"chai": "*",
"chai-spies": "*",
"eslint": "*",
"eslint-config-google": "*",
"eslint-plugin-mocha": "*",
"mocha": "*",
"nyc": "*",
"proxyquire": "*"
"eslint-plugin-jest": "*",
"jest": "*",
"tmp": "*"
},
"jest": {
"coverageThreshold": {
"global": {
"branches": 100,
"functions": 100,
"lines": 100,
"statements": 100
}
},
"collectCoverageFrom": [
"lib/**"
]
}
}
+10
View File
@@ -0,0 +1,10 @@
const fs = require('fs');
const filename = process.argv[2];
const text = fs.readFileSync(filename, 'utf8');
const zigbeeHerdsmanConverters = require('zigbee-herdsman-converters');
for (const line of text.split('\n')) {
const model = zigbeeHerdsmanConverters.devices.find((d) => d.model === line);
console.log(`- \`${line}\` ${model.vendor} ${model.description}`);
}
+73
View File
@@ -0,0 +1,73 @@
#!/bin/bash
function zigbee2mqtt-show-short-info {
echo "Setup for Zigbee2mqtt bridge."
}
function zigbee2mqtt-show-long-info {
echo "This script installs the Zigbee2mqtt bridge"
}
function zigbee2mqtt-show-copyright-info {
echo "Original concept by Landrash <https://github.com/landrash>."
}
function zigbee2mqtt-install-package {
echo -n "Installing dependencies : "
node=$(which npm)
if [ -z "${node}" ]; then #Installing NodeJS if not already installed.
printf "Downloading and installing NodeJS...\\n"
curl -sL https://deb.nodesource.com/setup_10.x | bash -
apt install -y nodejs
fi
echo "Cloning Zigbee2mqtt git repository"
git clone https://github.com/Koenkk/zigbee2mqtt.git /opt/zigbee2mqtt
chown -R pi:pi /opt/zigbee2mqtt
echo "Running install. This might take a while and can produce som expected errors"
cd /opt/zigbee2mqtt || exit
su pi -c "npm ci"
echo "Creating service file zigbee2mqtt.service"
service_path="/etc/systemd/system/zigbee2mqtt.service"
echo "[Unit]
Description=zigbee2mqtt
After=network.target
[Service]
ExecStart=/usr/bin/npm start
WorkingDirectory=/opt/zigbee2mqtt
StandardOutput=inherit
StandardError=inherit
Restart=always
User=pi
[Install]
WantedBy=multi-user.target" > $service_path
echo "Checking the installation..."
if [ ! -f /opt/zigbee2mqtt/data/configuration.yaml ]; then
validation=""
else
validation="ok"
fi
if [ ! -z "${validation}" ]; then
echo
echo -e "\\e[32mInstallation done..\\e[0m"
echo -e "Update of configuration.yaml is required found at /opt/zigbee2mqtt/data/"
echo -e "Some further configuration is required and details can be found here https://www.zigbee2mqtt.io"
echo
echo -e "Service can be started after configuration but running sudo systemctl start zigbee2mqtt"
echo
else
echo
echo -e "\\e[31mInstallation failed..."
echo
return 1
fi
return 0
}
[[ "$_" == "$0" ]] && zigbee2mqtt-install-package
+181
View File
@@ -0,0 +1,181 @@
#!/bin/bash
######################################
## INITIALIZE ##
######################################
set -o errexit -o pipefail -o noclobber -o nounset
! getopt --test > /dev/null
if [[ ${PIPESTATUS[0]} -ne 4 ]]; then
echo "Unfortunately getopt failed in this environment."
exit 2
fi
PROGRAM_NAME="zigbee2socat_installer"
VERSION="1.0"
######################################
## PARSE ARGUMENTS ##
######################################
OPTS="a:p:uvmhV"
LONG="addr:,port:,uninstall,verbose,man,help,version"
# Concern: possible to escape getopt and execute commands as root?
! PARSED=$(getopt -n $PROGRAM_NAME \
-o $OPTS \
-l $LONG \
-- "$@")
if [[ ${PIPESTATUS[0]} -ne 0 ]]; then
printf "Error parsing arguments. Try %s --help\n" "$PROGRAM_NAME"
exit 3
fi
eval set -- "$PARSED" # Use remaining arguments that weren't parsed
function handle_opts {
if [[ $# = 1 ]]; then
usage
fi
while true; do
case $1 in
-a|--addr)
ip=$2; shift 2; continue ;;
-p|--port)
port=$2; shift 2; continue ;;
-u|--uninstall)
uninstall ;;
-v|--verbose)
verbose=1; shift; continue ;;
-m|--man)
makemanual ;;
-h|--help)
usage ;;
-V|--version)
version ;;
--) # No more arguments to parse
shift; break ;;
*)
printf "Programming error! Option: %s\n" "$1"
exit 4 ;;
esac;done
}
######################################
## START OF MAIN ##
######################################
verbose=0
ip=""
port=""
function main {
handle_opts "$@"
# TODO: Check IP-address valid?
if [[ "$ip" = "" ]]; then
echo "IP-address not specified"
exit 5
fi
# Is the port valid?
if [[ $port -lt 1 || $port -gt 65535 ]]; then
printf "Port %s, is outside range: [1-65535]\n" "$port"
exit 6
fi
zigbee-socatvusb-install-package
}
######################################
## FUNCTIONS BELOW ##
######################################
function zigbee-socatvusb-install-package {
echo "Installing socat:"
sudo apt-get install socat
echo
echo "Make dir for zigbee vusb"
sudo mkdir -p /opt/zigbee2mqtt/vusb/ || die "Couldn't mkdir /opt/zigbee2mqtt/vusb/"
sudo chown -R pi:pi /opt/zigbee2mqtt/vusb/ || die "Couldn't chown /opt/zigbee2mqtt/vusb/"
echo "Creating service file zigbee-socatvusb.service"
service_path="/etc/systemd/system/zigbee-socatvusb.service"
[[ -f $service_path ]] && sudo rm $service_path
echo "[Unit]
Description=socat-vusb
After=network-online.target
[Service]
User=pi
ExecStart=/usr/bin/socat -d -d pty,raw,echo=0,link=/opt/zigbee2mqtt/vusb/zigbee_cc2530 tcp:$ip:$port,reuseaddr
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target" > $service_path || die "Couldn't create service /etc/systemd/system/zigbee-socatvusb.service"
sudo systemctl --system daemon-reload
echo "Installation is now complete"
echo
echo "Service can be started after configuration by running: sudo systemctl start zigbee-socatvusb"
}
function uninstall {
service_path="systemctl status socat-vusb.service"
[[ -f $service_path ]] && sudo rm $service_path
sudo systemctl --system daemon-reload
echo "Uninstalled successfully"
exit 0
}
function makemanual {
[[ -f "$PROGRAM_NAME.man" ]] && sudo rm $PROGRAM_NAME.man
help2man -N ./$PROGRAM_NAME.sh > $PROGRAM_NAME.man ; man ./$PROGRAM_NAME.man
exit 0
}
function usage {
echo -e "\
\rSetup for development version of Zigbee2Socat
-a, --addr IP Listen on this IP-address
-p, --port PORT Listen on this port
-u, --uninstall Uninstall zigbee-socatvusb.service
-v, --verbose Print more information
-m, --man Make and display manual
-h, --help Display this help message
\rOriginal concept by JFLN\
"
exit 0
}
function version {
echo "$PROGRAM_NAME $VERSION"
exit 0
}
function die {
printf "%s\n" "$1"
exit 1
}
main "$@" # Call main-function last
-127
View File
@@ -1,127 +0,0 @@
/**
* This script generates the supported devices page.
* Run by executing: npm run docs
*/
const deviceMapping = require('zigbee-shepherd-converters').devices;
const fs = require('fs');
const YAML = require('json2yaml');
const homeassistant = require('../lib/homeassistant');
const outputdir = process.argv[2];
if (!outputdir) {
console.error("Please specify an output directory");
}
let file = 'Supported-devices.md';
let text = '*NOTE: Automatically generated by `npm run docgen`*\n';
text += `
In case you own a Zigbee device which is **NOT** listed here, please see [How to support new devices](https://github.com/Koenkk/zigbee2mqtt/wiki/How-to-support-new-devices).
\n`;
const logDevices = (devices) => {
let result = '';
result += '| Model | Description | Picture |\n';
result += '| ------------- | ------------- | -------------------------- |\n';
devices = new Map(devices.map((d) => [d.model, d]));
devices.forEach((device) => {
const pathFriendly = device.model.replace(new RegExp("/", "g"), '-').replace(new RegExp(":", "g"), '-').replace(new RegExp(" ", "g"), '-');
result += `| ${device.model} | ${device.vendor} ${device.description} (${device.supports}) | ![${pathFriendly}](images/devices/${pathFriendly}.jpg) |\n`;
});
return result;
}
const vendors = Array.from(new Set(deviceMapping.map((d) => d.vendor)));
vendors.sort();
vendors.forEach((vendor) => {
text += `### ${vendor}\n`;
text += logDevices(deviceMapping.filter((d) => d.vendor === vendor));
text += '\n';
})
fs.writeFileSync(outputdir + '/' + file, text);
file = 'Integrating-with-Home-Assistant.md';
text = '*NOTE: Automatically generated by `npm run docgen`*\n\n';
text += 'If you\'re hosting zigbee2mqtt using [this hassio addon-on](https://github.com/danielwelch/hassio-zigbee2mqtt) use their documentation on how to configure.\n\n'
text += 'The easiest way to integrate zigbee2mqtt with Home Assistant is by using [MQTT discovery](https://www.home-assistant.io/docs/mqtt/discovery/).\n\n'
text += 'To achieve the best possible integration (including MQTT discovery):\n';
text += '- In your **zigbee2mqtt** `configuration.yaml` set `homeassistant: true`\n'
text += '- In your **Home Assistant** `configuration.yaml`:\n';
text += '```yaml\n';
text += 'mqtt:\n';
text += ' discovery: true\n';
text += ' broker: [YOUR MQTT BROKER] # Remove if you want to use builtin-in MQTT broker\n';
text += ' birth_message:\n';
text += ` topic: 'hass/status'\n`;
text += ` payload: 'online'\n`;
text += ' will_message:\n';
text += ` topic: 'hass/status'\n`;
text += ` payload: 'offline'\n`;
text += '```';
text += '\n\n'
text += 'To respond to button clicks (e.g. WXKG01LM) you can use the following Home Assistant configuration:\n'
text += '```yaml'
text += `
automation:
- alias: Respond to button clicks
trigger:
platform: mqtt
topic: 'zigbee2mqtt/<FRIENDLY_NAME'
condition:
condition: template
value_template: "{{ 'single' == trigger.payload_json.click }}"
action:
entity_id: light.bedroom
service: light.toggle
`
text += '```\n'
text += '**When changing a `friendly_name` for a device you first have to start zigbee2mqtt and after that restart Home Assistant in order to discover the new device ID.**\n\n';
text += 'In case you **dont** want to use Home Assistant MQTT discovery you can use the configuration below.\n\n'
const homeassistantConfig = (device) => {
const payload = {
platform: 'mqtt',
state_topic: "zigbee2mqtt/<FRIENDLY_NAME>",
availability_topic: "zigbee2mqtt/bridge/state",
...device.discovery_payload,
};
if (payload.command_topic) {
if (payload.command_topic_prefix) {
payload.command_topic = `zigbee2mqtt/<FRIENDLY_NAME>/${payload.command_topic_prefix}/set`;
} else {
payload.command_topic = `zigbee2mqtt/<FRIENDLY_NAME>/set`;
}
}
delete payload.command_topic_prefix;
let yml = YAML.stringify([payload]);
yml = yml.replace(/(-) \n /g, '- ');
yml = yml.replace('---', `${device.type}:`)
return yml;
}
deviceMapping.forEach((device) => {
text += `### ${device.model}\n`;
text += '```yaml\n'
const configurations = homeassistant.mapping[device.model]
configurations.forEach((d, i) => {
text += homeassistantConfig(d);
if (configurations.length > 1 && i < configurations.length - 1) {
text += '\n';
}
})
text += '```\n\n';
});
fs.writeFileSync(outputdir + '/' + file, text);
-13
View File
@@ -1,13 +0,0 @@
// Verify that there are homeassistant mappings for every device.
const devices = require('zigbee-shepherd-converters').devices;
const homeassistant = require('../lib/homeassistant');
let failed = false;
devices.forEach((d) => {
if (!homeassistant.mapping[d.model]) {
console.error(`Missing homeassistant mapping for '${d.model}'`);
failed = true;
}
});
process.exit(failed ? 1 : 0);
+11
View File
@@ -0,0 +1,11 @@
class Example {
constructor(zigbee, mqtt, state, publishEntityState, eventBus) {
this.mqtt = mqtt;
}
onMQTTConnected() {
this.mqtt.publish('example/extension', 'test')
}
}
module.exports = Example;
@@ -0,0 +1,20 @@
const homeassistantSwitch = {
type: 'switch',
object_id: 'switch',
discovery_payload: {
payload_off: 'OFF',
payload_on: 'ON',
value_template: '{{ value_json.state }}',
command_topic: true,
},
};
const mockDevices = [{
mock: 1,
model: 'external_converters_device',
homeassistant: [homeassistantSwitch],
}, {
mock: 2
}];
module.exports = mockDevices;
+5
View File
@@ -0,0 +1,5 @@
const mockDevice = {
mock: true
};
module.exports = mockDevice;
+400
View File
@@ -0,0 +1,400 @@
const data = require('./stub/data');
const logger = require('./stub/logger');
const zigbeeHerdsman = require('./stub/zigbeeHerdsman');
zigbeeHerdsman.returnDevices.push('0x000b57fffec6a5b3');
zigbeeHerdsman.returnDevices.push('0x00124b00120144ae');
zigbeeHerdsman.returnDevices.push('0x0017880104e45553');
zigbeeHerdsman.returnDevices.push('0x0017880104e45517');
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 mockExit = jest.spyOn(process, 'exit').mockImplementation(() => {});
const mocksClear = [MQTT.publish, logger.warn, logger.debug];
describe('Availability', () => {
let controller;
function getExtension() {
return controller.extensions.find((e) => e.constructor.name === 'Availability');
}
beforeEach(async () => {
data.writeDefaultConfiguration();
settings._reRead();
data.writeEmptyState();
jest.useFakeTimers();
settings.set(['advanced', 'availability_timeout'], 10)
controller = new Controller();
mocksClear.forEach((m) => m.mockClear());
await controller.start();
await flushPromises();
});
afterEach(async () => {
await controller.stop();
await flushPromises();
})
it('Should publish availabilty on startup', async () => {
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bulb_color/availability',
'online',
{ retain: true, qos: 0 },
expect.any(Function)
);
});
it('Should publish availabilty offline when ping fails', async () => {
MQTT.publish.mockClear();
logger.error.mockClear();
logger.debug.mockClear();
const device = zigbeeHerdsman.devices.bulb_color;
device.ping.mockImplementationOnce(() => {throw new Error('failed')});
jest.advanceTimersByTime(11 * 1000);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(1);
expect(MQTT.publish).toHaveBeenNthCalledWith(1,
'zigbee2mqtt/bulb_color/availability',
'offline',
{ retain: true, qos: 0 },
expect.any(Function)
);
expect(logger.error).toHaveBeenCalledTimes(1);
expect(logger.error).toHaveBeenCalledWith("Failed to ping 'bulb_color'");
device.ping.mockImplementationOnce(() => {throw new Error('failed')});
jest.advanceTimersByTime(11 * 1000);
await flushPromises();
expect(logger.debug).toHaveBeenCalledTimes(3);
expect(logger.debug).toHaveBeenCalledWith("Failed to ping 'bulb_color'");
expect(MQTT.publish).toHaveBeenCalledTimes(1);
expect(MQTT.publish).toHaveBeenNthCalledWith(1,
'zigbee2mqtt/bulb_color/availability',
'offline',
{ retain: true, qos: 0 },
expect.any(Function)
);
});
it('Should publish availabilty online and query state on reconnect', async () => {
const device = zigbeeHerdsman.devices.bulb_color;
const endpoint = device.getEndpoint(1);
device.ping.mockImplementationOnce(() => {throw new Error('failed')});
jest.advanceTimersByTime(11 * 1000);
await flushPromises();
MQTT.publish.mockClear();
jest.advanceTimersByTime(11 * 1000);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bulb_color/availability',
'online',
{ retain: true, qos: 0 },
expect.any(Function)
);
expect(endpoint.read).toHaveBeenCalledTimes(3);
expect(endpoint.read).toHaveBeenCalledWith('genLevelCtrl', ['currentLevel']);
expect(endpoint.read).toHaveBeenCalledWith('genOnOff', ['onOff']);
expect(endpoint.read).toHaveBeenCalledWith('lightingColorCtrl', ['currentX', 'currentY', 'colorTemperature']);
});
it('Should fail gracefully when quering state after reconnect fails', async () => {
const device = zigbeeHerdsman.devices.bulb_color;
const endpoint = device.getEndpoint(1);
endpoint.read.mockClear();
endpoint.read.mockImplementationOnce(() => {throw new Error('Device timedout')});
device.ping.mockImplementationOnce(() => {throw new Error('failed')});
logger.debug.mockClear();
jest.advanceTimersByTime(11 * 2000);
await flushPromises();
expect(endpoint.read).toHaveBeenCalledTimes(1);
expect(endpoint.read).toHaveBeenCalledWith('genOnOff', ['onOff']);
expect(logger.error).toHaveBeenCalledWith(`Failed to read state of 'bulb_color' after reconnect`);
});
it('Shouldnt ping again when still pinging', async () => {
const device = zigbeeHerdsman.devices.bulb_color;
device.ping.mockClear();
device.ping.mockImplementationOnce(async () => {await wait(100000000)});
jest.advanceTimersByTime(11 * 1000);
await flushPromises();
expect(device.ping).toHaveBeenCalledTimes(1);
jest.advanceTimersByTime(11 * 1000);
await flushPromises();
expect(device.ping).toHaveBeenCalledTimes(1);
});
it('Should mark device online when receiving message while offline', async () => {
MQTT.publish.mockClear();
const device = zigbeeHerdsman.devices.bulb_color;
const endpoint = device.getEndpoint(1);
device.ping.mockImplementationOnce(() => {throw new Error('failed')});
jest.advanceTimersByTime(11 * 1000);
await flushPromises();
MQTT.publish.mockClear();
const data = {modelID: 'test'}
const payload = {data, cluster: 'genOnOff', device, endpoint, type: 'readResponse', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(1);
expect(MQTT.publish).toHaveBeenNthCalledWith(1,
'zigbee2mqtt/bulb_color/availability',
'online',
{ retain: true, qos: 0 },
expect.any(Function)
);
});
it('Should retrieve the state when device is turned on/off within availability timeout', async () => {
MQTT.publish.mockClear();
getExtension().state = {};
const payload = {device: zigbeeHerdsman.devices.bulb_color};
await zigbeeHerdsman.events.deviceJoined(payload);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bulb_color/availability',
'online',
{ retain: true, qos: 0 },
expect.any(Function)
);
});
it('Should retrieve the state when device is turned on/off within availability timeout on deviceAnnounce', async () => {
MQTT.publish.mockClear();
const device = zigbeeHerdsman.devices.bulb_color;
const endpoint = device.getEndpoint(1);
endpoint.read.mockClear();
await zigbeeHerdsman.events.deviceAnnounce({device});
await flushPromises();
expect(endpoint.read).toHaveBeenCalledTimes(3);
expect(endpoint.read).toHaveBeenCalledWith('genLevelCtrl', ['currentLevel']);
expect(endpoint.read).toHaveBeenCalledWith('genOnOff', ['onOff']);
expect(endpoint.read).toHaveBeenCalledWith('lightingColorCtrl', ['currentX', 'currentY', 'colorTemperature']);
});
it('Should not retrieve the state when device is turned on/off within availability timeout on deviceJoined', async () => {
MQTT.publish.mockClear();
const device = zigbeeHerdsman.devices.bulb_color;
const endpoint = device.getEndpoint(1);
endpoint.read.mockClear();
await zigbeeHerdsman.events.deviceJoined({device});
await flushPromises();
expect(endpoint.read).toHaveBeenCalledTimes(0);
});
it('Should not do anything when message has no device', async () => {
MQTT.publish.mockClear();
const device = zigbeeHerdsman.devices.bulb_color;
const payload = {ieeeAddr: device.ieeeAddr};
await zigbeeHerdsman.events.deviceLeave(payload);
await flushPromises();
expect(MQTT.publish.mock.calls.find((c) => c[0].includes('availability'))).toBeUndefined();
});
it('Should not ping devices on blocklist by friendly name', async () => {
const device = zigbeeHerdsman.devices.bulb_color;
settings.set(['advanced', 'availability_blocklist'], ['bulb_color'])
await controller.stop();
await flushPromises();
controller = new Controller();
await controller.start();
await flushPromises();
device.ping.mockClear();
jest.advanceTimersByTime(11 * 1000);
await flushPromises();
expect(device.ping).toHaveBeenCalledTimes(0);
});
it('Should not ping devices on blacklist by friendly name', async () => {
const device = zigbeeHerdsman.devices.bulb_color;
settings.set(['advanced', 'availability_blacklist'], ['bulb_color'])
await controller.stop();
await flushPromises();
controller = new Controller();
await controller.start();
await flushPromises();
device.ping.mockClear();
jest.advanceTimersByTime(11 * 1000);
await flushPromises();
expect(device.ping).toHaveBeenCalledTimes(0);
});
it('Should not ping devices on blocklist by IEEE address', async () => {
const device = zigbeeHerdsman.devices.bulb_color;
settings.set(['advanced', 'availability_blocklist'], [device.ieeeAddr]);
await controller.stop();
await flushPromises();
controller = new Controller();
await controller.start();
await flushPromises();
device.ping.mockClear();
jest.advanceTimersByTime(11 * 1000);
await flushPromises();
expect(device.ping).toHaveBeenCalledTimes(0);
});
it('Should ping forced pingable devices', async () => {
const device = zigbeeHerdsman.devices.E11_G13;
const endpoint = device.getEndpoint(1);
const data = {modelID: 'test'}
const payload = {data, cluster: 'genOnOff', device, endpoint, type: 'readResponse', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
device.ping.mockClear();
jest.advanceTimersByTime(11 * 1000);
await flushPromises();
expect(device.ping).toHaveBeenCalledTimes(1);
});
it('Should ping devices on passlist by friendly name if availability_passlist is set', async () => {
const device = zigbeeHerdsman.devices.bulb_color;
settings.set(['advanced', 'availability_passlist'], ['bulb_color']);
await controller.stop();
await flushPromises();
controller = new Controller();
await controller.start();
await flushPromises();
device.ping.mockClear();
jest.advanceTimersByTime(11 * 1000);
await flushPromises();
expect(device.ping).toHaveBeenCalledTimes(1);
});
it('Should ping devices on whitelist by friendly name if availability_whitelist is set', async () => {
const device = zigbeeHerdsman.devices.bulb_color;
settings.set(['advanced', 'availability_whitelist'], ['bulb_color']);
await controller.stop();
await flushPromises();
controller = new Controller();
await controller.start();
await flushPromises();
device.ping.mockClear();
jest.advanceTimersByTime(11 * 1000);
await flushPromises();
expect(device.ping).toHaveBeenCalledTimes(1);
});
it('Should ping devices on passlist by IEEE address if availability_passlist is set', async () => {
const device = zigbeeHerdsman.devices.bulb_color;
settings.set(['advanced', 'availability_passlist'], [device.ieeeAddr]);
await controller.stop();
await flushPromises();
controller = new Controller();
await controller.start();
await flushPromises();
device.ping.mockClear();
jest.advanceTimersByTime(11 * 1000);
await flushPromises();
expect(device.ping).toHaveBeenCalledTimes(1);
});
it('Should not ping devices not in passlist if availability_passlist is set', async () => {
const device = zigbeeHerdsman.devices.bulb;
getExtension().state[device.ieeeAddr] = false;
settings.set(['advanced', 'availability_passlist'], ['0x000b57fffec6a5b3'])
await controller.stop();
await flushPromises();
controller = new Controller();
await controller.start();
await flushPromises();
jest.advanceTimersByTime(11 * 1000);
await flushPromises();
expect(device.ping).toHaveBeenCalledTimes(0);
MQTT.publish.mockClear();
await zigbeeHerdsman.events.deviceAnnounce({device});
});
it('Should not read when device has no modelID and reconnects', async () => {
const device = zigbeeHerdsman.devices.nomodel;
getExtension().state[device.ieeeAddr] = true;
const endpoint = device.getEndpoint(1);
await zigbeeHerdsman.events.deviceAnnounce({device});
await flushPromises();
expect(endpoint.read).toHaveBeenCalledTimes(0);
});
it('Should not read when device has is unsupported', async () => {
const device = zigbeeHerdsman.devices.unsupported_router;
getExtension().state[device.ieeeAddr] = true;
const endpoint = device.getEndpoint(1);
await zigbeeHerdsman.events.deviceAnnounce({device});
await flushPromises();
expect(endpoint.read).toHaveBeenCalledTimes(0);
});
it('Should stop pinging device when removed', async () => {
const device = zigbeeHerdsman.devices.bulb_color;
device.ping.mockClear();
const endpoint = device.getEndpoint(1);
jest.advanceTimersByTime(11 * 1000);
await flushPromises();
expect(device.ping).toHaveBeenCalledTimes(1);
settings.removeDevice(device.ieeeAddr);
jest.advanceTimersByTime(11 * 1000);
await flushPromises();
expect(device.ping).toHaveBeenCalledTimes(1);
});
it('Should publish availability when end device joins', async () => {
const device = zigbeeHerdsman.devices.WXKG02LM;
const payload = {device};
MQTT.publish.mockClear();
await zigbeeHerdsman.events.deviceJoined(payload);
await flushPromises();
expect(device.ping).toHaveBeenCalledTimes(0);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/button_double_key/availability',
'online',
{ retain: true, qos: 0 },
expect.any(Function)
);
});
it('Should mark non-pingable device as non-available when offline for longer than 24 hours', async () => {
const device = zigbeeHerdsman.devices.remote;
const defaultLastSeen = device.lastSeen;
device.lastSeen = Date.now();
MQTT.publish.mockClear();
jest.advanceTimersByTime(1000 * 60 * 60 * 1); // 1 hours
expect(MQTT.publish).toHaveBeenCalledTimes(0);
device.lastSeen = device.lastSeen - (1000 * 60 * 60 * 25);
jest.advanceTimersByTime(1000 * 60 * 60 * 1); // 1 hours
expect(MQTT.publish).toHaveBeenCalledTimes(1);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/remote/availability',
'offline',
{ retain: true, qos: 0 },
expect.any(Function)
);
// Shouldn't do anything more when device is removed
settings.removeDevice(device.ieeeAddr);
jest.advanceTimersByTime(1000 * 60 * 60 * 1); // 1 hours
expect(MQTT.publish).toHaveBeenCalledTimes(1);
device.lastSeen = defaultLastSeen;
});
it('Should republish existing state on MQTT connected', async () => {
const device = zigbeeHerdsman.devices.bulb_color;
await controller.stop();
await flushPromises();
MQTT.publish.mockClear();
controller = new Controller();
getExtension().state[device.ieeeAddr] = false;
await controller.start();
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bulb_color/availability',
'offline',
{ retain: true, qos: 0 },
expect.any(Function)
);
});
});
+406
View File
@@ -0,0 +1,406 @@
const data = require('./stub/data');
const logger = require('./stub/logger');
const zigbeeHerdsman = require('./stub/zigbeeHerdsman');
const MQTT = require('./stub/mqtt');
const settings = require('../lib/util/settings');
const Controller = require('../lib/controller');
const flushPromises = () => new Promise(setImmediate);
describe('Bind', () => {
let controller;
mockClear = (device) => {
for (const endpoint of device.endpoints) {
endpoint.read.mockClear();
endpoint.write.mockClear();
endpoint.configureReporting.mockClear();
endpoint.bind = jest.fn();
endpoint.bind.mockClear();
endpoint.unbind.mockClear();
}
}
beforeEach(async () => {
data.writeDefaultConfiguration();
settings._reRead();
data.writeEmptyState();
settings.set(['experimental', 'new_api'], true);
controller = new Controller();
await controller.start();
await flushPromises();
this.coordinatorEndoint = zigbeeHerdsman.devices.coordinator.getEndpoint(1);
MQTT.publish.mockClear();
});
it('Should subscribe to topics', async () => {
expect(MQTT.subscribe).toHaveBeenCalledWith('zigbee2mqtt/bridge/request/device/bind');
expect(MQTT.subscribe).toHaveBeenCalledWith('zigbee2mqtt/bridge/request/device/unbind');
expect(MQTT.subscribe).toHaveBeenCalledWith('zigbee2mqtt/bridge/bind/#');
});
it('Should bind', async () => {
const device = zigbeeHerdsman.devices.remote;
const target = zigbeeHerdsman.devices.bulb_color.getEndpoint(1);
const endpoint = device.getEndpoint(1);
mockClear(device);
MQTT.events.message('zigbee2mqtt/bridge/request/device/bind', JSON.stringify({from: 'remote', to: 'bulb_color'}));
await flushPromises();
expect(endpoint.bind).toHaveBeenCalledTimes(3);
expect(endpoint.bind).toHaveBeenCalledWith("genOnOff", target);
expect(endpoint.bind).toHaveBeenCalledWith("genLevelCtrl", target);
expect(endpoint.bind).toHaveBeenCalledWith("genScenes", target);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/bind',
JSON.stringify({"data":{"from":"remote","to":"bulb_color","clusters":["genScenes","genOnOff","genLevelCtrl"],"failed":[]},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
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/request/device/bind', JSON.stringify({from: 'remote', to: 'button'}));
await flushPromises();
expect(endpoint.bind).toHaveBeenCalledTimes(0);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/bind',
JSON.stringify({"data":{"from":"remote","to":"button","clusters":[],"failed":[]},"status":"error","error":"Nothing to bind"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should unbind', async () => {
const device = zigbeeHerdsman.devices.remote;
const target = zigbeeHerdsman.devices.bulb_color.getEndpoint(1);
const endpoint = device.getEndpoint(1);
mockClear(device);
MQTT.events.message('zigbee2mqtt/bridge/request/device/unbind', JSON.stringify({from: 'remote', to: 'bulb_color'}));
await flushPromises();
expect(endpoint.unbind).toHaveBeenCalledTimes(3);
expect(endpoint.unbind).toHaveBeenCalledWith("genOnOff", target);
expect(endpoint.unbind).toHaveBeenCalledWith("genLevelCtrl", target);
expect(endpoint.unbind).toHaveBeenCalledWith("genScenes", target);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/unbind',
JSON.stringify({"data":{"from":"remote","to":"bulb_color","clusters":["genScenes","genOnOff","genLevelCtrl"],"failed":[]},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should unbind coordinator', async () => {
const device = zigbeeHerdsman.devices.remote;
const target = zigbeeHerdsman.devices.coordinator.getEndpoint(1);
const endpoint = device.getEndpoint(1);
mockClear(device);
endpoint.unbind.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/device/unbind', JSON.stringify({from: 'remote', to: 'Coordinator'}));
await flushPromises();
expect(endpoint.unbind).toHaveBeenCalledTimes(3);
expect(endpoint.unbind).toHaveBeenCalledWith("genOnOff", target);
expect(endpoint.unbind).toHaveBeenCalledWith("genLevelCtrl", target);
expect(endpoint.unbind).toHaveBeenCalledWith("genScenes", target);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/unbind',
JSON.stringify({"data":{"from":"remote","to":"Coordinator","clusters":["genScenes","genOnOff","genLevelCtrl"],"failed":[]},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should bind to groups', async () => {
const device = zigbeeHerdsman.devices.remote;
const target = zigbeeHerdsman.groups.group_1;
const endpoint = device.getEndpoint(1);
mockClear(device);
MQTT.events.message('zigbee2mqtt/bridge/request/device/bind', JSON.stringify({from: 'remote', to: 'group_1'}));
await flushPromises();
expect(endpoint.bind).toHaveBeenCalledTimes(3);
expect(endpoint.bind).toHaveBeenCalledWith("genOnOff", target);
expect(endpoint.bind).toHaveBeenCalledWith("genLevelCtrl", target);
expect(endpoint.bind).toHaveBeenCalledWith("genScenes", target);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/bind',
JSON.stringify({"data":{"from":"remote","to":"group_1","clusters":["genScenes","genOnOff","genLevelCtrl"],"failed":[]},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should bind to group by number', async () => {
const device = zigbeeHerdsman.devices.remote;
const target = zigbeeHerdsman.groups.group_1;
const endpoint = device.getEndpoint(1);
mockClear(device);
MQTT.events.message('zigbee2mqtt/bridge/request/device/bind', JSON.stringify({from: 'remote', to: '1'}));
await flushPromises();
expect(endpoint.bind).toHaveBeenCalledTimes(3);
expect(endpoint.bind).toHaveBeenCalledWith("genOnOff", target);
expect(endpoint.bind).toHaveBeenCalledWith("genLevelCtrl", target);
expect(endpoint.bind).toHaveBeenCalledWith("genScenes", target);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/bind',
JSON.stringify({"data":{"from":"remote","to":"1","clusters":["genScenes","genOnOff","genLevelCtrl"],"failed":[]},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should log when bind fails', async () => {
logger.error.mockClear();
const device = zigbeeHerdsman.devices.remote;
const endpoint = device.getEndpoint(1);
mockClear(device);
endpoint.bind.mockImplementation(() => {throw new Error('failed')});
MQTT.events.message('zigbee2mqtt/bridge/request/device/bind', JSON.stringify({from: 'remote', to: 'bulb_color'}));
await flushPromises();
expect(endpoint.bind).toHaveBeenCalledTimes(3);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/bind',
JSON.stringify({"data":{"from":"remote","to":"bulb_color","clusters":[],"failed":["genScenes","genOnOff","genLevelCtrl"]},"status":"error","error":"Failed to bind"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should bind from non default endpoints', async () => {
const device = zigbeeHerdsman.devices.remote;
const target = zigbeeHerdsman.devices.QBKG03LM.getEndpoint(3);
const endpoint = device.getEndpoint(2);
mockClear(device);
MQTT.events.message('zigbee2mqtt/bridge/request/device/bind', JSON.stringify({from: 'remote/ep2', to: 'wall_switch_double/right'}));
await flushPromises();
expect(endpoint.bind).toHaveBeenCalledTimes(1);
expect(endpoint.bind).toHaveBeenCalledWith("genOnOff", target);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/bind',
JSON.stringify({"data":{"from":"remote/ep2","to":"wall_switch_double/right","clusters":["genOnOff"],"failed":[]},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should bind to default endpoint returned by endpoints()', async () => {
const device = zigbeeHerdsman.devices.remote;
const target = zigbeeHerdsman.devices.QBKG04LM.getEndpoint(2);
const endpoint = device.getEndpoint(2);
mockClear(device);
MQTT.events.message('zigbee2mqtt/bridge/request/device/bind', JSON.stringify({from: 'remote/ep2', to: 'wall_switch'}));
await flushPromises();
expect(endpoint.bind).toHaveBeenCalledTimes(1);
expect(endpoint.bind).toHaveBeenCalledWith("genOnOff", target);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/bind',
JSON.stringify({"data":{"from":"remote/ep2","to":"wall_switch","clusters":["genOnOff"],"failed":[]},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should unbind from default_bind_group', async () => {
const device = zigbeeHerdsman.devices.remote;
const target = 'default_bind_group';
const endpoint = device.getEndpoint(1);
mockClear(device);
MQTT.events.message('zigbee2mqtt/bridge/request/device/unbind', JSON.stringify({from: 'remote', to: target}));
await flushPromises();
expect(endpoint.unbind).toHaveBeenCalledTimes(3);
expect(endpoint.unbind).toHaveBeenCalledWith("genOnOff", 901);
expect(endpoint.unbind).toHaveBeenCalledWith("genLevelCtrl", 901);
expect(endpoint.unbind).toHaveBeenCalledWith("genScenes", 901);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/unbind',
JSON.stringify({"data":{"from":"remote","to":"default_bind_group","clusters":["genScenes","genOnOff","genLevelCtrl"],"failed":[]},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Error bind fails when source not existing', async () => {
const device = zigbeeHerdsman.devices.remote;
const target = zigbeeHerdsman.devices.bulb_color.getEndpoint(1);
const endpoint = device.getEndpoint(1);
mockClear(device);
MQTT.events.message('zigbee2mqtt/bridge/request/device/bind', JSON.stringify({from: 'remote_not_existing', to: 'bulb_color'}));
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/bind',
JSON.stringify({"data":{"from":"remote_not_existing","to":"bulb_color"},"status":"error","error":"Source device 'remote_not_existing' does not exist"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Error bind fails when target not existing', async () => {
const device = zigbeeHerdsman.devices.remote;
const target = zigbeeHerdsman.devices.bulb_color.getEndpoint(1);
const endpoint = device.getEndpoint(1);
mockClear(device);
MQTT.events.message('zigbee2mqtt/bridge/request/device/bind', JSON.stringify({from: 'remote', to: 'bulb_color_not_existing'}));
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/bind',
JSON.stringify({"data":{"from":"remote","to":"bulb_color_not_existing"},"status":"error","error":"Target device or group 'bulb_color_not_existing' does not exist"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Legacy api: Should bind', async () => {
const device = zigbeeHerdsman.devices.remote;
const target = zigbeeHerdsman.devices.bulb_color.getEndpoint(1);
const endpoint = device.getEndpoint(1);
mockClear(device);
MQTT.events.message('zigbee2mqtt/bridge/bind/remote', 'bulb_color');
await flushPromises();
expect(endpoint.bind).toHaveBeenCalledTimes(3);
expect(endpoint.bind).toHaveBeenCalledWith("genOnOff", target);
expect(endpoint.bind).toHaveBeenCalledWith("genLevelCtrl", target);
expect(endpoint.bind).toHaveBeenCalledWith("genScenes", target);
expect(MQTT.publish).toHaveBeenCalledTimes(3);
expect(MQTT.publish.mock.calls[0][0]).toStrictEqual('zigbee2mqtt/bridge/log');
expect(JSON.parse(MQTT.publish.mock.calls[0][1])).toStrictEqual({type: 'device_bind', message: {from: 'remote', to: 'bulb_color', cluster: 'genScenes'}});
expect(MQTT.publish.mock.calls[1][0]).toStrictEqual('zigbee2mqtt/bridge/log');
expect(JSON.parse(MQTT.publish.mock.calls[1][1])).toStrictEqual({type: 'device_bind', message: {from: 'remote', to: 'bulb_color', cluster: 'genOnOff'}});
expect(MQTT.publish.mock.calls[2][0]).toStrictEqual('zigbee2mqtt/bridge/log');
expect(JSON.parse(MQTT.publish.mock.calls[2][1])).toStrictEqual({type: 'device_bind', message: {from: 'remote', to: 'bulb_color', cluster: 'genLevelCtrl'}});
});
it('Legacy api: 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('Legacy api: Should unbind', async () => {
const device = zigbeeHerdsman.devices.remote;
const target = zigbeeHerdsman.devices.bulb_color.getEndpoint(1);
const endpoint = device.getEndpoint(1);
mockClear(device);
MQTT.events.message('zigbee2mqtt/bridge/unbind/remote', 'bulb_color');
await flushPromises();
expect(endpoint.unbind).toHaveBeenCalledTimes(3);
expect(endpoint.unbind).toHaveBeenCalledWith("genOnOff", target);
expect(endpoint.unbind).toHaveBeenCalledWith("genLevelCtrl", target);
expect(endpoint.unbind).toHaveBeenCalledWith("genScenes", target);
expect(MQTT.publish).toHaveBeenCalledTimes(3);
expect(MQTT.publish.mock.calls[0][0]).toStrictEqual('zigbee2mqtt/bridge/log');
expect(JSON.parse(MQTT.publish.mock.calls[0][1])).toStrictEqual({type: 'device_unbind', message: {from: 'remote', to: 'bulb_color', cluster: 'genScenes'}});
expect(MQTT.publish.mock.calls[1][0]).toStrictEqual('zigbee2mqtt/bridge/log');
expect(JSON.parse(MQTT.publish.mock.calls[1][1])).toStrictEqual({type: 'device_unbind', message: {from: 'remote', to: 'bulb_color', cluster: 'genOnOff'}});
expect(MQTT.publish.mock.calls[2][0]).toStrictEqual('zigbee2mqtt/bridge/log');
expect(JSON.parse(MQTT.publish.mock.calls[2][1])).toStrictEqual({type: 'device_unbind', message: {from: 'remote', to: 'bulb_color', cluster: 'genLevelCtrl'}});
});
it('Legacy api: Should unbind coordinator', async () => {
const device = zigbeeHerdsman.devices.remote;
const target = zigbeeHerdsman.devices.coordinator.getEndpoint(1);
const endpoint = device.getEndpoint(1);
mockClear(device);
endpoint.unbind.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/unbind/remote', 'Coordinator');
await flushPromises();
expect(endpoint.unbind).toHaveBeenCalledTimes(3);
expect(endpoint.unbind).toHaveBeenCalledWith("genOnOff", target);
expect(endpoint.unbind).toHaveBeenCalledWith("genLevelCtrl", target);
expect(endpoint.unbind).toHaveBeenCalledWith("genScenes", target);
expect(MQTT.publish).toHaveBeenCalledTimes(3);
expect(MQTT.publish.mock.calls[0][0]).toStrictEqual('zigbee2mqtt/bridge/log');
expect(JSON.parse(MQTT.publish.mock.calls[0][1])).toStrictEqual({type: 'device_unbind', message: {from: 'remote', to: 'Coordinator', cluster: 'genScenes'}});
expect(MQTT.publish.mock.calls[1][0]).toStrictEqual('zigbee2mqtt/bridge/log');
expect(JSON.parse(MQTT.publish.mock.calls[1][1])).toStrictEqual({type: 'device_unbind', message: {from: 'remote', to: 'Coordinator', cluster: 'genOnOff'}});
expect(MQTT.publish.mock.calls[2][0]).toStrictEqual('zigbee2mqtt/bridge/log');
expect(JSON.parse(MQTT.publish.mock.calls[2][1])).toStrictEqual({type: 'device_unbind', message: {from: 'remote', to: 'Coordinator', cluster: 'genLevelCtrl'}});
});
it('Legacy api: Should bind to groups', async () => {
const device = zigbeeHerdsman.devices.remote;
const target = zigbeeHerdsman.groups.group_1;
const endpoint = device.getEndpoint(1);
mockClear(device);
MQTT.events.message('zigbee2mqtt/bridge/bind/remote', 'group_1');
await flushPromises();
expect(endpoint.bind).toHaveBeenCalledTimes(3);
expect(endpoint.bind).toHaveBeenCalledWith("genOnOff", target);
expect(endpoint.bind).toHaveBeenCalledWith("genLevelCtrl", target);
expect(endpoint.bind).toHaveBeenCalledWith("genScenes", target);
expect(MQTT.publish).toHaveBeenCalledTimes(3);
expect(MQTT.publish.mock.calls[0][0]).toStrictEqual('zigbee2mqtt/bridge/log');
expect(JSON.parse(MQTT.publish.mock.calls[0][1])).toStrictEqual({type: 'device_bind', message: {from: 'remote', to: 'group_1', cluster: 'genScenes'}});
expect(MQTT.publish.mock.calls[1][0]).toStrictEqual('zigbee2mqtt/bridge/log');
expect(JSON.parse(MQTT.publish.mock.calls[1][1])).toStrictEqual({type: 'device_bind', message: {from: 'remote', to: 'group_1', cluster: 'genOnOff'}});
expect(MQTT.publish.mock.calls[2][0]).toStrictEqual('zigbee2mqtt/bridge/log');
expect(JSON.parse(MQTT.publish.mock.calls[2][1])).toStrictEqual({type: 'device_bind', message: {from: 'remote', to: 'group_1', cluster: 'genLevelCtrl'}});
});
it('Legacy api: Should bind to group by number', async () => {
const device = zigbeeHerdsman.devices.remote;
const target = zigbeeHerdsman.groups.group_1;
const endpoint = device.getEndpoint(1);
mockClear(device);
MQTT.events.message('zigbee2mqtt/bridge/bind/remote', '1');
await flushPromises();
expect(endpoint.bind).toHaveBeenCalledTimes(3);
expect(endpoint.bind).toHaveBeenCalledWith("genOnOff", target);
expect(endpoint.bind).toHaveBeenCalledWith("genLevelCtrl", target);
expect(endpoint.bind).toHaveBeenCalledWith("genScenes", target);
expect(MQTT.publish).toHaveBeenCalledTimes(3);
expect(MQTT.publish.mock.calls[0][0]).toStrictEqual('zigbee2mqtt/bridge/log');
expect(JSON.parse(MQTT.publish.mock.calls[0][1])).toStrictEqual({type: 'device_bind', message: {from: 'remote', to: 'group_1', cluster: 'genScenes'}});
expect(MQTT.publish.mock.calls[1][0]).toStrictEqual('zigbee2mqtt/bridge/log');
expect(JSON.parse(MQTT.publish.mock.calls[1][1])).toStrictEqual({type: 'device_bind', message: {from: 'remote', to: 'group_1', cluster: 'genOnOff'}});
expect(MQTT.publish.mock.calls[2][0]).toStrictEqual('zigbee2mqtt/bridge/log');
expect(JSON.parse(MQTT.publish.mock.calls[2][1])).toStrictEqual({type: 'device_bind', message: {from: 'remote', to: 'group_1', cluster: 'genLevelCtrl'}});
});
it('Legacy api: Should log when bind fails', async () => {
logger.error.mockClear();
const device = zigbeeHerdsman.devices.remote;
const endpoint = device.getEndpoint(1);
mockClear(device);
endpoint.bind.mockImplementationOnce(() => {throw new Error('failed')});
MQTT.events.message('zigbee2mqtt/bridge/bind/remote', 'bulb_color');
await flushPromises();
expect(logger.error).toHaveBeenCalledWith("Failed to bind cluster 'genScenes' from 'remote' to 'bulb_color' (Error: failed)");
expect(endpoint.bind).toHaveBeenCalledTimes(3);
});
it('Legacy api: Should bind from non default endpoints', async () => {
const device = zigbeeHerdsman.devices.remote;
const target = zigbeeHerdsman.devices.QBKG03LM.getEndpoint(3);
const endpoint = device.getEndpoint(2);
mockClear(device);
MQTT.events.message('zigbee2mqtt/bridge/bind/remote/ep2', 'wall_switch_double/right');
await flushPromises();
expect(endpoint.bind).toHaveBeenCalledTimes(1);
expect(endpoint.bind).toHaveBeenCalledWith("genOnOff", target);
});
it('Legacy api: Should bind to default endpoint returned by endpoints()', async () => {
const device = zigbeeHerdsman.devices.remote;
const target = zigbeeHerdsman.devices.QBKG04LM.getEndpoint(2);
const endpoint = device.getEndpoint(2);
mockClear(device);
MQTT.events.message('zigbee2mqtt/bridge/bind/remote/ep2', 'wall_switch');
await flushPromises();
expect(endpoint.bind).toHaveBeenCalledTimes(1);
expect(endpoint.bind).toHaveBeenCalledWith("genOnOff", target);
});
it('Legacy api: Should unbind from default_bind_group', async () => {
const device = zigbeeHerdsman.devices.remote;
const target = 'default_bind_group';
const endpoint = device.getEndpoint(1);
mockClear(device);
MQTT.events.message('zigbee2mqtt/bridge/unbind/remote', target);
await flushPromises();
expect(endpoint.unbind).toHaveBeenCalledTimes(3);
expect(endpoint.unbind).toHaveBeenCalledWith("genOnOff", 901);
expect(endpoint.unbind).toHaveBeenCalledWith("genLevelCtrl", 901);
expect(endpoint.unbind).toHaveBeenCalledWith("genScenes", 901);
expect(MQTT.publish).toHaveBeenCalledTimes(3);
expect(MQTT.publish.mock.calls[0][0]).toStrictEqual('zigbee2mqtt/bridge/log');
expect(JSON.parse(MQTT.publish.mock.calls[0][1])).toStrictEqual({type: 'device_unbind', message: {from: 'remote', to: 'default_bind_group', cluster: 'genScenes'}});
expect(MQTT.publish.mock.calls[1][0]).toStrictEqual('zigbee2mqtt/bridge/log');
expect(JSON.parse(MQTT.publish.mock.calls[1][1])).toStrictEqual({type: 'device_unbind', message: {from: 'remote', to: 'default_bind_group', cluster: 'genOnOff'}});
expect(MQTT.publish.mock.calls[2][0]).toStrictEqual('zigbee2mqtt/bridge/log');
expect(JSON.parse(MQTT.publish.mock.calls[2][1])).toStrictEqual({type: 'device_unbind', message: {from: 'remote', to: 'default_bind_group', cluster: 'genLevelCtrl'}});
});
});
+605
View File
@@ -0,0 +1,605 @@
const data = require('./stub/data');
const logger = require('./stub/logger');
const zigbeeHerdsman = require('./stub/zigbeeHerdsman');
const MQTT = require('./stub/mqtt');
const settings = require('../lib/util/settings');
const Controller = require('../lib/controller');
const flushPromises = () => new Promise(setImmediate);
const mockExit = jest.spyOn(process, 'exit').mockImplementation(() => {});
const {coordinator, bulb, unsupported} = zigbeeHerdsman.devices;
zigbeeHerdsman.returnDevices.push(coordinator.ieeeAddr);
zigbeeHerdsman.returnDevices.push(bulb.ieeeAddr);
zigbeeHerdsman.returnDevices.push(unsupported.ieeeAddr);
describe('Bridge', () => {
let controller;
beforeEach(async () => {
data.writeDefaultConfiguration();
settings._reRead();
settings.set(['advanced', 'legacy_api'], false);
settings.set(['experimental', 'new_api'], true);
data.writeDefaultState();
logger.info.mockClear();
logger.warn.mockClear();
MQTT.publish.mockClear();
const device = zigbeeHerdsman.devices.bulb;
device.removeFromDatabase.mockClear();
device.removeFromNetwork.mockClear();
controller = new Controller();
await controller.start();
await flushPromises();
});
it('Should publish bridge info on startup', async () => {
const version = await require('../lib/util/utils').getZigbee2mqttVersion();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/info',
JSON.stringify({"version":version.version,"commit":version.commitHash,"coordinator":{"type":"z-Stack","meta":{"version":1,"revision":20190425}},"log_level":"info","permit_join":false}),
{ retain: true, qos: 0 },
expect.any(Function)
);
});
it('Should publish devices on startup', async () => {
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/devices',
JSON.stringify([{"ieee_address":"0x000b57fffec6a5b2","type":"Router","network_address":40369,"supported":true,"friendly_name":"bulb","definition":{"model":"LED1545G12","vendor":"IKEA","description":"TRADFRI LED bulb E26/E27 980 lumen, dimmable, white spectrum, opal white","supports":"on/off, brightness, color temperature"},"power_source":"Mains (single phase)","date_code":null,"interviewing":false,"interview_completed":true},{"ieee_address":"0x0017880104e45518","type":"EndDevice","network_address":6536,"supported":false,"friendly_name":"0x0017880104e45518","definition":null,"power_source":"Battery","date_code":null,"interviewing":false,"interview_completed":true}]),
{ retain: true, qos: 0 },
expect.any(Function)
);
});
it('Should publish devices on startup', async () => {
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/groups',
JSON.stringify([{"id":1,"friendly_name":"group_1","members":[]},{"id":15071,"friendly_name":"group_tradfri_remote","members":[]},{"id":99,"friendly_name":99,"members":[]},{"id":11,"friendly_name":"group_with_tradfri","members":[]},{"id":2,"friendly_name":"group_2","members":[]}]),
{ retain: true, qos: 0 },
expect.any(Function)
);
});
it('Should publish event when device joined', async () => {
MQTT.publish.mockClear();
await zigbeeHerdsman.events.deviceJoined({device: zigbeeHerdsman.devices.bulb});
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(1);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/event',
JSON.stringify({"type":"device_joined","data":{"friendly_name":"bulb","ieee_address":"0x000b57fffec6a5b2"}}),
{ retain: false, qos: 0 },
expect.any(Function)
);
});
it('Should publish event when device interview started', async () => {
MQTT.publish.mockClear();
await zigbeeHerdsman.events.deviceInterview({device: zigbeeHerdsman.devices.bulb, status: 'started'});
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(1);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/event',
JSON.stringify({"type":"device_interview","data":{"friendly_name":"bulb","status":"started","ieee_address":"0x000b57fffec6a5b2"}}),
{ retain: false, qos: 0 },
expect.any(Function)
);
});
it('Should publish event and devices when device interview failed', async () => {
MQTT.publish.mockClear();
await zigbeeHerdsman.events.deviceInterview({device: zigbeeHerdsman.devices.bulb, status: 'failed'});
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(2);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/event',
JSON.stringify({"type":"device_interview","data":{"friendly_name":"bulb","status":"failed","ieee_address":"0x000b57fffec6a5b2"}}),
{ retain: false, qos: 0 },
expect.any(Function)
);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/devices',
expect.any(String),
{ retain: true, qos: 0 },
expect.any(Function)
);
});
it('Should publish event and devices when device interview successful', async () => {
MQTT.publish.mockClear();
await zigbeeHerdsman.events.deviceInterview({device: zigbeeHerdsman.devices.bulb, status: 'successful'});
await zigbeeHerdsman.events.deviceInterview({device: zigbeeHerdsman.devices.unsupported, status: 'successful'});
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(4);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/event',
JSON.stringify({"type":"device_interview","data":{"friendly_name":"bulb","status":"successful","ieee_address":"0x000b57fffec6a5b2","supported":true,"definition":{"model":"LED1545G12","vendor":"IKEA","description":"TRADFRI LED bulb E26/E27 980 lumen, dimmable, white spectrum, opal white","supports":"on/off, brightness, color temperature"}}}),
{ retain: false, qos: 0 },
expect.any(Function)
);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/event',
JSON.stringify({"type":"device_interview","data":{"friendly_name":"0x0017880104e45518","status":"successful","ieee_address":"0x0017880104e45518","supported":false,"definition":null}}),
{ retain: false, qos: 0 },
expect.any(Function)
);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/devices',
expect.any(String),
{ retain: true, qos: 0 },
expect.any(Function)
);
});
it('Should publish event and devices when device leaves', async () => {
MQTT.publish.mockClear();
await zigbeeHerdsman.events.deviceLeave({ieeeAddr: zigbeeHerdsman.devices.bulb.ieeeAddr});
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(2);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/event',
JSON.stringify({"type":"device_leave","data":{"ieee_address":"0x000b57fffec6a5b2"}}),
{ retain: false, qos: 0 },
expect.any(Function)
);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/devices',
expect.any(String),
{ retain: true, qos: 0 },
expect.any(Function)
);
});
it('Should allow permit join', async () => {
zigbeeHerdsman.permitJoin.mockClear();
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/permit_join', 'true');
await flushPromises();
expect(zigbeeHerdsman.permitJoin).toHaveBeenCalledTimes(1);
expect(zigbeeHerdsman.permitJoin).toHaveBeenCalledWith(true);
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bridge/info', expect.any(String), { retain: true, qos: 0 }, expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/permit_join',
JSON.stringify({"data":{"value":true},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
zigbeeHerdsman.permitJoin.mockClear();
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/permit_join', JSON.stringify({"value": false}));
await flushPromises();
expect(zigbeeHerdsman.permitJoin).toHaveBeenCalledTimes(1);
expect(zigbeeHerdsman.permitJoin).toHaveBeenCalledWith(false);
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bridge/info', expect.any(String), { retain: true, qos: 0 }, expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/permit_join',
JSON.stringify({"data":{"value":false},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should put transaction in response when request is done with transaction', async () => {
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/permit_join', JSON.stringify({"value": false, "transaction": 22}));
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/permit_join',
JSON.stringify({"data":{"value":false},"status":"ok", "transaction": 22}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should put error in response when request fails', async () => {
zigbeeHerdsman.permitJoin.mockImplementationOnce(() => {throw new Error('Failed to connect to adapter')});
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/permit_join', JSON.stringify({"value": false}));
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/permit_join',
JSON.stringify({"data":{},"status":"error","error": "Failed to connect to adapter"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should put error in response when format is incorrect', async () => {
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/permit_join', JSON.stringify({"value_not_good": false}));
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/permit_join',
JSON.stringify({"data":{},"status":"error","error": "No value given"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Coverage satisfaction', async () => {
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/random', JSON.stringify({"value": false}));
const device = zigbeeHerdsman.devices.bulb;
await zigbeeHerdsman.events.message({data: {onOff: 1}, cluster: 'genOnOff', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10});
await flushPromises();
});
it('Should allow a healthcheck', async () => {
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/health_check', '');
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/health_check',
JSON.stringify({"data":{"healthy": true},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should allow to remove device by string', async () => {
const device = zigbeeHerdsman.devices.bulb;
controller.state.state = {'0x000b57fffec6a5b3': {brightness: 100}};
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/device/remove', 'bulb');
await flushPromises();
expect(controller.state[device.ieeeAddr]).toBeUndefined();
expect(device.removeFromNetwork).toHaveBeenCalledTimes(1);
expect(device.removeFromDatabase).not.toHaveBeenCalled();
expect(settings.getDevice('bulb')).toBeNull();
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bridge/devices', expect.any(String), expect.any(Object), expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/remove',
JSON.stringify({"data":{"id": "bulb","block":false,"force":false},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
expect(settings.get().blocklist).toStrictEqual([]);
});
it('Should allow to remove device by object ID', async () => {
const device = zigbeeHerdsman.devices.bulb;
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/device/remove', JSON.stringify({id: "bulb"}));
await flushPromises();
expect(device.removeFromNetwork).toHaveBeenCalledTimes(1);
expect(device.removeFromDatabase).not.toHaveBeenCalled();
expect(settings.getDevice('bulb')).toBeNull();
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bridge/devices', expect.any(String), expect.any(Object), expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/remove',
JSON.stringify({"data":{"id": "bulb","block":false,"force":false},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should allow to force remove device', async () => {
const device = zigbeeHerdsman.devices.bulb;
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/device/remove', JSON.stringify({id: "bulb", force: true}));
await flushPromises();
expect(device.removeFromDatabase).toHaveBeenCalledTimes(1);
expect(device.removeFromNetwork).not.toHaveBeenCalled();
expect(settings.getDevice('bulb')).toBeNull();
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bridge/devices', expect.any(String), expect.any(Object), expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/remove',
JSON.stringify({"data":{"id": "bulb","block":false,"force":true},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should allow to block device', async () => {
const device = zigbeeHerdsman.devices.bulb;
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/device/remove', JSON.stringify({id: "bulb", block: true, force: true}));
await flushPromises();
expect(device.removeFromDatabase).toHaveBeenCalledTimes(1);
expect(settings.getDevice('bulb')).toBeNull();
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bridge/devices', expect.any(String), expect.any(Object), expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/remove',
JSON.stringify({"data":{"id": "bulb","block":true,"force":true},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
expect(settings.get().blocklist).toStrictEqual(["0x000b57fffec6a5b2"]);
});
it('Should allow to remove group', async () => {
const group = zigbeeHerdsman.groups.group_1;
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/group/remove', 'group_1');
await flushPromises();
expect(group.removeFromNetwork).toHaveBeenCalledTimes(1);
expect(settings.getGroup('group_1')).toBeNull();
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bridge/groups', expect.any(String), expect.any(Object), expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/group/remove',
JSON.stringify({"data":{"id": "group_1", "force": false},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should allow to force remove group', async () => {
const group = zigbeeHerdsman.groups.group_1;
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/group/remove', JSON.stringify({id: "group_1", force: true}));
await flushPromises();
expect(group.removeFromDatabase).toHaveBeenCalledTimes(1);
expect(settings.getGroup('group_1')).toBeNull();
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bridge/groups', expect.any(String), expect.any(Object), expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/group/remove',
JSON.stringify({"data":{"id": "group_1", "force": true},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should throw error on removing non-existing device', async () => {
const device = zigbeeHerdsman.devices.bulb;
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/device/remove', JSON.stringify({id: "non-existing-device"}));
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/remove',
JSON.stringify({"data":{},"status":"error","error":"Device 'non-existing-device' does not exist"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should throw error when remove device fails', async () => {
const device = zigbeeHerdsman.devices.bulb;
MQTT.publish.mockClear();
device.removeFromNetwork.mockImplementationOnce(() => {throw new Error('device timeout')})
MQTT.events.message('zigbee2mqtt/bridge/request/device/remove', JSON.stringify({id: "bulb"}));
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/remove',
JSON.stringify({"data":{},"status":"error","error":"Failed to remove device 'bulb' (block: false, force: false) (Error: device timeout)"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should allow rename device', async () => {
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/device/rename', JSON.stringify({from: 'bulb', to: 'bulb_new_name'}));
await flushPromises();
expect(settings.getDevice('bulb')).toBeNull();
expect(settings.getDevice('bulb_new_name')).toStrictEqual({"ID": "0x000b57fffec6a5b2", "friendly_name": "bulb_new_name", "friendlyName": "bulb_new_name", "retain": true});
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bridge/devices', expect.any(String), expect.any(Object), expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/rename',
JSON.stringify({"data":{"from":"bulb","to":"bulb_new_name"},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should allow rename group', async () => {
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/group/rename', JSON.stringify({from: 'group_1', to: 'group_new_name'}));
await flushPromises();
expect(settings.getGroup('group_1')).toBeNull();
expect(settings.getGroup('group_new_name')).toStrictEqual({"ID": 1, "devices": [], "friendly_name": "group_new_name", "friendlyName": "group_new_name", "optimistic": true, "retain": false});
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bridge/groups', expect.any(String), expect.any(Object), expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/group/rename',
JSON.stringify({"data":{"from":"group_1","to":"group_new_name"},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should throw error on invalid device rename payload', async () => {
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/device/rename', JSON.stringify({from_bla: 'bulb', to: 'bulb_new_name'}));
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/rename',
JSON.stringify({"data":{},"status":"error","error":"Invalid payload"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should throw error on non-existing device rename', async () => {
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/device/rename', JSON.stringify({from: 'bulb_not_existing', to: 'bulb_new_name'}));
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/rename',
JSON.stringify({"data":{},"status":"error","error":"Device 'bulb_not_existing' does not exist"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should allow to rename last joined device', async () => {
MQTT.publish.mockClear();
await zigbeeHerdsman.events.deviceJoined({device: zigbeeHerdsman.devices.bulb});
MQTT.events.message('zigbee2mqtt/bridge/request/device/rename', JSON.stringify({last: true, to: 'bulb_new_name'}));
await flushPromises();
expect(settings.getDevice('bulb')).toBeNull();
expect(settings.getDevice('bulb_new_name')).toStrictEqual({"ID": "0x000b57fffec6a5b2", "friendly_name": "bulb_new_name", "friendlyName": "bulb_new_name", "retain": true});
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bridge/devices', expect.any(String), expect.any(Object), expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/rename',
JSON.stringify({"data":{"from":"bulb","to":"bulb_new_name"},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should throw error when renaming last joined device but none has joined', async () => {
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/device/rename', JSON.stringify({last: true, to: 'bulb_new_name'}));
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/rename',
JSON.stringify({"data":{},"status":"error","error":"No device has joined since start"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should allow change device options', async () => {
MQTT.publish.mockClear();
expect(settings.getDevice('bulb')).toStrictEqual({"ID": "0x000b57fffec6a5b2", "friendly_name": "bulb", "friendlyName": "bulb", "retain": true});
MQTT.events.message('zigbee2mqtt/bridge/request/device/options', JSON.stringify({options: {retain: false, transition: 1}, id: 'bulb'}));
await flushPromises();
expect(settings.getDevice('bulb')).toStrictEqual({"ID": "0x000b57fffec6a5b2", "friendly_name": "bulb", "friendlyName": "bulb", "retain": false, "transition": 1});
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/options',
JSON.stringify({"data":{"from":{"retain": true},"to":{"retain": false,"transition":1}, "id":"bulb"},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should allow change group options', async () => {
MQTT.publish.mockClear();
expect(settings.getGroup('group_1')).toStrictEqual({"ID": 1, "devices": [], "friendly_name": "group_1", "retain": false, "friendlyName": "group_1", "optimistic": true});
MQTT.events.message('zigbee2mqtt/bridge/request/group/options', JSON.stringify({options: {retain: true, transition: 1}, id: 'group_1'}));
await flushPromises();
expect(settings.getGroup('group_1')).toStrictEqual({"ID": 1, "devices": [], "friendly_name": "group_1", "retain": true, "friendlyName": "group_1", "optimistic": true, "transition": 1});
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/group/options',
JSON.stringify({"data":{"from":{"optimistic": true,"retain": false},"to":{"optimistic": true,"retain": true,"transition":1}, "id":"group_1"},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should throw error on invalid device change options payload', async () => {
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/device/options', JSON.stringify({options_: {retain: true, transition: 1}, id: 'bulb'}));
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/options',
JSON.stringify({"data":{},"status":"error","error":"Invalid payload"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should allow to add group by string', async () => {
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/group/add', 'group_193');
await flushPromises();
expect(settings.getGroup('group_193')).toStrictEqual({"ID": 3, "devices": [], "friendly_name": "group_193", "friendlyName": "group_193", "optimistic": true});
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bridge/groups', expect.any(String), expect.any(Object), expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/group/add',
JSON.stringify({"data":{"friendly_name":"group_193","id": 3},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should allow to add group with ID', async () => {
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/group/add', JSON.stringify({friendly_name: "group_193", id: 9}));
await flushPromises();
expect(settings.getGroup('group_193')).toStrictEqual({"ID": 9, "devices": [], "friendly_name": "group_193", "friendlyName": "group_193", "optimistic": true});
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bridge/groups', expect.any(String), expect.any(Object), expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/group/add',
JSON.stringify({"data":{"friendly_name":"group_193","id": 9},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should throw error when add with invalid payload', async () => {
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/group/add', JSON.stringify({friendly_name9: "group_193"}));
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/group/add',
JSON.stringify({"data":{},"status":"error","error":"Invalid payload"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should allow to set last_seen', async () => {
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/config/last_seen', 'ISO_8601');
await flushPromises();
expect(settings.get().advanced.last_seen).toBe('ISO_8601');
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/config/last_seen',
JSON.stringify({"data":{"value":"ISO_8601"},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should fail to set last_seen when invalid type', async () => {
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/config/last_seen', 'invalid_one');
await flushPromises();
expect(settings.get().advanced.last_seen).toBe('disable');
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/config/last_seen',
JSON.stringify({"data":{},"status":"error","error":"'invalid_one' is not an allowed value, allowed: disable,ISO_8601,epoch,ISO_8601_local"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should allow to set elapsed', async () => {
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/config/elapsed', 'true');
await flushPromises();
expect(settings.get().advanced.elapsed).toBe(true);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/config/elapsed',
JSON.stringify({"data":{"value":true},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should fail to set last_seen when invalid type', async () => {
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/config/elapsed', 'not_valid');
await flushPromises();
expect(settings.get().advanced.elapsed).toBe(false);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/config/elapsed',
JSON.stringify({"data":{},"status":"error","error":"'not_valid' is not an allowed value, allowed: true,false"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should allow to set log level', async () => {
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/config/log_level', 'debug');
await flushPromises();
expect(logger.getLevel()).toBe('debug');
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bridge/info', expect.any(String), expect.any(Object), expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/config/log_level',
JSON.stringify({"data":{"value":'debug'},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should fail to set log level when invalid type', async () => {
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/config/log_level', 'not_valid');
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/config/log_level',
JSON.stringify({"data":{},"status":"error","error":"'not_valid' is not an allowed value, allowed: error,warn,info,debug"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should allow to touchlink factory reset (succeeds)', async () => {
MQTT.publish.mockClear();
zigbeeHerdsman.touchlinkFactoryReset.mockClear();
zigbeeHerdsman.touchlinkFactoryReset.mockReturnValueOnce(true);
MQTT.events.message('zigbee2mqtt/bridge/request/touchlink/factory_reset', '');
await flushPromises();
expect(zigbeeHerdsman.touchlinkFactoryReset).toHaveBeenCalledTimes(1);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/touchlink/factory_reset',
JSON.stringify({"data":{},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should allow to touchlink factory reset (fails)', async () => {
MQTT.publish.mockClear();
zigbeeHerdsman.touchlinkFactoryReset.mockClear();
zigbeeHerdsman.touchlinkFactoryReset.mockReturnValueOnce(false);
MQTT.events.message('zigbee2mqtt/bridge/request/touchlink/factory_reset', '');
await flushPromises();
expect(zigbeeHerdsman.touchlinkFactoryReset).toHaveBeenCalledTimes(1);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/touchlink/factory_reset',
JSON.stringify({"data":{},"status":"error","error":"Failed to factory reset device through Touchlink"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
});
+223
View File
@@ -0,0 +1,223 @@
const data = require('./stub/data');
const logger = require('./stub/logger');
const zigbeeHerdsman = require('./stub/zigbeeHerdsman');
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];
describe('Configure', () => {
let controller;
expectRemoteConfigured = () => {
const device = zigbeeHerdsman.devices.remote;
const endpoint1 = device.getEndpoint(1);
expect(endpoint1.bind).toHaveBeenCalledTimes(2);
expect(endpoint1.bind).toHaveBeenCalledWith('genOnOff', this.coordinatorEndoint);
expect(endpoint1.bind).toHaveBeenCalledWith('genLevelCtrl', this.coordinatorEndoint);
const endpoint2 = device.getEndpoint(2);
expect(endpoint2.write).toHaveBeenCalledTimes(1);
expect(endpoint2.write).toHaveBeenCalledWith("genBasic", {"49": {"type": 25, "value": 11}}, {"disableDefaultResponse": true, "manufacturerCode": 4107});
expect(device.meta.configured).toBe(1);
}
expectRemoteNotConfigured = () => {
const device = zigbeeHerdsman.devices.remote;
const endpoint1 = device.getEndpoint(1);
expect(endpoint1.bind).toHaveBeenCalledTimes(0);
}
mockClear = (device) => {
for (const endpoint of device.endpoints) {
endpoint.read.mockClear();
endpoint.write.mockClear();
endpoint.configureReporting.mockClear();
endpoint.bind.mockClear();
}
}
beforeEach(async () => {
jest.useRealTimers();
data.writeDefaultConfiguration();
settings._reRead();
data.writeEmptyState();
controller = new Controller();
await controller.start();
mocksClear.forEach((m) => m.mockClear());
await flushPromises();
this.coordinatorEndoint = zigbeeHerdsman.devices.coordinator.getEndpoint(1);
});
it('Should configure on startup', async () => {
expectRemoteConfigured();
});
it('Should re-configure when device rejoins', async () => {
expectRemoteConfigured();
const device = zigbeeHerdsman.devices.remote;
const endpoint = device.getEndpoint(1);
await flushPromises();
mockClear(device);
const payload = {device};
zigbeeHerdsman.events.deviceJoined(payload);
await flushPromises();
expectRemoteConfigured();
});
it('Should not configure twice', async () => {
expectRemoteConfigured();
const device = zigbeeHerdsman.devices.remote;
const endpoint = device.getEndpoint(1);
mockClear(device);
const payload = {data: {zclVersion: 1}, cluster: 'genBasic', device, endpoint, type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(endpoint.bind).toHaveBeenCalledTimes(0);
});
it('Should configure on zigbee message when not configured yet', async () => {
const device = zigbeeHerdsman.devices.remote;
delete device.meta.configured;
const endpoint = device.getEndpoint(1);
mockClear(device);
const payload = {data: {zclVersion: 1}, cluster: 'genBasic', device, endpoint, type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expectRemoteConfigured();
});
it('Should allow to configure via MQTT', async () => {
expectRemoteConfigured();
mockClear(zigbeeHerdsman.devices.remote);
expectRemoteNotConfigured();
await MQTT.events.message('zigbee2mqtt/bridge/request/device/configure', 'remote');
await flushPromises();
expectRemoteConfigured();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/configure',
JSON.stringify({"data":{"id": "remote"},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Fail to configure via MQTT when device does not exist', async () => {
await MQTT.events.message('zigbee2mqtt/bridge/request/device/configure', JSON.stringify({id: "not_existing_device"}));
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/configure',
JSON.stringify({"data":{"id": "not_existing_device"},"status":"error","error": "Device 'not_existing_device' does not exist"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Fail to configure via MQTT when configure fails', async () => {
zigbeeHerdsman.devices.remote.getEndpoint(1).bind.mockImplementationOnce(async () => {throw new Error('Bind timeout after 10s')});
await MQTT.events.message('zigbee2mqtt/bridge/request/device/configure', JSON.stringify({id: "remote"}));
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/configure',
JSON.stringify({"data":{"id": "remote"},"status":"error","error": "Failed to configure (Bind timeout after 10s)"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Fail to configure via MQTT when device has no configure', async () => {
await MQTT.events.message('zigbee2mqtt/bridge/request/device/configure', JSON.stringify({id: "bulb", transaction: 20}));
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/configure',
JSON.stringify({"data":{"id": "bulb"},"status":"error","error": "Device 'bulb' cannot be configured","transaction":20}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Legacy api: Should allow to reconfigure manually', async () => {
mockClear(zigbeeHerdsman.devices.remote);
expectRemoteNotConfigured();
await MQTT.events.message('zigbee2mqtt/bridge/configure', 'remote');
await flushPromises();
expectRemoteConfigured();
});
it('Legacy api: Shouldnt manually reconfigure when device does not exist', async () => {
await MQTT.events.message('zigbee2mqtt/bridge/configure', 'remote_random_non_existing');
await flushPromises();
expect(logger.error).toHaveBeenCalledWith(`Device 'remote_random_non_existing' does not exist`);
});
it('Legacy api: Should skip reconfigure when device does not require this', async () => {
await MQTT.events.message('zigbee2mqtt/bridge/configure', 'bulb');
await flushPromises();
expect(logger.warn).toHaveBeenCalledWith(`Skipping configure of 'bulb', device does not require this.`)
});
it('Should not configure when interviewing', async () => {
const device = zigbeeHerdsman.devices.remote;
delete device.meta.configured;
device.interviewing = true;
const endpoint = device.getEndpoint(1);
mockClear(device);
const payload = {data: {zclVersion: 1}, cluster: 'genBasic', device, endpoint, type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expectRemoteNotConfigured();
device.interviewing = false;
});
it('Should configure when not interviewCompleted', async () => {
const device = zigbeeHerdsman.devices.remote;
delete device.meta.configured;
device.interviewCompleted = false;
const endpoint = device.getEndpoint(1);
mockClear(device);
const payload = {data: {zclVersion: 1}, cluster: 'genBasic', device, endpoint, type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expectRemoteConfigured();
device.interviewCompleted = true;
});
it('Should not configure when already configuring', async () => {
const device = zigbeeHerdsman.devices.remote;
delete device.meta.configured;
const endpoint = device.getEndpoint(1);
endpoint.bind.mockImplementationOnce(async () => await wait(500));
mockClear(device);
const payload = {data: {zclVersion: 1}, cluster: 'genBasic', device, endpoint, type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(endpoint.bind).toHaveBeenCalledTimes(1);
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(endpoint.bind).toHaveBeenCalledTimes(1);
});
it('Should configure max 3 times when fails', async () => {
controller.extensions.find((e) => e.constructor.name === 'Configure').attempts = {};
const device = zigbeeHerdsman.devices.remote;
delete device.meta.configured;
const endpoint = device.getEndpoint(1);
mockClear(device);
endpoint.bind.mockImplementationOnce(async () => {throw new Error('BLA')});
const payload = {data: {zclVersion: 1}, cluster: 'genBasic', device, endpoint, type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
endpoint.bind.mockImplementationOnce(async () => {throw new Error('BLA')});
await zigbeeHerdsman.events.message(payload);
await flushPromises();
endpoint.bind.mockImplementationOnce(async () => {throw new Error('BLA')});
await zigbeeHerdsman.events.message(payload);
await flushPromises();
endpoint.bind.mockImplementationOnce(async () => {throw new Error('BLA')});
await zigbeeHerdsman.events.message(payload);
await flushPromises();
endpoint.bind.mockImplementationOnce(async () => {throw new Error('BLA')});
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(endpoint.bind).toHaveBeenCalledTimes(3);
});
});
+598
View File
@@ -0,0 +1,598 @@
const data = require('./stub/data');
const logger = require('./stub/logger');
const zigbeeHerdsman = require('./stub/zigbeeHerdsman');
const MQTT = require('./stub/mqtt');
const path = require('path');
const mockExit = jest.spyOn(process, 'exit').mockImplementation(() => {});
const settings = require('../lib/util/settings');
const Controller = require('../lib/controller');
const flushPromises = () => new Promise(setImmediate);
const tmp = require('tmp');
const mocksClear = [
zigbeeHerdsman.permitJoin, mockExit, MQTT.end, zigbeeHerdsman.stop, logger.debug,
MQTT.publish, MQTT.connect, zigbeeHerdsman.devices.bulb_color.removeFromNetwork,
zigbeeHerdsman.devices.bulb.removeFromNetwork, logger.error,
];
const fs = require('fs');
describe('Controller', () => {
let controller;
beforeEach(() => {
zigbeeHerdsman.returnDevices.splice(0);
controller = new Controller();
mocksClear.forEach((m) => m.mockClear());
data.writeDefaultConfiguration();
settings._reRead();
data.writeDefaultState();
});
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),adapter: {concurrent: null}, "serialPort":{"baudRate":undefined,"rtscts":undefined,"path":"/dev/dummy"}});
expect(zigbeeHerdsman.start).toHaveBeenCalledTimes(1);
expect(zigbeeHerdsman.setLED).toHaveBeenCalledTimes(0);
expect(zigbeeHerdsman.setTransmitPower).toHaveBeenCalledTimes(0);
expect(zigbeeHerdsman.permitJoin).toHaveBeenCalledTimes(1);
expect(zigbeeHerdsman.permitJoin).toHaveBeenCalledWith(true);
expect(logger.info).toHaveBeenCalledWith(`Currently ${Object.values(zigbeeHerdsman.devices).length - 1} devices are joined:`)
expect(logger.info).toHaveBeenCalledWith('bulb (0x000b57fffec6a5b2): LED1545G12 - IKEA TRADFRI LED bulb E26/E27 980 lumen, dimmable, white spectrum, opal white (Router)');
expect(logger.info).toHaveBeenCalledWith('remote (0x0017880104e45517): 324131092621 - Philips Hue dimmer switch (EndDevice)');
expect(logger.info).toHaveBeenCalledWith('0x0017880104e45518 (0x0017880104e45518): Not supported (EndDevice)');
expect(MQTT.connect).toHaveBeenCalledTimes(1);
expect(MQTT.connect).toHaveBeenCalledWith("mqtt://localhost", {"will": {"payload": "offline", "retain": true, "topic": "zigbee2mqtt/bridge/state"}});
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bulb', '{"state":"ON","brightness":50,"color_temp":370,"linkquality":99}',{ retain: true, qos: 0 }, expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/remote', '{"brightness":255}', { retain: true, qos: 0 }, expect.any(Function));
});
it('Start controller when permit join fails', async () => {
zigbeeHerdsman.permitJoin.mockImplementationOnce(() => {throw new Error("failed!")});
await controller.start();
expect(zigbeeHerdsman.permitJoin).toHaveBeenCalledTimes(1);
expect(MQTT.connect).toHaveBeenCalledTimes(1);
});
it('Start controller with specific MQTT settings', async () => {
const ca = tmp.fileSync().name;
fs.writeFileSync(ca, "ca");
const key = tmp.fileSync().name;
fs.writeFileSync(key, "key");
const cert = tmp.fileSync().name;
fs.writeFileSync(cert, "cert");
const configuration = {
base_topic: "zigbee2mqtt",
server: "mqtt://localhost",
keepalive: 30,
ca, cert, key,
password: 'pass',
user: 'user1',
client_id: 'my_client_id',
reject_unauthorized: false,
version: 5,
}
settings.set(['mqtt'], configuration)
await controller.start();
await flushPromises();
expect(MQTT.connect).toHaveBeenCalledTimes(1);
const expected = {
"will": {"payload": "offline", "retain": true, "topic": "zigbee2mqtt/bridge/state"},
keepalive: 30,
ca: Buffer.from([99, 97]),
key: Buffer.from([107, 101, 121]),
cert: Buffer.from([99, 101, 114, 116]),
password: 'pass',
username: 'user1',
clientId: 'my_client_id',
rejectUnauthorized: false,
protocolVersion: 5,
}
expect(MQTT.connect).toHaveBeenCalledWith("mqtt://localhost", expected);
});
it('Should generate network_key when set to GENERATE', async () => {
settings.set(['advanced', 'network_key'], 'GENERATE');
await controller.start();
await flushPromises();
expect(zigbeeHerdsman.constructor.mock.calls[0][0].network.networkKey.length).toStrictEqual(16);
expect(data.read().advanced.network_key.length).toStrictEqual(16);
});
it('Start controller should publish cached states', async () => {
data.writeDefaultState();
await controller.start();
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bulb", `{"state":"ON","brightness":50,"color_temp":370,"linkquality":99}`, {"qos": 0, "retain": true}, expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/remote", `{"brightness":255}`, {"qos": 0, "retain": true}, expect.any(Function));
});
it('Start controller should not publish cached states when disabled', async () => {
settings.set(['advanced', 'cache_state_send_on_startup'], false);
data.writeDefaultState();
await controller.start();
await flushPromises();
const publishedTopics = MQTT.publish.mock.calls.map(m => m[0]);
expect(publishedTopics).toEqual(expect.not.arrayContaining(["zigbee2mqtt/bulb", "zigbee2mqtt/remote"]));
});
it('Start controller should not publish cached states when cache_state is false', async () => {
settings.set(['advanced', 'cache_state'], false);
data.writeDefaultState();
await controller.start();
await flushPromises();
expect(MQTT.publish).not.toHaveBeenCalledWith("zigbee2mqtt/bulb", `{"state":"ON","brightness":50,"color_temp":370,"linkquality":99}`, {"qos": 0, "retain": true}, expect.any(Function));
expect(MQTT.publish).not.toHaveBeenCalledWith("zigbee2mqtt/remote", `{"brightness":255}`, {"qos": 0, "retain": true}, expect.any(Function));
});
it('Log when MQTT client is unavailable', async () => {
jest.useFakeTimers();
await controller.start();
await flushPromises();
logger.error.mockClear();
controller.mqtt.client.reconnecting = true;
jest.advanceTimersByTime(11 * 1000);
await flushPromises();
expect(logger.error).toHaveBeenCalledTimes(1);
expect(logger.error).toHaveBeenCalledWith("Not connected to MQTT server!");
controller.mqtt.client.reconnecting = false;
});
it('Dont publish to mqtt when client is unavailable', async () => {
await controller.start();
await flushPromises();
logger.error.mockClear();
controller.mqtt.client.reconnecting = true;
await controller.publishEntityState('bulb', {state: 'ON', brightness: 50, color_temp: 370, color: {r: 100, g: 50, b: 10}, dummy: {1: 'yes', 2: 'no'}});
await flushPromises();
expect(logger.error).toHaveBeenCalledTimes(2);
expect(logger.error).toHaveBeenCalledWith("Not connected to MQTT server!");
expect(logger.error).toHaveBeenCalledWith("Cannot send message: topic: 'zigbee2mqtt/bulb', payload: '{\"state\":\"ON\",\"brightness\":50,\"color_temp\":370,\"linkquality\":99,\"color\":{\"r\":100,\"g\":50,\"b\":10},\"dummy\":{\"1\":\"yes\",\"2\":\"no\"}}");
controller.mqtt.client.reconnecting = false;
});
it('Load empty state when state file does not exist', async () => {
data.removeState();
await controller.start();
await flushPromises();
expect(controller.state.state).toStrictEqual({});
});
it('Should remove device not on passlist on startup', async () => {
settings.set(['passlist'], [zigbeeHerdsman.devices.bulb_color.ieeeAddr]);
await controller.start();
await flushPromises();
expect(zigbeeHerdsman.devices.bulb_color.removeFromNetwork).toHaveBeenCalledTimes(0);
expect(zigbeeHerdsman.devices.bulb.removeFromNetwork).toHaveBeenCalledTimes(1);
});
it('Should remove non whitelisted devices on startup', async () => {
settings.set(['whitelist'], [zigbeeHerdsman.devices.bulb_color.ieeeAddr]);
await controller.start();
await flushPromises();
expect(zigbeeHerdsman.devices.bulb_color.removeFromNetwork).toHaveBeenCalledTimes(0);
expect(zigbeeHerdsman.devices.bulb.removeFromNetwork).toHaveBeenCalledTimes(1);
});
it('Should remove device on blocklist on startup', async () => {
settings.set(['blocklist'], [zigbeeHerdsman.devices.bulb_color.ieeeAddr]);
await controller.start();
await flushPromises();
expect(zigbeeHerdsman.devices.bulb_color.removeFromNetwork).toHaveBeenCalledTimes(1);
expect(zigbeeHerdsman.devices.bulb.removeFromNetwork).toHaveBeenCalledTimes(0);
});
it('Should remove banned devices on startup', async () => {
settings.set(['ban'], [zigbeeHerdsman.devices.bulb_color.ieeeAddr]);
await controller.start();
await flushPromises();
expect(zigbeeHerdsman.devices.bulb_color.removeFromNetwork).toHaveBeenCalledTimes(1);
expect(zigbeeHerdsman.devices.bulb.removeFromNetwork).toHaveBeenCalledTimes(0);
});
it('Start controller fails', async () => {
zigbeeHerdsman.start.mockImplementationOnce(() => {throw new Error('failed')});
await controller.start();
expect(mockExit).toHaveBeenCalledTimes(1);
});
it('Start controller with permit join true', async () => {
settings.set(['permit_join'], false);
await controller.start();
expect(zigbeeHerdsman.permitJoin).toHaveBeenCalledTimes(1);
expect(zigbeeHerdsman.permitJoin).toHaveBeenCalledWith(false);
});
it('Refuse to start when configuration.yaml is invalid', async () => {
settings.set(['permit_join'], 'invalid');
await controller.start();
expect(logger.error).toHaveBeenCalledWith('Refusing to start, configuration.yaml is not valid, found the following errors:');
expect(logger.error).toHaveBeenCalledWith('\t - permit_join should be boolean');
expect(mockExit).toHaveBeenCalledTimes(1);
expect(mockExit).toHaveBeenCalledWith(1);
});
it('Start controller with disable_led', async () => {
settings.set(['serial', 'disable_led'], true);
await controller.start();
expect(zigbeeHerdsman.setLED).toHaveBeenCalledTimes(1);
expect(zigbeeHerdsman.setLED).toHaveBeenCalledWith(false);
});
it('Start controller with transmit power', async () => {
settings.set(['experimental', 'transmit_power'], 14);
await controller.start();
expect(zigbeeHerdsman.setTransmitPower).toHaveBeenCalledTimes(1);
expect(zigbeeHerdsman.setTransmitPower).toHaveBeenCalledWith(14);
});
it('Start controller and stop', async () => {
await controller.start();
await controller.stop();
expect(MQTT.end).toHaveBeenCalledTimes(1);
expect(zigbeeHerdsman.stop).toHaveBeenCalledTimes(1);
expect(mockExit).toHaveBeenCalledTimes(1);
expect(mockExit).toHaveBeenCalledWith(0);
});
it('Start controller and stop', async () => {
zigbeeHerdsman.stop.mockImplementationOnce(() => {throw new Error('failed')})
await controller.start();
await controller.stop();
expect(MQTT.end).toHaveBeenCalledTimes(1);
expect(zigbeeHerdsman.stop).toHaveBeenCalledTimes(1);
expect(mockExit).toHaveBeenCalledTimes(1);
expect(mockExit).toHaveBeenCalledWith(1);
});
it('Start controller adapter disconnects', async () => {
zigbeeHerdsman.stop.mockImplementationOnce(() => {throw new Error('failed')})
await controller.start();
await zigbeeHerdsman.events.adapterDisconnected();
await flushPromises();
expect(MQTT.end).toHaveBeenCalledTimes(1);
expect(zigbeeHerdsman.stop).toHaveBeenCalledTimes(1);
expect(mockExit).toHaveBeenCalledTimes(1);
expect(mockExit).toHaveBeenCalledWith(1);
});
it('Handle mqtt message', async () => {
await controller.start();
logger.debug.mockClear();
await MQTT.events.message('dummytopic', 'dummymessage');
expect(logger.debug).toHaveBeenCalledWith("Received MQTT message on 'dummytopic' with data 'dummymessage'")
});
it('On zigbee event message', async () => {
await controller.start();
const device = zigbeeHerdsman.devices.bulb;
const payload = {device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10, cluster: 'genBasic', data: {modelId: device.modelID}};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(logger.debug).toHaveBeenCalledWith(`Received Zigbee message from 'bulb', type 'attributeReport', cluster 'genBasic', data '{"modelId":"TRADFRI bulb E27 WS opal 980lm"}' from endpoint 1`);
});
it('On zigbee event message with group ID', async () => {
await controller.start();
const device = zigbeeHerdsman.devices.bulb;
const payload = {device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10, groupID: 0, cluster: 'genBasic', data: {modelId: device.modelID}};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
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);
await flushPromises();
expect(settings.getDevice(device.ieeeAddr)).toStrictEqual({"ID": "0x0017880104e45519", "friendlyName": "0x0017880104e45519", "friendly_name": "0x0017880104e45519"});
});
it('On zigbee deviceJoined', async () => {
await controller.start();
const device = zigbeeHerdsman.devices.bulb;
const payload = {device};
await zigbeeHerdsman.events.deviceJoined(payload);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bridge/log", '{"type":"device_connected","message":{"friendly_name":"bulb"}}', {"retain": false, qos: 0}, expect.any(Function));
});
it('acceptJoiningDeviceHandler reject device on blocklist', async () => {
await controller.start();
const device = zigbeeHerdsman.devices.bulb;
settings.set(['blocklist'], [device.ieeeAddr]);
const handler = zigbeeHerdsman.constructor.mock.calls[0][0].acceptJoiningDeviceHandler;
expect(await handler(device.ieeeAddr)).toBe(false);
});
it('acceptJoiningDeviceHandler accept device not on blocklist', async () => {
await controller.start();
const device = zigbeeHerdsman.devices.bulb;
settings.set(['blocklist'], ['123']);
const handler = zigbeeHerdsman.constructor.mock.calls[0][0].acceptJoiningDeviceHandler;
expect(await handler(device.ieeeAddr)).toBe(true);
});
it('acceptJoiningDeviceHandler accept device on passlist', async () => {
await controller.start();
const device = zigbeeHerdsman.devices.bulb;
settings.set(['passlist'], [device.ieeeAddr]);
const handler = zigbeeHerdsman.constructor.mock.calls[0][0].acceptJoiningDeviceHandler;
expect(await handler(device.ieeeAddr)).toBe(true);
});
it('acceptJoiningDeviceHandler reject device not in passlist', async () => {
await controller.start();
const device = zigbeeHerdsman.devices.bulb;
settings.set(['passlist'], ['123']);
const handler = zigbeeHerdsman.constructor.mock.calls[0][0].acceptJoiningDeviceHandler;
expect(await handler(device.ieeeAddr)).toBe(false);
});
it('acceptJoiningDeviceHandler should prefer passlist above blocklist', async () => {
await controller.start();
const device = zigbeeHerdsman.devices.bulb;
settings.set(['passlist'], [device.ieeeAddr]);
settings.set(['blocklist'], [device.ieeeAddr]);
const handler = zigbeeHerdsman.constructor.mock.calls[0][0].acceptJoiningDeviceHandler;
expect(await handler(device.ieeeAddr)).toBe(true);
});
it('acceptJoiningDeviceHandler accept when not on blocklist and passlist', async () => {
await controller.start();
const device = zigbeeHerdsman.devices.bulb;
const handler = zigbeeHerdsman.constructor.mock.calls[0][0].acceptJoiningDeviceHandler;
expect(await handler(device.ieeeAddr)).toBe(true);
});
it('Shouldnt crash when two device join events are received', async () => {
await controller.start();
const device = zigbeeHerdsman.devices.bulb;
const payload = {device};
zigbeeHerdsman.events.deviceJoined(payload);
zigbeeHerdsman.events.deviceJoined(payload);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bridge/log", '{"type":"device_connected","message":{"friendly_name":"bulb"}}', {"retain": false, qos: 0}, expect.any(Function));
});
it('On zigbee deviceInterview started', async () => {
await controller.start();
const device = zigbeeHerdsman.devices.bulb;
const payload = {device, status: 'started'};
await zigbeeHerdsman.events.deviceInterview(payload);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bridge/log', '{"type":"pairing","message":"interview_started","meta":{"friendly_name":"bulb"}}', { retain: false, qos: 0 }, expect.any(Function));
});
it('On zigbee deviceInterview failed', async () => {
await controller.start();
const device = zigbeeHerdsman.devices.bulb;
const payload = {device, status: 'failed'};
await zigbeeHerdsman.events.deviceInterview(payload);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bridge/log', '{"type":"pairing","message":"interview_failed","meta":{"friendly_name":"bulb"}}', { retain: false, qos: 0 }, expect.any(Function));
});
it('On zigbee deviceInterview successful supported', async () => {
await controller.start();
const device = zigbeeHerdsman.devices.bulb;
const payload = {device, status: 'successful'};
await zigbeeHerdsman.events.deviceInterview(payload);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bridge/log', '{"type":"pairing","message":"interview_successful","meta":{"friendly_name":"bulb","model":"LED1545G12","vendor":"IKEA","description":"TRADFRI LED bulb E26/E27 980 lumen, dimmable, white spectrum, opal white","supported":true}}', { retain: false, qos: 0 }, expect.any(Function));
});
it('On zigbee deviceInterview successful not supported', async () => {
await controller.start();
const device = zigbeeHerdsman.devices.unsupported;
const payload = {device, status: 'successful'};
await zigbeeHerdsman.events.deviceInterview(payload);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bridge/log', '{"type":"pairing","message":"interview_successful","meta":{"friendly_name":"0x0017880104e45518","supported":false}}', { retain: false, qos: 0 }, expect.any(Function));
});
it('On zigbee event device announce', async () => {
await controller.start();
const device = zigbeeHerdsman.devices.bulb;
const payload = {device};
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 () => {
await controller.start();
zigbeeHerdsman.returnDevices.push('0x00124b00120144ae');
settings.set(['devices'], {})
MQTT.publish.mockClear();
const device = zigbeeHerdsman.devices.bulb;
const payload = {ieeeAddr: device.ieeeAddr};
await zigbeeHerdsman.events.deviceLeave(payload);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bridge/log', '{"type":"device_removed","message":"left_network","meta":{"friendly_name":"0x000b57fffec6a5b2"}}', { retain: false, qos: 0}, expect.any(Function));
});
it('On zigbee event device leave (removed from database and NOT settings)', async () => {
await controller.start();
zigbeeHerdsman.returnDevices.push('0x00124b00120144ae');
const device = zigbeeHerdsman.devices.bulb;
MQTT.publish.mockClear();
const payload = {ieeeAddr: device.ieeeAddr};
await zigbeeHerdsman.events.deviceLeave(payload);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bridge/log', '{"type":"device_removed","message":"left_network","meta":{"friendly_name":"0x000b57fffec6a5b2"}}', { retain: false, qos: 0}, expect.any(Function));
});
it('Publish entity state attribute output', async () => {
await controller.start();
settings.set(['experimental', 'output'], 'attribute');
MQTT.publish.mockClear();
await controller.publishEntityState('bulb', {state: 'ON', brightness: 50, color_temp: 370, color: {r: 100, g: 50, b: 10}, dummy: {1: 'yes', 2: 'no'}});
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bulb/state", "ON", {"qos": 0, "retain": true}, expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bulb/brightness", "50", {"qos": 0, "retain": true}, expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bulb/color_temp", "370", {"qos": 0, "retain": true}, expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bulb/color", '100,50,10', {"qos": 0, "retain": true}, expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bulb/dummy-1", 'yes', {"qos": 0, "retain": true}, expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bulb/dummy-2", 'no', {"qos": 0, "retain": true}, expect.any(Function));
});
it('Publish entity state attribute_json output', async () => {
await controller.start();
settings.set(['experimental', 'output'], 'attribute_and_json');
MQTT.publish.mockClear();
await controller.publishEntityState('bulb', {state: 'ON', brightness: 200, color_temp: 370, linkquality: 99});
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(5);
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/color_temp", "370", {"qos": 0, "retain": true}, expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bulb/linkquality", "99", {"qos": 0, "retain": true}, expect.any(Function));
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);
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,"device":{"friendlyName":"bulb","model":"LED1545G12","ieeeAddr":"0x000b57fffec6a5b2","networkAddress":40369,"type":"Router","manufacturerID":4476,"powerSource":"Mains (single phase)","dateCode":null}}', {"qos": 0, "retain": true}, expect.any(Function));
// Unsupported device should have model "unknown"
await controller.publishEntityState('unsupported2', {state: 'ON'});
await flushPromises();
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();
MQTT.publish.mockClear();
await controller.publishEntityState('bulb', {});
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(0);
});
it('Should allow to disable state persistency', async () => {
settings.set(['advanced', 'cache_state_persistent'], false);
data.removeState();
await controller.start();
MQTT.publish.mockClear();
await controller.publishEntityState('bulb', {state: 'ON'});
await controller.publishEntityState('bulb', {brightness: 200});
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(2);
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bulb", JSON.stringify({state: "ON"}), {"qos": 0, "retain": true}, expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bulb", JSON.stringify({state: "ON", brightness: 200}), {"qos": 0, "retain": true}, expect.any(Function));
await controller.stop();
expect(data.stateExists()).toBeFalsy();
});
it('Publish should not cache when set', async () => {
settings.set(['advanced', 'cache_state'], false);
data.writeEmptyState();
await controller.start();
MQTT.publish.mockClear();
await controller.publishEntityState('bulb', {state: 'ON'});
await controller.publishEntityState('bulb', {brightness: 200});
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(2);
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));
});
it('Publish should not do anything for unknown entity', async () => {
await controller.start();
MQTT.publish.mockClear();
await controller.publishEntityState('bulb-unknown', {brightness: 200});
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(0);
});
it('Should start when state is corrupted', async () => {
fs.writeFileSync(path.join(data.mockDir, 'state.json'), 'corrupted');
await controller.start();
await flushPromises();
expect(controller.state.state).toStrictEqual({});
});
it('Load user extension', async () => {
const extensionPath = path.join(data.mockDir, 'extension');
fs.mkdirSync(extensionPath);
fs.copyFileSync(path.join(__dirname, 'assets', 'exampleExtension.js'), path.join(extensionPath, 'exampleExtension.js'))
controller = new Controller();
await controller.start();
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/example/extension', 'test', { retain: false, qos: 0 }, expect.any(Function));
});
});
+13 -10
View File
@@ -1,23 +1,26 @@
/* global describe, it */
const chai = require('chai');
const proxyquire = require('proxyquire').noPreserveCache();
const data = () => proxyquire('../lib/util/data.js', {});
const logger = require('./stub/logger');
const data = require('../lib/util/data.js');
const path = require('path');
const tmp = require('tmp');
const fs = require('fs');
describe('Data', () => {
describe('Get path', () => {
it('Should return correct path', () => {
const expected = path.normalize(path.join(__dirname, '..', 'data'));
const actual = data().getPath();
chai.assert.strictEqual(actual, expected);
const actual = data.getPath();
expect(actual).toBe(expected);
});
it('Should return correct path when ZIGBEE2MQTT_DATA set', () => {
const expected = path.join('var', 'zigbee2mqtt');
const expected = tmp.dirSync().name;
process.env.ZIGBEE2MQTT_DATA = expected;
const actual = data().getPath();
chai.assert.strictEqual(actual, expected);
data._reload();
const actual = data.getPath();
expect(actual).toBe(expected);
expect(data.joinPath('test')).toStrictEqual(path.join(expected, 'test'));
delete process.env.ZIGBEE2MQTT_DATA;
data._reload();
});
});
});
+115
View File
@@ -0,0 +1,115 @@
const data = require('./stub/data');
const logger = require('./stub/logger');
const zigbeeHerdsman = require('./stub/zigbeeHerdsman');
const MQTT = require('./stub/mqtt');
const mockExit = jest.spyOn(process, 'exit').mockImplementation(() => {});
const zigbeeHerdsmanConverters = require('zigbee-herdsman-converters');
const settings = require('../lib/util/settings');
const Controller = require('../lib/controller');
const flushPromises = () => new Promise(setImmediate);
const path = require('path');
const fs = require('fs');
zigbeeHerdsmanConverters.addDeviceDefinition = jest.fn();
const mocksClear = [zigbeeHerdsmanConverters.addDeviceDefinition, zigbeeHerdsman.permitJoin,
mockExit, MQTT.end, zigbeeHerdsman.stop, logger.debug,
MQTT.publish, MQTT.connect, zigbeeHerdsman.devices.bulb_color.removeFromNetwork,
zigbeeHerdsman.devices.bulb.removeFromNetwork, logger.error,
];
jest.mock(
'mock-external-converter-module', () => {
return {
mock: true
};
}, {
virtual: true
});
jest.mock(
'mock-multiple-external-converter-module', () => {
return [{
mock: 1
}, {
mock: 2
}];
}, {
virtual: true
});
describe('Loads external converters', () => {
let controller;
beforeEach(async () => {
jest.useRealTimers();
await flushPromises();
mocksClear.forEach((m) => m.mockClear());
data.writeDefaultConfiguration();
data.writeEmptyState();
settings._reRead();
});
it('Does not load external converters', async () => {
settings.set(['external_converters'], []);
controller = new Controller();
await controller.start();
await flushPromises();
expect(zigbeeHerdsmanConverters.addDeviceDefinition).toHaveBeenCalledTimes(0);
});
it('Loads external converters', async () => {
fs.copyFileSync(path.join(__dirname, 'assets', 'mock-external-converter.js'), path.join(data.mockDir, 'mock-external-converter.js'));
const devicesCount = zigbeeHerdsman.devices.lenght;
settings.set(['external_converters'], ['mock-external-converter.js']);
controller = new Controller();
await controller.start();
await flushPromises();
expect(zigbeeHerdsmanConverters.addDeviceDefinition).toHaveBeenCalledTimes(1);
expect(zigbeeHerdsmanConverters.addDeviceDefinition).toHaveBeenCalledWith({
mock: true
});
});
it('Loads multiple external converters', async () => {
fs.copyFileSync(path.join(__dirname, 'assets', 'mock-external-converter-multiple.js'), path.join(data.mockDir, 'mock-external-converter-multiple.js'));
const devicesCount = zigbeeHerdsman.devices.lenght;
settings.set(['external_converters'], ['mock-external-converter-multiple.js']);
controller = new Controller();
await controller.start();
await flushPromises();
expect(zigbeeHerdsmanConverters.addDeviceDefinition).toHaveBeenCalledTimes(2);
expect(zigbeeHerdsmanConverters.addDeviceDefinition).toHaveBeenNthCalledWith(1, {
mock: 1,
model: 'external_converters_device',
});
expect(zigbeeHerdsmanConverters.addDeviceDefinition).toHaveBeenNthCalledWith(2, {
mock: 2
});
});
it('Loads external converters from package', async () => {
settings.set(['external_converters'], ['mock-external-converter-module']);
controller = new Controller();
await controller.start();
await flushPromises();
expect(zigbeeHerdsmanConverters.addDeviceDefinition).toHaveBeenCalledTimes(1);
expect(zigbeeHerdsmanConverters.addDeviceDefinition).toHaveBeenCalledWith({
mock: true
});
});
it('Loads multiple external converters from package', async () => {
settings.set(['external_converters'], ['mock-multiple-external-converter-module']);
controller = new Controller();
await controller.start();
await flushPromises();
expect(zigbeeHerdsmanConverters.addDeviceDefinition).toHaveBeenCalledTimes(2);
expect(zigbeeHerdsmanConverters.addDeviceDefinition).toHaveBeenNthCalledWith(1, {
mock: 1
});
expect(zigbeeHerdsmanConverters.addDeviceDefinition).toHaveBeenNthCalledWith(2, {
mock: 2
});
});
});
+725
View File
@@ -0,0 +1,725 @@
const data = require('./stub/data');
const logger = require('./stub/logger');
const zigbeeHerdsman = require('./stub/zigbeeHerdsman');
const zigbeeHerdsmanConverters = require('zigbee-herdsman-converters');
zigbeeHerdsman.returnDevices.push('0x00124b00120144ae');
zigbeeHerdsman.returnDevices.push('0x000b57fffec6a5b3');
zigbeeHerdsman.returnDevices.push('0x000b57fffec6a5b2');
zigbeeHerdsman.returnDevices.push('0x0017880104e45542');
const MQTT = require('./stub/mqtt');
const Controller = require('../lib/controller');
const flushPromises = () => new Promise(setImmediate);
const settings = require('../lib/util/settings');
describe('Groups', () => {
let controller;
beforeEach(() => {
data.writeEmptyState();
settings.set(['experimental', 'new_api'], true);
controller = new Controller();
Object.values(zigbeeHerdsman.groups).forEach((g) => g.members = []);
data.writeDefaultConfiguration();
settings._reRead();
MQTT.publish.mockClear();
zigbeeHerdsmanConverters.toZigbeeConverters.__clearStore__();
})
it('Apply group updates add', async () => {
settings.set(['groups'], {'1': {friendly_name: 'group_1', retain: false, devices: ['bulb', 'bulb_color']}});
zigbeeHerdsman.groups.group_1.members.push(zigbeeHerdsman.devices.bulb.getEndpoint(1))
await controller.start();
await flushPromises();
expect(zigbeeHerdsman.groups.group_1.members).toStrictEqual([
zigbeeHerdsman.devices.bulb.getEndpoint(1),
zigbeeHerdsman.devices.bulb_color.getEndpoint(1)
]);
});
it('Apply group updates remove', async () => {
const endpoint = zigbeeHerdsman.devices.bulb_color.getEndpoint(1);
const group = zigbeeHerdsman.groups.group_1;
group.members.push(endpoint);
settings.set(['groups'], {'1': {friendly_name: 'group_1', retain: false,}});
await controller.start();
await flushPromises();
expect(zigbeeHerdsman.groups.group_1.members).toStrictEqual([]);
});
it('Move to non existing group', 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'], {'3': {friendly_name: 'group_3', retain: false, devices: [device.ieeeAddr]}});
await controller.start();
await flushPromises();
expect(zigbeeHerdsman.groups.group_1.members).toStrictEqual([]);
});
it('Add non standard endpoint to group with name', async () => {
const QBKG03LM = zigbeeHerdsman.devices.QBKG03LM;
settings.set(['groups'], {'1': {friendly_name: 'group_1', retain: false, devices: ['0x0017880104e45542/right']}});
await controller.start();
await flushPromises();
expect(zigbeeHerdsman.groups.group_1.members).toStrictEqual([QBKG03LM.getEndpoint(3)]);
});
it('Add non standard endpoint to group with number', async () => {
const QBKG03LM = zigbeeHerdsman.devices.QBKG03LM;
settings.set(['groups'], {'1': {friendly_name: 'group_1', retain: false, devices: ['wall_switch_double/2']}});
await controller.start();
await flushPromises();
expect(zigbeeHerdsman.groups.group_1.members).toStrictEqual([QBKG03LM.getEndpoint(2)]);
});
it('Shouldnt crash on non-existing devices', async () => {
logger.error.mockClear();
settings.set(['groups'], {'1': {friendly_name: 'group_1', retain: false, devices: ['not_existing_bla']}});
await controller.start();
await flushPromises();
expect(zigbeeHerdsman.groups.group_1.members).toStrictEqual([]);
expect(logger.error).toHaveBeenCalledWith("Cannot find 'not_existing_bla' of group 'group_1'");
});
it('Legacy api: Add to group via MQTT', async () => {
const device = zigbeeHerdsman.devices.bulb_color;
const endpoint = device.getEndpoint(1);
const group = zigbeeHerdsman.groups.group_1;
settings.set(['groups'], {'1': {friendly_name: 'group_1', retain: false, devices: []}});
expect(group.members.length).toBe(0);
await controller.start();
await flushPromises();
MQTT.events.message('zigbee2mqtt/bridge/group/group_1/add', 'bulb_color');
await flushPromises();
expect(group.members).toStrictEqual([endpoint]);
expect(settings.getGroup('group_1').devices).toStrictEqual([`${device.ieeeAddr}/1`]);
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bridge/log", '{"type":"device_group_add","message":{"friendly_name":"bulb_color","group":"group_1"}}', {"retain": false, qos: 0}, expect.any(Function));
});
it('Legacy api: Add to group with slashes via MQTT', async () => {
const device = zigbeeHerdsman.devices.bulb_color;
const endpoint = device.getEndpoint(1);
const group = zigbeeHerdsman.groups["group/with/slashes"];
settings.set(['groups'], {'99': {friendly_name: 'group/with/slashes', retain: false, devices: []}});
expect(group.members.length).toBe(0);
await controller.start();
await flushPromises();
MQTT.events.message('zigbee2mqtt/bridge/group/group/with/slashes/add', 'bulb_color');
await flushPromises();
expect(group.members).toStrictEqual([endpoint]);
expect(settings.getGroup('group/with/slashes').devices).toStrictEqual([`${device.ieeeAddr}/1`]);
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bridge/log", '{"type":"device_group_add","message":{"friendly_name":"bulb_color","group":"group/with/slashes"}}', {"retain": false, qos: 0}, expect.any(Function));
// Test if subscribed to topics with slashes
expect(MQTT.subscribe).toHaveBeenCalledWith('zigbee2mqtt/bridge/group/+/remove');
expect(MQTT.subscribe).toHaveBeenCalledWith('zigbee2mqtt/bridge/group/+/+/remove');
expect(MQTT.subscribe).toHaveBeenCalledWith('zigbee2mqtt/bridge/group/+/+/+/+/+/remove');
expect(MQTT.subscribe).toHaveBeenCalledWith('zigbee2mqtt/bridge/group/+/+/+/+/+/add');
});
it('Legacy api: Add to group via MQTT with postfix', async () => {
const device = zigbeeHerdsman.devices.QBKG03LM;
const endpoint = device.getEndpoint(3);
const group = zigbeeHerdsman.groups.group_1;
expect(group.members.length).toBe(0);
await controller.start();
await flushPromises();
await MQTT.events.message('zigbee2mqtt/bridge/group/group_1/add', 'wall_switch_double/right');
await flushPromises();
expect(group.members).toStrictEqual([endpoint]);
expect(settings.getGroup('group_1').devices).toStrictEqual([`${device.ieeeAddr}/${endpoint.ID}`]);
});
it('Legacy api: Add to group via MQTT with postfix shouldnt add it twice', async () => {
const device = zigbeeHerdsman.devices.QBKG03LM;
const endpoint = device.getEndpoint(3);
const group = zigbeeHerdsman.groups.group_1;
expect(group.members.length).toBe(0);
await controller.start();
await flushPromises();
await MQTT.events.message('zigbee2mqtt/bridge/group/group_1/add', 'wall_switch_double/right');
await flushPromises();
await MQTT.events.message('zigbee2mqtt/bridge/group/group_1/add', '0x0017880104e45542/3');
await flushPromises();
expect(group.members).toStrictEqual([endpoint]);
expect(settings.getGroup('group_1').devices).toStrictEqual([`${device.ieeeAddr}/${endpoint.ID}`]);
});
it('Legacy api: Remove from group via MQTT', 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, devices: [device.ieeeAddr]}});
await controller.start();
await flushPromises();
await MQTT.events.message('zigbee2mqtt/bridge/group/group_1/remove', 'bulb_color');
await flushPromises();
expect(group.members).toStrictEqual([]);
expect(settings.getGroup('group_1').devices).toStrictEqual([]);
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bridge/log", '{"type":"device_group_remove","message":{"friendly_name":"bulb_color","group":"group_1"}}', {"retain": false, qos: 0}, expect.any(Function));
});
it('Legacy api: Remove from group via MQTT when in zigbee but not in settings', 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, devices: ['dummy']}});
await controller.start();
await flushPromises();
await MQTT.events.message('zigbee2mqtt/bridge/group/group_1/remove', 'bulb_color');
await flushPromises();
expect(group.members).toStrictEqual([]);
expect(settings.getGroup('group_1').devices).toStrictEqual(['dummy']);
});
it('Legacy api: Remove from group via MQTT with postfix variant 1', 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, devices: [`wall_switch_double/right`]}});
await controller.start();
await flushPromises();
await MQTT.events.message('zigbee2mqtt/bridge/group/group_1/remove', '0x0017880104e45542/3');
await flushPromises();
expect(group.members).toStrictEqual([]);
expect(settings.getGroup('group_1').devices).toStrictEqual([]);
});
it('Legacy api: Remove from group via MQTT with postfix variant 2', 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, devices: [`0x0017880104e45542/right`]}});
await controller.start();
await flushPromises();
await MQTT.events.message('zigbee2mqtt/bridge/group/group_1/remove', 'wall_switch_double/3');
await flushPromises();
expect(group.members).toStrictEqual([]);
expect(settings.getGroup('group_1').devices).toStrictEqual([]);
});
it('Legacy api: Remove from group via MQTT with postfix variant 3', 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, devices: [`wall_switch_double/3`]}});
await controller.start();
await flushPromises();
await MQTT.events.message('zigbee2mqtt/bridge/group/group_1/remove', '0x0017880104e45542/right');
await flushPromises();
expect(group.members).toStrictEqual([]);
expect(settings.getGroup('group_1').devices).toStrictEqual([]);
});
it('Legacy api: Remove from group all', 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, devices: [`wall_switch_double/3`]}});
await controller.start();
await flushPromises();
await MQTT.events.message('zigbee2mqtt/bridge/group/remove_all', '0x0017880104e45542/right');
await flushPromises();
expect(group.members).toStrictEqual([]);
expect(settings.getGroup('group_1').devices).toStrictEqual([]);
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bridge/log", '{"type":"device_group_remove_all","message":{"friendly_name":"wall_switch_double"}}', {"retain": false, qos: 0}, expect.any(Function));
});
it('Remove from group all deprecated', 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, devices: [`wall_switch_double/3`]}});
await controller.start();
await flushPromises();
await MQTT.events.message('zigbee2mqtt/bridge/group/group_1/remove_all', '0x0017880104e45542/right');
await flushPromises();
expect(group.members).toStrictEqual([]);
expect(settings.getGroup('group_1').devices).toStrictEqual([]);
});
it('Legacy api: Log when adding to non-existing group', async () => {
await controller.start();
await flushPromises();
logger.error.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/group/group_1_not_existing/add', 'bulb_color');
await flushPromises();
expect(logger.error).toHaveBeenCalledWith("Group 'group_1_not_existing' does not exist");
});
it('Legacy api: Log when adding to non-existing device', async () => {
await controller.start();
await flushPromises();
logger.error.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/group/group_1/add', 'bulb_color_not_existing');
await flushPromises();
expect(logger.error).toHaveBeenCalledWith("Device 'bulb_color_not_existing' does not exist");
});
it('Should publish group state change when a device in it changes state', 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, devices: [device.ieeeAddr]}});
await controller.start();
await flushPromises();
MQTT.publish.mockClear();
const payload = {data: {onOff: 1}, cluster: 'genOnOff', device, endpoint, type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(2);
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bulb_color", '{"state":"ON","linkquality":10}', {"retain": false, qos: 0}, expect.any(Function));
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', 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, devices: [device.ieeeAddr]}});
await controller.start();
await flushPromises();
MQTT.publish.mockClear();
await MQTT.events.message('zigbee2mqtt/group_1/set', JSON.stringify({state: 'ON'}));
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(2);
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bulb_color", '{"state":"ON"}', {"retain": false, qos: 0}, expect.any(Function));
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);
const group = zigbeeHerdsman.groups.group_1;
group.members.push(endpoint);
settings.set(['groups'], {'1': {friendly_name: 'group_1', devices: [device.ieeeAddr], optimistic: false, retain: false}});
await controller.start();
await flushPromises();
MQTT.publish.mockClear();
const payload = {data: {onOff: 1}, cluster: 'genOnOff', device, endpoint, type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(1);
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bulb_color", '{"state":"ON","linkquality":10}', {"retain": false, qos: 0}, expect.any(Function));
});
it('Should publish state change of another group with shared device when a group changes its state', 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, devices: [device.ieeeAddr]},
'2': {friendly_name: 'group_2', retain: false, devices: [device.ieeeAddr]},
'3': {friendly_name: 'group_3', retain: false, devices: []}
});
await controller.start();
await flushPromises();
MQTT.publish.mockClear();
await MQTT.events.message('zigbee2mqtt/group_1/set', JSON.stringify({state: 'ON'}));
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(3);
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bulb_color", '{"state":"ON"}', {"retain": false, qos: 0}, expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/group_1", '{"state":"ON"}', {"retain": false, qos: 0}, expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/group_2", '{"state":"ON"}', {"retain": false, qos: 0}, expect.any(Function));
});
it('Should not publish state change off if any lights within are still on when changed via device', async () => {
const device_1 = zigbeeHerdsman.devices.bulb_color;
const device_2 = zigbeeHerdsman.devices.bulb;
const endpoint_1 = device_1.getEndpoint(1);
const endpoint_2 = device_2.getEndpoint(1);
const group = zigbeeHerdsman.groups.group_1;
group.members.push(endpoint_1);
group.members.push(endpoint_2);
settings.set(['groups'], {
'1': {friendly_name: 'group_1', devices: [device_1.ieeeAddr, device_2.ieeeAddr], retain: false}
});
await controller.start();
await flushPromises();
await MQTT.events.message('zigbee2mqtt/group_1/set', JSON.stringify({state: 'ON'}));
await flushPromises();
MQTT.publish.mockClear();
await MQTT.events.message('zigbee2mqtt/bulb_color/set', JSON.stringify({state: 'OFF'}));
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(1);
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bulb_color", '{"state":"OFF","brightness":0}', {"retain": false, qos: 0}, expect.any(Function));
});
it('Should not publish state change off if any lights within are still on when changed via shared group', async () => {
const device_1 = zigbeeHerdsman.devices.bulb_color;
const device_2 = zigbeeHerdsman.devices.bulb;
const endpoint_1 = device_1.getEndpoint(1);
const endpoint_2 = device_2.getEndpoint(1);
const group = zigbeeHerdsman.groups.group_1;
group.members.push(endpoint_1);
group.members.push(endpoint_2);
settings.set(['groups'], {
'1': {friendly_name: 'group_1', devices: [device_1.ieeeAddr, device_2.ieeeAddr], retain: false},
'2': {friendly_name: 'group_2', retain: false, devices: [device_1.ieeeAddr]},
});
await controller.start();
await flushPromises();
await MQTT.events.message('zigbee2mqtt/group_1/set', JSON.stringify({state: 'ON'}));
await flushPromises();
MQTT.publish.mockClear();
await MQTT.events.message('zigbee2mqtt/group_2/set', JSON.stringify({state: 'OFF'}));
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(2);
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/group_2", '{"state":"OFF","brightness":0}', {"retain": false, qos: 0}, expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bulb_color", '{"state":"OFF","brightness":0}', {"retain": false, qos: 0}, expect.any(Function));
});
it('Should publish state change off if all lights within turn off', async () => {
const device_1 = zigbeeHerdsman.devices.bulb_color;
const device_2 = zigbeeHerdsman.devices.bulb;
const endpoint_1 = device_1.getEndpoint(1);
const endpoint_2 = device_2.getEndpoint(1);
const group = zigbeeHerdsman.groups.group_1;
group.members.push(endpoint_1);
group.members.push(endpoint_2);
settings.set(['groups'], {
'1': {friendly_name: 'group_1', devices: [device_1.ieeeAddr, device_2.ieeeAddr], retain: false}
});
await controller.start();
await flushPromises();
await MQTT.events.message('zigbee2mqtt/group_1/set', JSON.stringify({state: 'ON'}));
await flushPromises();
MQTT.publish.mockClear();
await MQTT.events.message('zigbee2mqtt/bulb_color/set', JSON.stringify({state: 'OFF'}));
await MQTT.events.message('zigbee2mqtt/bulb/set', JSON.stringify({state: 'OFF'}));
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(3);
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bulb_color", '{"state":"OFF","brightness":0}', {"retain": false, qos: 0}, expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bulb", '{"state":"OFF","brightness":0}', {"retain": true, qos: 0}, expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/group_1", '{"state":"OFF","brightness":0}', {"retain": false, qos: 0}, expect.any(Function));
});
it('Should publish state change off even when missing current state', async () => {
const device_1 = zigbeeHerdsman.devices.bulb_color;
const device_2 = zigbeeHerdsman.devices.bulb;
const endpoint_1 = device_1.getEndpoint(1);
const endpoint_2 = device_2.getEndpoint(1);
const group = zigbeeHerdsman.groups.group_1;
group.members.push(endpoint_1);
group.members.push(endpoint_2);
settings.set(['groups'], {
'1': {friendly_name: 'group_1', devices: [device_1.ieeeAddr, device_2.ieeeAddr], retain: false}
});
await controller.start();
await flushPromises();
await MQTT.events.message('zigbee2mqtt/group_1/set', JSON.stringify({state: 'ON'}));
await flushPromises();
MQTT.publish.mockClear();
controller.state.state = {};
await MQTT.events.message('zigbee2mqtt/bulb_color/set', JSON.stringify({state: 'OFF'}));
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(2);
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/bulb_color", '{"state":"OFF","brightness":0}', {"retain": false, qos: 0}, expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith("zigbee2mqtt/group_1", '{"state":"OFF","brightness":0}', {"retain": false, qos: 0}, expect.any(Function));
});
it('Add to group via MQTT', async () => {
const device = zigbeeHerdsman.devices.bulb_color;
const endpoint = device.getEndpoint(1);
const group = zigbeeHerdsman.groups.group_1;
settings.set(['groups'], {'1': {friendly_name: 'group_1', retain: false, devices: []}});
expect(group.members.length).toBe(0);
await controller.start();
await flushPromises();
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/group/members/add', JSON.stringify({group: 'group_1', device: 'bulb_color'}));
await flushPromises();
expect(group.members).toStrictEqual([endpoint]);
expect(settings.getGroup('group_1').devices).toStrictEqual([`${device.ieeeAddr}/1`]);
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bridge/groups', expect.any(String), expect.any(Object), expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/group/members/add',
JSON.stringify({"data":{"device":"bulb_color","group":"group_1"},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Add to group via MQTT fails', async () => {
const device = zigbeeHerdsman.devices.bulb_color;
const endpoint = device.getEndpoint(1);
const group = zigbeeHerdsman.groups.group_1;
settings.set(['groups'], {'1': {friendly_name: 'group_1', retain: false, devices: []}});
expect(group.members.length).toBe(0);
await controller.start();
endpoint.addToGroup.mockImplementationOnce(() => {throw new Error('timeout')});
await flushPromises();
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/group/members/add', JSON.stringify({group: 'group_1', device: 'bulb_color'}));
await flushPromises();
expect(group.members).toStrictEqual([]);
expect(settings.getGroup('group_1').devices).toStrictEqual([]);
expect(MQTT.publish).not.toHaveBeenCalledWith('zigbee2mqtt/bridge/groups', expect.any(String), expect.any(Object), expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/group/members/add',
JSON.stringify({"data":{"device":"bulb_color","group":"group_1"},"status":"error","error":"Failed to add from group (timeout)"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Add to group with slashes via MQTT', async () => {
const device = zigbeeHerdsman.devices.bulb_color;
const endpoint = device.getEndpoint(1);
const group = zigbeeHerdsman.groups["group/with/slashes"];
settings.set(['groups'], {'99': {friendly_name: 'group/with/slashes', retain: false, devices: []}});
expect(group.members.length).toBe(0);
await controller.start();
await flushPromises();
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/group/members/add', JSON.stringify({group: 'group/with/slashes', device: 'bulb_color'}));
await flushPromises();
expect(group.members).toStrictEqual([endpoint]);
expect(settings.getGroup('group/with/slashes').devices).toStrictEqual([`${device.ieeeAddr}/1`]);
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bridge/groups', expect.any(String), expect.any(Object), expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/group/members/add',
JSON.stringify({"data":{"device":"bulb_color","group":"group/with/slashes"},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Add to group via MQTT with postfix', async () => {
const device = zigbeeHerdsman.devices.QBKG03LM;
const endpoint = device.getEndpoint(3);
const group = zigbeeHerdsman.groups.group_1;
expect(group.members.length).toBe(0);
await controller.start();
await flushPromises();
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/group/members/add', JSON.stringify({group: 'group_1', device: 'wall_switch_double/right'}));
await flushPromises();
expect(group.members).toStrictEqual([endpoint]);
expect(settings.getGroup('group_1').devices).toStrictEqual([`${device.ieeeAddr}/${endpoint.ID}`]);
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bridge/groups', expect.any(String), expect.any(Object), expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/group/members/add',
JSON.stringify({"data":{"device":"wall_switch_double/right","group":"group_1"},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Add to group via MQTT with postfix shouldnt add it twice', async () => {
const device = zigbeeHerdsman.devices.QBKG03LM;
const endpoint = device.getEndpoint(3);
const group = zigbeeHerdsman.groups.group_1;
expect(group.members.length).toBe(0);
await controller.start();
await flushPromises();
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/group/members/add', JSON.stringify({group: 'group_1', device: 'wall_switch_double/right'}));
await flushPromises();
MQTT.events.message('zigbee2mqtt/bridge/request/group/members/add', JSON.stringify({group: 'group_1', device: '0x0017880104e45542/3'}));
await flushPromises();
expect(group.members).toStrictEqual([endpoint]);
expect(settings.getGroup('group_1').devices).toStrictEqual([`${device.ieeeAddr}/${endpoint.ID}`]);
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bridge/groups', expect.any(String), expect.any(Object), expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/group/members/add',
JSON.stringify({"data":{"device":"wall_switch_double/right","group":"group_1"},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Remove from group via MQTT', 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, devices: [device.ieeeAddr]}});
await controller.start();
await flushPromises();
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/group/members/remove', JSON.stringify({group: 'group_1', device: 'bulb_color'}));
await flushPromises();
expect(group.members).toStrictEqual([]);
expect(settings.getGroup('group_1').devices).toStrictEqual([]);
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bridge/groups', expect.any(String), expect.any(Object), expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/group/members/remove',
JSON.stringify({"data":{"device":"bulb_color","group":"group_1"},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Remove from group via MQTT when in zigbee but not in settings', 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, devices: ['dummy']}});
await controller.start();
await flushPromises();
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/group/members/remove', JSON.stringify({group: 'group_1', device: 'bulb_color'}));
await flushPromises();
expect(group.members).toStrictEqual([]);
expect(settings.getGroup('group_1').devices).toStrictEqual(['dummy']);
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bridge/groups', expect.any(String), expect.any(Object), expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/group/members/remove',
JSON.stringify({"data":{"device":"bulb_color","group":"group_1"},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Remove from group via MQTT with postfix variant 1', 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, devices: [`wall_switch_double/right`]}});
await controller.start();
await flushPromises();
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/group/members/remove', JSON.stringify({group: 'group_1', device: '0x0017880104e45542/3'}));
await flushPromises();
expect(group.members).toStrictEqual([]);
expect(settings.getGroup('group_1').devices).toStrictEqual([]);
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bridge/groups', expect.any(String), expect.any(Object), expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/group/members/remove',
JSON.stringify({"data":{"device":"0x0017880104e45542/3","group":"group_1"},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Remove from group via MQTT with postfix variant 2', 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, devices: [`0x0017880104e45542/right`]}});
await controller.start();
await flushPromises();
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/group/members/remove', JSON.stringify({group: 'group_1', device: 'wall_switch_double/3'}));
await flushPromises();
expect(group.members).toStrictEqual([]);
expect(settings.getGroup('group_1').devices).toStrictEqual([]);
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bridge/groups', expect.any(String), expect.any(Object), expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/group/members/remove',
JSON.stringify({"data":{"device":"wall_switch_double/3","group":"group_1"},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Remove from group via MQTT with postfix variant 3', 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, devices: [`wall_switch_double/3`]}});
await controller.start();
await flushPromises();
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/group/members/remove', JSON.stringify({group: 'group_1', device: '0x0017880104e45542/right'}));
await flushPromises();
expect(group.members).toStrictEqual([]);
expect(settings.getGroup('group_1').devices).toStrictEqual([]);
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bridge/groups', expect.any(String), expect.any(Object), expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/group/members/remove',
JSON.stringify({"data":{"device":"0x0017880104e45542/right","group":"group_1"},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Remove from group all', 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, devices: [`wall_switch_double/3`]}});
await controller.start();
await flushPromises();
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/group/members/remove_all', JSON.stringify({device: '0x0017880104e45542/right'}));
await flushPromises();
expect(group.members).toStrictEqual([]);
expect(settings.getGroup('group_1').devices).toStrictEqual([]);
expect(MQTT.publish).toHaveBeenCalledWith('zigbee2mqtt/bridge/groups', expect.any(String), expect.any(Object), expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/group/members/remove_all',
JSON.stringify({"data":{"device":"0x0017880104e45542/right"},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Error when adding to non-existing group', async () => {
await controller.start();
await flushPromises();
logger.error.mockClear();
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/group/members/remove', JSON.stringify({group: 'group_1_not_existing', device: 'bulb_color'}));
await flushPromises();
expect(MQTT.publish).not.toHaveBeenCalledWith('zigbee2mqtt/bridge/groups', expect.any(String), expect.any(Object), expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/group/members/remove',
JSON.stringify({"data":{"device":"bulb_color","group":"group_1_not_existing"},"status":"error","error":"Group 'group_1_not_existing' does not exist"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Error when adding to non-existing device', async () => {
await controller.start();
await flushPromises();
logger.error.mockClear();
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/group/members/add', JSON.stringify({group: 'group_1', device: 'bulb_color_not_existing'}));
await flushPromises();
expect(MQTT.publish).not.toHaveBeenCalledWith('zigbee2mqtt/bridge/groups', expect.any(String), expect.any(Object), expect.any(Function));
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/group/members/add',
JSON.stringify({"data":{"device":"bulb_color_not_existing","group":"group_1"},"status":"error","error":"Device 'bulb_color_not_existing' does not exist"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
});
File diff suppressed because it is too large Load Diff
+477
View File
@@ -0,0 +1,477 @@
const data = require('../stub/data');
const logger = require('../stub/logger');
const zigbeeHerdsman = require('../stub/zigbeeHerdsman');
const MQTT = require('../stub/mqtt');
const path = require('path');
const mockExit = jest.spyOn(process, 'exit').mockImplementation(() => {});
const settings = require('../../lib/util/settings');
const Controller = require('../../lib/controller');
const flushPromises = () => new Promise(setImmediate);
describe('Bridge legacy', () => {
let controller;
beforeAll(async () => {
this.version = await require('../../lib/util/utils').getZigbee2mqttVersion();
controller = new Controller();
await controller.start();
})
beforeEach(() => {
data.writeDefaultConfiguration();
settings._reRead();
data.writeDefaultState();
logger.info.mockClear();
logger.warn.mockClear();
});
it('Should publish bridge configuration on startup', async () => {
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/config',
JSON.stringify({"version":this.version.version,"commit":this.version.commitHash,"coordinator":{"type":"z-Stack","meta":{"version":1, "revision": 20190425}},"log_level":'info',"permit_join":false}),
{ retain: true, qos: 0 },
expect.any(Function)
);
});
it('Should allow to set elapsed', async () => {
MQTT.events.message('zigbee2mqtt/bridge/config/elapsed', 'true');
await flushPromises();
expect(settings.get().advanced.elapsed).toBe(true);
MQTT.events.message('zigbee2mqtt/bridge/config/elapsed', 'false');
await flushPromises();
expect(settings.get().advanced.elapsed).toBe(false);
MQTT.events.message('zigbee2mqtt/bridge/config/elapsed', 'wrong');
await flushPromises();
expect(settings.get().advanced.elapsed).toBe(false);
});
it('Should allow whitelist', async () => {
const bulb_color = zigbeeHerdsman.devices.bulb_color;
const bulb = zigbeeHerdsman.devices.bulb;
expect(settings.get().whitelist).toStrictEqual([]);
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/config/whitelist', 'bulb_color');
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/log',
JSON.stringify({type: "device_whitelisted", "message": {friendly_name: "bulb_color"}}),
{ retain: false, qos: 0 },
expect.any(Function)
);
MQTT.publish.mockClear()
expect(settings.get().whitelist).toStrictEqual([bulb_color.ieeeAddr]);
MQTT.events.message('zigbee2mqtt/bridge/config/whitelist', 'bulb');
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/log',
JSON.stringify({type: "device_whitelisted", "message": {friendly_name: "bulb"}}),
{ retain: false, qos: 0 },
expect.any(Function)
);
MQTT.publish.mockClear()
expect(settings.get().whitelist).toStrictEqual([bulb_color.ieeeAddr, bulb.ieeeAddr]);
MQTT.events.message('zigbee2mqtt/bridge/config/whitelist', 'bulb');
await flushPromises();
expect(settings.get().whitelist).toStrictEqual([bulb_color.ieeeAddr, bulb.ieeeAddr]);
expect(MQTT.publish).toHaveBeenCalledTimes(0);
});
it('Should allow changing device options', async () => {
const bulb_color = zigbeeHerdsman.devices.bulb_color;
expect(settings.getDevice('bulb_color')).toStrictEqual(
{"ID": "0x000b57fffec6a5b3", "friendlyName": "bulb_color", "friendly_name": "bulb_color", "retain": false}
);
MQTT.events.message('zigbee2mqtt/bridge/config/device_options', JSON.stringify({friendly_name: 'bulb_color', options: {retain: true}}));
await flushPromises();
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', optionswrong: {retain: true}}));
await flushPromises();
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', "{friendly_name: 'bulb_color'malformed: {retain: true}}");
await flushPromises();
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 () => {
zigbeeHerdsman.permitJoin.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/config/permit_join', 'true');
await flushPromises();
expect(zigbeeHerdsman.permitJoin).toHaveBeenCalledTimes(1);
expect(zigbeeHerdsman.permitJoin).toHaveBeenCalledWith(true);
zigbeeHerdsman.permitJoin.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/config/permit_join', 'false');
await flushPromises();
expect(zigbeeHerdsman.permitJoin).toHaveBeenCalledTimes(1);
expect(zigbeeHerdsman.permitJoin).toHaveBeenCalledWith(false);
});
it('Should allow to reset', async () => {
zigbeeHerdsman.reset.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/config/reset', '');
await flushPromises();
expect(zigbeeHerdsman.reset).toHaveBeenCalledTimes(1);
expect(zigbeeHerdsman.reset).toHaveBeenCalledWith('soft');
zigbeeHerdsman.reset.mockImplementationOnce(() => {throw new Error('')});
MQTT.events.message('zigbee2mqtt/bridge/config/reset', '');
await flushPromises();
expect(zigbeeHerdsman.reset).toHaveBeenCalledTimes(2);
expect(zigbeeHerdsman.reset.mock.calls[1][0]).toBe('soft');
});
it('Should allow to set last_seen', async () => {
MQTT.events.message('zigbee2mqtt/bridge/config/last_seen', 'ISO_8601');
await flushPromises();
expect(settings.get().advanced.last_seen).toBe('ISO_8601');
MQTT.events.message('zigbee2mqtt/bridge/config/last_seen', 'disable');
await flushPromises();
expect(settings.get().advanced.last_seen).toBe('disable');
MQTT.events.message('zigbee2mqtt/bridge/config/last_seen', 'notvalid');
await flushPromises();
expect(settings.get().advanced.last_seen).toBe('disable');
});
it('Should allow to set log_level', async () => {
MQTT.events.message('zigbee2mqtt/bridge/config/log_level', 'debug');
await flushPromises();
expect(logger.getLevel()).toBe('debug');
MQTT.events.message('zigbee2mqtt/bridge/config/log_level', 'error');
await flushPromises();
expect(logger.getLevel()).toBe('error');
MQTT.events.message('zigbee2mqtt/bridge/config/log_level', 'notvalid');
await flushPromises();
expect(logger.getLevel()).toBe('error');
});
it('Should allow to get devices', async () => {
const now = Date.now;
Date.now = () => 100;
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/config/devices/get', '');
await flushPromises();
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[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;
});
it('Should allow to get groups', async () => {
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/config/groups', '');
await flushPromises();
expect(MQTT.publish.mock.calls[0][0]).toStrictEqual('zigbee2mqtt/bridge/log');
const payload = JSON.parse(MQTT.publish.mock.calls[0][1]);
expect(payload).toStrictEqual({"message": [{"ID": 1, "friendly_name": "group_1", "retain": false, 'devices': [], optimistic: true}, {"ID": 2, "friendly_name": "group_2", "retain": false, "devices": [], optimistic: true}, {"ID": 11, "friendly_name": "group_with_tradfri", "retain": false, "devices": ['bulb_2'], optimistic: true}, {"ID": 15071, "friendly_name": "group_tradfri_remote", "retain": false, "devices": ['bulb_color_2', 'bulb_2'], optimistic: true}], "type": "groups"});
});
it('Should allow rename devices', async () => {
const bulb_color2 = {"ID": "0x000b57fffec6a5b3", "friendlyName": "bulb_color2", "friendly_name": "bulb_color2", "retain": false};
MQTT.publish.mockClear();
expect(settings.getDevice('bulb_color')).toStrictEqual({"ID": "0x000b57fffec6a5b3", "friendlyName": "bulb_color", "friendly_name": "bulb_color", "retain": false});
MQTT.events.message('zigbee2mqtt/bridge/config/rename', JSON.stringify({old: 'bulb_color', new: 'bulb_color2'}));
await flushPromises();
expect(settings.getDevice('bulb_color')).toStrictEqual(null);
expect(settings.getDevice('bulb_color2')).toStrictEqual(bulb_color2);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/log',
JSON.stringify({type: 'device_renamed', message: {from: 'bulb_color', to: 'bulb_color2'}}),
{qos: 0, retain: false},
expect.any(Function)
);
MQTT.events.message('zigbee2mqtt/bridge/config/rename', JSON.stringify({old: 'bulb_color2', newmalformed: 'bulb_color3'}));
await flushPromises();
expect(settings.getDevice('bulb_color2')).toStrictEqual(bulb_color2);
MQTT.events.message('zigbee2mqtt/bridge/config/rename', "{old: 'bulb_color2'newmalformed: 'bulb_color3'}");
await flushPromises();
expect(settings.getDevice('bulb_color2')).toStrictEqual(bulb_color2);
MQTT.events.message('zigbee2mqtt/bridge/config/rename', JSON.stringify({old: 'bulb_color', new: 'bulb_color3'}));
await flushPromises();
expect(settings.getDevice('bulb_color2')).toStrictEqual(bulb_color2);
});
it('Should allow rename groups', async () => {
MQTT.publish.mockClear();
expect(settings.getGroup(1)).toStrictEqual({"ID": 1, devices: [], friendlyName: "group_1", "friendly_name": "group_1", optimistic: true, retain: false});
MQTT.events.message('zigbee2mqtt/bridge/config/rename', JSON.stringify({old: 'group_1', new: 'group_1_renamed'}));
await flushPromises();
expect(settings.getGroup(1)).toStrictEqual({"ID": 1, devices: [], friendlyName: "group_1_renamed", "friendly_name": "group_1_renamed", optimistic: true, retain: false});
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/log',
JSON.stringify({type: 'group_renamed', message: {from: 'group_1', to: 'group_1_renamed'}}),
{qos: 0, retain: false},
expect.any(Function)
);
});
it('Should allow to rename last joined device', async () => {
const device = zigbeeHerdsman.devices.bulb;
const payload = {device};
await zigbeeHerdsman.events.deviceJoined(payload);
await flushPromises();
expect(settings.getDevice('0x000b57fffec6a5b2').friendlyName).toStrictEqual('bulb');
MQTT.events.message('zigbee2mqtt/bridge/config/rename_last', 'bulb_new_name');
await flushPromises();
expect(settings.getDevice('0x000b57fffec6a5b2').friendlyName).toStrictEqual('bulb_new_name');
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/log',
JSON.stringify({type: 'device_renamed', message: {from: 'bulb', to: 'bulb_new_name'}}),
{qos: 0, retain: false},
expect.any(Function)
);
});
it('Shouldnt rename when no device has been joined', async () => {
controller = new Controller();
await controller.start();
await flushPromises();
expect(settings.getDevice('0x000b57fffec6a5b2').friendlyName).toStrictEqual('bulb');
MQTT.events.message('zigbee2mqtt/bridge/config/rename_last', 'bulb_new_name');
await flushPromises();
expect(settings.getDevice('0x000b57fffec6a5b2').friendlyName).toStrictEqual('bulb');
});
it('Should allow to add groups', async () => {
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);
});
it('Should allow to add groups with json', async () => {
zigbeeHerdsman.createGroup.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/config/add_group', '{"friendly_name": "new_group"}');
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(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 () => {
zigbeeHerdsman.createGroup.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/config/add_group', '{"friendly_name": "new_group", "id": 42}');
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(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 () => {
zigbeeHerdsman.createGroup.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/config/add_group', '{"id": 42}');
await flushPromises();
expect(settings.getGroup('group_42')).toStrictEqual({"ID": 42, "friendlyName": "group_42", "friendly_name": "group_42", devices: [], optimistic: true});
expect(zigbeeHerdsman.createGroup).toHaveBeenCalledTimes(1);
expect(zigbeeHerdsman.createGroup).toHaveBeenCalledWith(42)
});
it('Should allow to remove groups', async () => {
const group = zigbeeHerdsman.groups.group_1;
MQTT.events.message('zigbee2mqtt/bridge/config/remove_group', 'group_1');
await flushPromises();
expect(settings.getGroup('to_be_removed')).toStrictEqual(null);
expect(group.removeFromNetwork).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('Should allow to force remove groups', async () => {
const group = zigbeeHerdsman.groups.group_1;
MQTT.events.message('zigbee2mqtt/bridge/config/force_remove_group', 'group_1');
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 () => {
zigbeeHerdsman.createGroup.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/config/add_group', '{}');
await flushPromises();
expect(logger.error).toHaveBeenCalledWith('Failed to add group, missing friendly_name!');
});
it('Shouldnt do anything on unsupported topic', async () => {
await flushPromises();
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/config/not_supported', 'to_be_removed');
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(0);
});
it('Should allow to remove device', async () => {
controller.state.state = {'0x000b57fffec6a5b3': {brightness: 100}};
const device = zigbeeHerdsman.devices.bulb_color;
device.removeFromNetwork.mockClear();
expect(settings.get().ban.length).toBe(0);
await flushPromises();
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/config/remove', 'bulb_color');
await flushPromises();
expect(device.removeFromNetwork).toHaveBeenCalledTimes(1);
expect(controller.state[device.ieeeAddr]).toBeUndefined();
expect(settings.getDevice('bulb_color')).toBeNull();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/log',
JSON.stringify({type: 'device_removed', message: 'bulb_color'}),
{qos: 0, retain: false},
expect.any(Function)
);
expect(controller.state.state).toStrictEqual({});
expect(settings.get().ban.length).toBe(0);
});
it('Should allow to force remove device', async () => {
controller.state.state = {'0x000b57fffec6a5b3': {brightness: 100}};
const device = zigbeeHerdsman.devices.bulb_color;
device.removeFromDatabase.mockClear();
expect(settings.get().ban.length).toBe(0);
await flushPromises();
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/config/force_remove', 'bulb_color');
await flushPromises();
expect(device.removeFromDatabase).toHaveBeenCalledTimes(1);
expect(controller.state[device.ieeeAddr]).toBeUndefined();
expect(settings.getDevice('bulb_color')).toBeNull();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/log',
JSON.stringify({type: 'device_force_removed', message: 'bulb_color'}),
{qos: 0, retain: false},
expect.any(Function)
);
expect(controller.state.state).toStrictEqual({});
expect(settings.get().ban.length).toBe(0);
});
it('Should allow to ban device', async () => {
const device = zigbeeHerdsman.devices.bulb_color;
device.removeFromNetwork.mockClear();
expect(settings.get().ban.length).toBe(0);
await flushPromises();
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/config/ban', 'bulb_color');
await flushPromises();
expect(device.removeFromNetwork).toHaveBeenCalledTimes(1);
expect(controller.state[device.ieeeAddr]).toBeUndefined();
expect(settings.getDevice('bulb_color')).toBeNull();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/log',
JSON.stringify({type: 'device_banned', message: 'bulb_color'}),
{qos: 0, retain: false},
expect.any(Function)
);
expect(settings.get().ban).toStrictEqual(['0x000b57fffec6a5b3']);
});
it('Shouldnt crash when removing non-existing device', async () => {
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/config/remove', 'not_existing_123');
await flushPromises();
expect(logger.error).toHaveBeenCalledWith(`Cannot remove, device 'not_existing_123' does not exist`);
});
it('Should handle when remove fails', async () => {
const device = zigbeeHerdsman.devices.bulb_color;
device.removeFromNetwork.mockClear();
device.removeFromNetwork.mockImplementationOnce(() => {throw new Error('')})
await flushPromises();
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/config/remove', 'bulb_color');
await flushPromises();
expect(device.removeFromNetwork).toHaveBeenCalledTimes(1);
expect(MQTT.publish).toHaveBeenCalledTimes(1);
expect(settings.getDevice('bulb_color')).toStrictEqual({"ID": "0x000b57fffec6a5b3", "friendlyName": "bulb_color", "friendly_name": "bulb_color", "retain": false})
expect(MQTT.publish).toHaveBeenCalledTimes(1);
});
it('Should handle when ban fails', async () => {
const device = zigbeeHerdsman.devices.bulb_color;
device.removeFromNetwork.mockClear();
device.removeFromNetwork.mockImplementationOnce(() => {throw new Error('')})
await flushPromises();
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/config/ban', 'bulb_color');
await flushPromises();
expect(device.removeFromNetwork).toHaveBeenCalledTimes(1);
expect(MQTT.publish).toHaveBeenCalledTimes(1);
expect(settings.getDevice('bulb_color')).toStrictEqual({"ID": "0x000b57fffec6a5b3", "friendlyName": "bulb_color", "friendly_name": "bulb_color", "retain": false})
expect(MQTT.publish).toHaveBeenCalledTimes(1);
});
it('Should allow to touchlink factory reset (OK)', async () => {
zigbeeHerdsman.touchlinkFactoryReset.mockClear();
zigbeeHerdsman.touchlinkFactoryReset.mockReturnValueOnce(true);
MQTT.events.message('zigbee2mqtt/bridge/config/touchlink/factory_reset', '');
await flushPromises();
expect(zigbeeHerdsman.touchlinkFactoryReset).toHaveBeenCalledTimes(1);
expect(logger.info).toHaveBeenCalledWith('Successfully factory reset device through Touchlink');
});
it('Should allow to touchlink factory reset (FAILS)', async () => {
zigbeeHerdsman.touchlinkFactoryReset.mockClear();
zigbeeHerdsman.touchlinkFactoryReset.mockReturnValueOnce(false);
MQTT.events.message('zigbee2mqtt/bridge/config/touchlink/factory_reset', '');
await flushPromises();
expect(zigbeeHerdsman.touchlinkFactoryReset).toHaveBeenCalledTimes(1);
expect(logger.warn).toHaveBeenCalledWith('Failed to factory reset device through Touchlink');
});
});
+111
View File
@@ -0,0 +1,111 @@
const tmp = require('tmp');
const dir = tmp.dirSync();
let settings;
const fs = require('fs');
const path = require('path');
const data = require('./stub/data');
let stdOutWriteOriginal;
const rimraf = require('rimraf');
describe('Logger', () => {
beforeEach(async () => {
data.writeDefaultConfiguration();
jest.resetModules();
settings = require('../lib/util/settings');
settings.set(['advanced', 'log_directory'], dir.name + '/%TIMESTAMP%');
settings._reRead();
stdOutWriteOriginal = console._stdout.write;
console._stdout.write = () => {};
});
afterEach(async () => {
console._stdout.write = stdOutWriteOriginal;
});
it('Create log directory', () => {
const logger = require('../lib/util/logger.js');
const dirs = fs.readdirSync(dir.name);
expect(dirs.length).toBe(1);
});
it('Should cleanup', () => {
const logger = require('../lib/util/logger.js');
for (const d of fs.readdirSync(dir.name)) {
rimraf.sync(path.join(dir.name, d));
}
for (let i = 0; i < 21; i++) {
fs.mkdirSync(path.join(dir.name, `log_${i}`));
}
expect(fs.readdirSync(dir.name).length).toBe(21);
logger.cleanup();
expect(fs.readdirSync(dir.name).length).toBe(10);
})
it('Should not cleanup when there is no timestamp set', () => {
const logger = require('../lib/util/logger.js');
for (let i = 30; i < 40; i++) {
fs.mkdirSync(path.join(dir.name, `log_${i}`));
}
settings.set(['advanced', 'log_directory'], dir.name + '/bla');
expect(fs.readdirSync(dir.name).length).toBe(20);
logger.cleanup();
expect(fs.readdirSync(dir.name).length).toBe(20);
})
it('Set and get log level', () => {
const logger = require('../lib/util/logger.js');
logger.setLevel('debug');
expect(logger.getLevel()).toBe('debug');
});
it('Logger should be console and file by default', () => {
const logger = require('../lib/util/logger.js');
const pipes = logger._readableState.pipes;
expect(pipes.length).toBe(2);
expect(pipes[0].constructor.name).toBe('Console');
expect(pipes[0].silent).toBe(false);
expect(pipes[1].constructor.name).toBe('File');
expect(pipes[1].dirname.startsWith(dir.name)).toBeTruthy();
});
it('Logger can be file only', () => {
settings.set(['advanced', 'log_output'], ['file']);
const logger = require('../lib/util/logger.js');
const pipes = logger._readableState.pipes;
expect(pipes.length).toBe(2);
expect(pipes[0].constructor.name).toBe('Console');
expect(pipes[0].silent).toBe(true);
expect(pipes[1].constructor.name).toBe('File');
expect(pipes[1].dirname.startsWith(dir.name)).toBeTruthy();
});
it('Logger can be console only', () => {
settings.set(['advanced', 'log_output'], ['console']);
const logger = require('../lib/util/logger.js');
const pipes = logger._readableState.pipes;
expect(pipes.constructor.name).toBe('Console');
expect(pipes.silent).toBe(false);
});
it('Logger can be nothing', () => {
settings.set(['advanced', 'log_output'], []);
const logger = require('../lib/util/logger.js');
const pipes = logger._readableState.pipes;
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();
});
});
+310
View File
@@ -0,0 +1,310 @@
const data = require('./stub/data');
const logger = require('./stub/logger');
const zigbeeHerdsman = require('./stub/zigbeeHerdsman');
const {coordinator, bulb, bulb_color, WXKG02LM, CC2530_ROUTER, unsupported_router} = zigbeeHerdsman.devices;
zigbeeHerdsman.returnDevices.push(coordinator.ieeeAddr);
zigbeeHerdsman.returnDevices.push(bulb.ieeeAddr);
zigbeeHerdsman.returnDevices.push(bulb_color.ieeeAddr);
zigbeeHerdsman.returnDevices.push(WXKG02LM.ieeeAddr);
zigbeeHerdsman.returnDevices.push(CC2530_ROUTER.ieeeAddr);
zigbeeHerdsman.returnDevices.push(unsupported_router.ieeeAddr);
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));
Date.now = jest.fn()
Date.now.mockReturnValue(10000);
const mocksClear = [MQTT.publish, logger.warn, logger.debug];
describe('Networkmap', () => {
let controller;
beforeAll(async () => {
data.writeDefaultConfiguration();
settings._reRead();
data.writeEmptyState();
settings.set(['experimental', 'new_api'], true);
controller = new Controller();
await controller.start();
mocksClear.forEach((m) => m.mockClear());
await flushPromises();
});
beforeEach(async () => {
mocksClear.forEach((m) => m.mockClear());
await flushPromises();
});
function mock() {
/**
* Topology
*
* | -> bulb_color -> unsupported_router (offline)
* coordinator | ^ ^
* | | | (not valid)
* | -> bulb |
* | -> CC2530_ROUTER -> WXKG02LM
*
*/
coordinator.lqi = () => {return {neighbors: [
{ieeeAddr: bulb_color.ieeeAddr, networkAddress: bulb_color.networkAddress, relationship: 2, depth: 1, linkquality: 120},
{ieeeAddr: bulb.ieeeAddr, networkAddress: bulb.networkAddress, relationship: 2, depth: 1, linkquality: 92}
]}};
coordinator.routingTable = () => {return {table: [
{destinationAddress: CC2530_ROUTER.networkAddress, status: 'ACTIVE', nextHop: bulb.networkAddress},
]}};
bulb.lqi = () => {return {neighbors: [
{ieeeAddr: bulb_color.ieeeAddr, networkAddress: bulb_color.networkAddress, relationship: 1, depth: 2, linkquality: 110},
{ieeeAddr: CC2530_ROUTER.ieeeAddr, networkAddress: CC2530_ROUTER.networkAddress, relationship: 1, depth: 2, linkquality: 100}
]}};
bulb.routingTable = () => {return {table: []}};
bulb_color.lqi = () => {return {neighbors: []}}
bulb_color.routingTable = () => {return {table: []}};
CC2530_ROUTER.lqi = () => {return {neighbors: [
{ieeeAddr: WXKG02LM.ieeeAddr, networkAddress: WXKG02LM.networkAddress, relationship: 1, depth: 2, linkquality: 130},
{ieeeAddr: bulb_color.ieeeAddr, networkAddress: bulb_color.networkAddress, relationship: 4, depth: 2, linkquality: 130},
]}};
CC2530_ROUTER.routingTable = () => {return {table: []}};
unsupported_router.lqi = () => {throw new Error('failed')};
unsupported_router.routingTable = () => {throw new Error('failed')};
}
it('Output raw networkmap legacy api', async () => {
mock();
MQTT.events.message('zigbee2mqtt/bridge/networkmap/routes', 'raw');
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(1);
let call = MQTT.publish.mock.calls[0];
expect(call[0]).toStrictEqual('zigbee2mqtt/bridge/networkmap/raw');
const conv = (device) => {return {ieeeAddr: device.ieeeAddr, networkAddress: device.networkAddress}};
const expected = {
"nodes":[
{"lastSeen": 1000,"ieeeAddr":coordinator.ieeeAddr,"friendlyName":"Coordinator","type":"Coordinator","networkAddress":0,"modelID":null,"failed":[]},
{"lastSeen": 1000,"ieeeAddr":bulb.ieeeAddr,"friendlyName":"bulb","type":"Router","networkAddress":40369,"modelID":"TRADFRI bulb E27 WS opal 980lm","failed":[]},
{"lastSeen": 1000,"ieeeAddr":bulb_color.ieeeAddr,"friendlyName":"bulb_color","type":"Router","networkAddress":40399,"modelID":"LLC020","failed":[]},
{"lastSeen": 1000,"ieeeAddr":WXKG02LM.ieeeAddr,"friendlyName":"button_double_key","type":"EndDevice","networkAddress":6538,"modelID":"lumi.sensor_86sw2.es1"},
{"lastSeen": 1000,"ieeeAddr":unsupported_router.ieeeAddr,"friendlyName":"0x0017880104e45525","type":"Router","networkAddress":6536,"modelID":"notSupportedModelID","manufacturerName": "Boef","failed":['lqi', 'routingTable']},
{"lastSeen": 1000,"ieeeAddr":CC2530_ROUTER.ieeeAddr,"friendlyName":"cc2530_router","type":"Router","networkAddress":6540,"modelID":"lumi.router","failed":[]},
],
"links":[
{depth: 1, linkquality: 120, routes: [], source: conv(bulb_color), target: conv(coordinator), sourceIeeeAddr: bulb_color.ieeeAddr, sourceNwkAddr: bulb_color.networkAddress, targetIeeeAddr: coordinator.ieeeAddr, lqi: 120, relationship: 2},
{depth: 1, linkquality: 92, routes: [{destinationAddress: CC2530_ROUTER.networkAddress, status: 'ACTIVE', nextHop: bulb.networkAddress}], source: conv(bulb), target: conv(coordinator), sourceIeeeAddr: bulb.ieeeAddr, sourceNwkAddr: bulb.networkAddress, targetIeeeAddr: coordinator.ieeeAddr, lqi: 92, relationship: 2},
{depth: 2, linkquality: 110, routes: [], source: conv(bulb_color), target: conv(bulb), sourceIeeeAddr: bulb_color.ieeeAddr, sourceNwkAddr: bulb_color.networkAddress, targetIeeeAddr: bulb.ieeeAddr, lqi: 110, relationship: 1},
{depth: 2, linkquality: 100, routes: [], source: conv(CC2530_ROUTER), target: conv(bulb), sourceIeeeAddr: CC2530_ROUTER.ieeeAddr, sourceNwkAddr: CC2530_ROUTER.networkAddress, targetIeeeAddr: bulb.ieeeAddr, lqi: 100, relationship: 1},
{depth: 2, linkquality: 130, routes: [], source: conv(WXKG02LM), target: conv(CC2530_ROUTER), sourceIeeeAddr: WXKG02LM.ieeeAddr, sourceNwkAddr: WXKG02LM.networkAddress, targetIeeeAddr: CC2530_ROUTER.ieeeAddr, lqi: 130, relationship: 1}
]
};
expect(JSON.parse(call[1])).toStrictEqual(expected);
/**
* Check again without routes
*/
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/networkmap', 'raw');
await flushPromises();
call = MQTT.publish.mock.calls[0];
expect(MQTT.publish).toHaveBeenCalledTimes(1);
expect(call[0]).toStrictEqual('zigbee2mqtt/bridge/networkmap/raw');
// Remove routing information
expected.nodes.forEach((n) => {
if (n.failed && n.failed.includes('routingTable')) {
n.failed.splice(n.failed.indexOf('routingTable'), 1);
}
});
expected.links.forEach((l) => l.routes = [])
expect(JSON.parse(call[1])).toStrictEqual(expected);
});
it('Output graphviz networkmap legacy api', async () => {
mock();
const device = zigbeeHerdsman.devices.bulb_color;
device.lastSeen = null;
const endpoint = device.getEndpoint(1);
const data = {modelID: 'test'}
const payload = {data, cluster: 'genOnOff', device, endpoint, type: 'readResponse', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
MQTT.events.message('zigbee2mqtt/bridge/networkmap/routes', 'graphviz');
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(1);
let call = MQTT.publish.mock.calls[0];
expect(call[0]).toStrictEqual('zigbee2mqtt/bridge/networkmap/graphviz');
const expected = `digraph G {
node[shape=record];
"0x00124b00120144ae" [style="bold, filled", fillcolor="#e04e5d", fontcolor="#ffffff", label="{Coordinator|0x00124b00120144ae (0)|0 seconds ago}"];
"0x000b57fffec6a5b2" [style="rounded, filled", fillcolor="#4ea3e0", fontcolor="#ffffff", label="{bulb|0x000b57fffec6a5b2 (40369)|IKEA TRADFRI LED bulb E26/E27 980 lumen, dimmable, white spectrum, opal white (LED1545G12)|9 seconds ago}"];
"0x000b57fffec6a5b2" -> "0x00124b00120144ae" [penwidth=2, weight=1, color="#009900", label="92 (routes: 6540)"]
"0x000b57fffec6a5b3" [style="rounded, filled", fillcolor="#4ea3e0", fontcolor="#ffffff", label="{bulb_color|0x000b57fffec6a5b3 (40399)|Philips Hue Go (7146060PH)|unknown}"];
"0x000b57fffec6a5b3" -> "0x00124b00120144ae" [penwidth=0.5, weight=0, color="#994444", label="120"]
"0x000b57fffec6a5b3" -> "0x000b57fffec6a5b2" [penwidth=0.5, weight=0, color="#994444", label="110"]
"0x0017880104e45521" [style="rounded, dashed, filled", fillcolor="#fff8ce", fontcolor="#000000", label="{button_double_key|0x0017880104e45521 (6538)|Xiaomi Aqara double key wireless wall switch (WXKG02LM)|9 seconds ago}"];
"0x0017880104e45521" -> "0x0017880104e45559" [penwidth=1, weight=0, color="#994444", label="130"]
"0x0017880104e45525" [style="rounded, filled", fillcolor="#4ea3e0", fontcolor="#ffffff", label="{0x0017880104e45525|0x0017880104e45525 (6536)failed: lqi,routingTable|Boef notSupportedModelID|9 seconds ago}"];
"0x0017880104e45559" [style="rounded, filled", fillcolor="#4ea3e0", fontcolor="#ffffff", label="{cc2530_router|0x0017880104e45559 (6540)|Custom devices (DiY) [CC2530 router](http://ptvo.info/cc2530-based-zigbee-coordinator-and-router-112/) (CC2530.ROUTER)|9 seconds ago}"];
"0x0017880104e45559" -> "0x000b57fffec6a5b2" [penwidth=0.5, weight=0, color="#994444", label="100"]
}`;
const expectedLines = expected.split('\n');
const actualLines = call[1].split('\n');
for (let i = 0; i < expectedLines.length; i++) {
expect(actualLines[i].trim()).toStrictEqual(expectedLines[i].trim());
}
});
it('Output plantuml networkmap legacy api', async () => {
mock();
const device = zigbeeHerdsman.devices.bulb_color;
device.lastSeen = null;
const endpoint = device.getEndpoint(1);
const data = {modelID: 'test'}
const payload = {data, cluster: 'genOnOff', device, endpoint, type: 'readResponse', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
MQTT.events.message('zigbee2mqtt/bridge/networkmap/routes', 'plantuml');
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(1);
let call = MQTT.publish.mock.calls[0];
expect(call[0]).toStrictEqual('zigbee2mqtt/bridge/networkmap/plantuml');
const expected = `' paste into: https://www.planttext.com/
@startuml
card 0x0017880104e45525 [
0x0017880104e45525
---
0x0017880104e45525 (6536) failed: lqi,routingTable
---
Boef notSupportedModelID
---
9 seconds ago
]
card 0x000b57fffec6a5b2 [
bulb
---
0x000b57fffec6a5b2 (40369)
---
IKEA TRADFRI LED bulb E26/E27 980 lumen, dimmable, white spectrum, opal white (LED1545G12)
---
9 seconds ago
]
card 0x000b57fffec6a5b3 [
bulb_color
---
0x000b57fffec6a5b3 (40399)
---
Philips Hue Go (7146060PH)
---
unknown
]
card 0x0017880104e45521 [
button_double_key
---
0x0017880104e45521 (6538)
---
Xiaomi Aqara double key wireless wall switch (WXKG02LM)
---
9 seconds ago
]
card 0x0017880104e45559 [
cc2530_router
---
0x0017880104e45559 (6540)
---
Custom devices (DiY) [CC2530 router](http://ptvo.info/cc2530-based-zigbee-coordinator-and-router-112/) (CC2530.ROUTER)
---
9 seconds ago
]
card 0x00124b00120144ae [
Coordinator
---
0x00124b00120144ae (0)
---
0 seconds ago
]
0x000b57fffec6a5b3 --> 0x00124b00120144ae: 120
0x000b57fffec6a5b2 --> 0x00124b00120144ae: 92
0x000b57fffec6a5b3 --> 0x000b57fffec6a5b2: 110
0x0017880104e45559 --> 0x000b57fffec6a5b2: 100
0x0017880104e45521 --> 0x0017880104e45559: 130
@enduml`;
const expectedLines = expected.split('\n');
const actualLines = call[1].split('\n');
for (let i = 0; i < expectedLines.length; i++) {
expect(actualLines[i].trim()).toStrictEqual(expectedLines[i].trim());
}
});
it('Should output raw networkmap', async () => {
mock();
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/networkmap', JSON.stringify({type: 'raw', routes: true}));
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(1);
let call = MQTT.publish.mock.calls[0];
expect(call[0]).toStrictEqual('zigbee2mqtt/bridge/response/networkmap');
const conv = (device) => {return {ieeeAddr: device.ieeeAddr, networkAddress: device.networkAddress}};
const expected = {
status: 'ok',
data: {
type: 'raw',
routes: true,
value: {
"nodes":[
{"lastSeen": 1000,"ieeeAddr":coordinator.ieeeAddr,"friendlyName":"Coordinator","type":"Coordinator","networkAddress":0,"modelID":null,"failed":[]},
{"lastSeen": 1000,"ieeeAddr":bulb.ieeeAddr,"friendlyName":"bulb","type":"Router","networkAddress":40369,"modelID":"TRADFRI bulb E27 WS opal 980lm","failed":[]},
{"lastSeen": null,"ieeeAddr":bulb_color.ieeeAddr,"friendlyName":"bulb_color","type":"Router","networkAddress":40399,"modelID":"LLC020","failed":[]},
{"lastSeen": 1000,"ieeeAddr":WXKG02LM.ieeeAddr,"friendlyName":"button_double_key","type":"EndDevice","networkAddress":6538,"modelID":"lumi.sensor_86sw2.es1"},
{"lastSeen": 1000,"ieeeAddr":unsupported_router.ieeeAddr,"friendlyName":"0x0017880104e45525","type":"Router","networkAddress":6536,"modelID":"notSupportedModelID","manufacturerName": "Boef","failed":['lqi', 'routingTable']},
{"lastSeen": 1000,"ieeeAddr":CC2530_ROUTER.ieeeAddr,"friendlyName":"cc2530_router","type":"Router","networkAddress":6540,"modelID":"lumi.router","failed":[]},
],
"links":[
{depth: 1, linkquality: 120, routes: [], source: conv(bulb_color), target: conv(coordinator), sourceIeeeAddr: bulb_color.ieeeAddr, sourceNwkAddr: bulb_color.networkAddress, targetIeeeAddr: coordinator.ieeeAddr, lqi: 120, relationship: 2},
{depth: 1, linkquality: 92, routes: [{destinationAddress: CC2530_ROUTER.networkAddress, status: 'ACTIVE', nextHop: bulb.networkAddress}], source: conv(bulb), target: conv(coordinator), sourceIeeeAddr: bulb.ieeeAddr, sourceNwkAddr: bulb.networkAddress, targetIeeeAddr: coordinator.ieeeAddr, lqi: 92, relationship: 2},
{depth: 2, linkquality: 110, routes: [], source: conv(bulb_color), target: conv(bulb), sourceIeeeAddr: bulb_color.ieeeAddr, sourceNwkAddr: bulb_color.networkAddress, targetIeeeAddr: bulb.ieeeAddr, lqi: 110, relationship: 1},
{depth: 2, linkquality: 100, routes: [], source: conv(CC2530_ROUTER), target: conv(bulb), sourceIeeeAddr: CC2530_ROUTER.ieeeAddr, sourceNwkAddr: CC2530_ROUTER.networkAddress, targetIeeeAddr: bulb.ieeeAddr, lqi: 100, relationship: 1},
{depth: 2, linkquality: 130, routes: [], source: conv(WXKG02LM), target: conv(CC2530_ROUTER), sourceIeeeAddr: WXKG02LM.ieeeAddr, sourceNwkAddr: WXKG02LM.networkAddress, targetIeeeAddr: CC2530_ROUTER.ieeeAddr, lqi: 130, relationship: 1}
]
}
}
};
const actual = JSON.parse(call[1]);
actual.data.value = JSON.parse(actual.data.value);
expect(actual).toStrictEqual(expected);
});
it('Should throw error when rquesting invalid type', async () => {
mock();
MQTT.publish.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/request/networkmap', 'not_existing');
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/networkmap',
JSON.stringify({"data":{},"status":"error","error":"Type 'not_existing' not supported, allowed are: raw,graphviz,plantuml"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
});
+75
View File
@@ -0,0 +1,75 @@
const data = require('./stub/data');
const logger = require('./stub/logger');
const zigbeeHerdsman = require('./stub/zigbeeHerdsman');
zigbeeHerdsman.returnDevices.push('0x00124b00120144ae');
zigbeeHerdsman.returnDevices.push('0x0017880104e45560');
const MQTT = require('./stub/mqtt');
const settings = require('../lib/util/settings');
const Controller = require('../lib/controller');
const flushPromises = () => new Promise(setImmediate);
const mockExit = jest.spyOn(process, 'exit').mockImplementation(() => {});
const mocksClear = [MQTT.publish, logger.warn, logger.debug];
const zigbeeHerdsmanConverters = require('zigbee-herdsman-converters');
const mockOnEvent = jest.fn();
const mappedLivolo = zigbeeHerdsmanConverters.findByDevice(zigbeeHerdsman.devices.LIVOLO);
mappedLivolo.onEvent = mockOnEvent;
zigbeeHerdsmanConverters.onEvent = jest.fn();
describe('On event', () => {
let controller;
const device = zigbeeHerdsman.devices.LIVOLO;
beforeEach(async () => {
data.writeDefaultConfiguration();
settings._reRead();
data.writeEmptyState();
controller = new Controller();
await controller.start();
mocksClear.forEach((m) => m.mockClear());
zigbeeHerdsmanConverters.onEvent.mockClear();
await flushPromises();
});
it('Should call with start event', async () => {
expect(mockOnEvent).toHaveBeenCalledTimes(1);
const call = mockOnEvent.mock.calls[0];
expect(call[0]).toBe('start')
expect(call[1]).toStrictEqual({})
expect(call[2]).toBe(device);
});
it('Should call with stop event', async () => {
mockOnEvent.mockClear();
await controller.stop();
await flushPromises();
expect(mockOnEvent).toHaveBeenCalledTimes(1);
const call = mockOnEvent.mock.calls[0];
expect(call[0]).toBe('stop')
expect(call[1]).toStrictEqual({})
expect(call[2]).toBe(device);
});
it('Should call with zigbee event', async () => {
mockOnEvent.mockClear();
await zigbeeHerdsman.events.deviceAnnounce({device});
await flushPromises();
expect(mockOnEvent).toHaveBeenCalledTimes(1);
const call = mockOnEvent.mock.calls[0];
expect(call[0]).toBe('deviceAnnounce')
expect(call[1]).toStrictEqual({device})
expect(call[2]).toBe(device);
});
it('Should call index onEvent with zigbee event', async () => {
zigbeeHerdsmanConverters.onEvent.mockClear();
await zigbeeHerdsman.events.deviceAnnounce({device});
await flushPromises();
expect(zigbeeHerdsmanConverters.onEvent).toHaveBeenCalledTimes(1);
const call = zigbeeHerdsmanConverters.onEvent.mock.calls[0];
expect(call[0]).toBe('deviceAnnounce')
expect(call[1]).toStrictEqual({device})
expect(call[2]).toBe(device);
});
});
+360
View File
@@ -0,0 +1,360 @@
const data = require('./stub/data');
const logger = require('./stub/logger');
const zigbeeHerdsman = require('./stub/zigbeeHerdsman');
const MQTT = require('./stub/mqtt');
const settings = require('../lib/util/settings');
const Controller = require('../lib/controller');
const flushPromises = () => new Promise(setImmediate);
const zigbeeHerdsmanConverters = require('zigbee-herdsman-converters');
describe('OTA update', () => {
let controller;
mockClear = (mapped) => {
mapped.ota.updateToLatest = jest.fn();
mapped.ota.isUpdateAvailable = jest.fn();
}
beforeEach(async () => {
data.writeDefaultConfiguration();
settings._reRead();
settings.set(['experimental', 'new_api'], true);
data.writeEmptyState();
controller = new Controller();
await controller.start();
await flushPromises();
MQTT.publish.mockClear();
});
it('Should subscribe to topics', async () => {
expect(MQTT.subscribe).toHaveBeenCalledWith('zigbee2mqtt/bridge/ota_update/check');
expect(MQTT.subscribe).toHaveBeenCalledWith('zigbee2mqtt/bridge/ota_update/update');
expect(MQTT.subscribe).toHaveBeenCalledWith('zigbee2mqtt/bridge/request/device/ota_update/check');
expect(MQTT.subscribe).toHaveBeenCalledWith('zigbee2mqtt/bridge/request/device/ota_update/update');
});
it('Should OTA update a device', async () => {
const device = zigbeeHerdsman.devices.bulb;
const endpoint = device.endpoints[0];
let count = 0;
endpoint.read.mockImplementation(() => {
count++;
return {swBuildId: count, dateCode: '2019010' + count}
});
const mapped = zigbeeHerdsmanConverters.findByDevice(device)
mockClear(mapped);
logger.info.mockClear();
device.save.mockClear();
mapped.ota.updateToLatest.mockImplementationOnce((a, b, onUpdate) => {
onUpdate(0, null);
onUpdate(10, 3600);
});
MQTT.events.message('zigbee2mqtt/bridge/request/device/ota_update/update', 'bulb');
await flushPromises();
expect(logger.info).toHaveBeenCalledWith(`Updating 'bulb' to latest firmware`);
expect(mapped.ota.isUpdateAvailable).toHaveBeenCalledTimes(0);
expect(mapped.ota.updateToLatest).toHaveBeenCalledTimes(1);
expect(mapped.ota.updateToLatest).toHaveBeenCalledWith(device, logger, expect.any(Function));
expect(logger.info).toHaveBeenCalledWith(`Update of 'bulb' at 0.00%`);
expect(logger.info).toHaveBeenCalledWith(`Update of 'bulb' at 10.00%, +- 60 minutes remaining`);
expect(logger.info).toHaveBeenCalledWith(`Finished update of 'bulb', from '{"softwareBuildID":1,"dateCode":"20190101"}' to '{"softwareBuildID":2,"dateCode":"20190102"}'`);
expect(device.save).toHaveBeenCalledTimes(1);
expect(device.dateCode).toBe('20190102');
expect(device.softwareBuildID).toBe(2);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/ota_update/update',
JSON.stringify({"data":{"id": "bulb","from":{"software_build_id":1,"date_code":"20190101"},"to":{"software_build_id":2,"date_code":"20190102"}},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should handle when OTA update fails', async () => {
const device = zigbeeHerdsman.devices.bulb;
const endpoint = device.endpoints[0];
endpoint.read.mockImplementation(() => {return {swBuildId: 1, dateCode: '2019010'}});
const mapped = zigbeeHerdsmanConverters.findByDevice(device)
mockClear(mapped);
device.save.mockClear();
mapped.ota.updateToLatest.mockImplementationOnce((a, b, onUpdate) => {
throw new Error('Update failed');
});
MQTT.events.message('zigbee2mqtt/bridge/request/device/ota_update/update', JSON.stringify({id: "bulb"}));
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/ota_update/update',
JSON.stringify({"data":{"id": "bulb"},"status":"error","error":"Update of 'bulb' failed (Update failed)"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should be able to check if OTA update is available', async () => {
const device = zigbeeHerdsman.devices.bulb;
const mapped = zigbeeHerdsmanConverters.findByDevice(device)
mockClear(mapped);
mapped.ota.isUpdateAvailable.mockReturnValueOnce(false);
MQTT.events.message('zigbee2mqtt/bridge/request/device/ota_update/check', "bulb");
await flushPromises();
expect(mapped.ota.isUpdateAvailable).toHaveBeenCalledTimes(1);
expect(mapped.ota.updateToLatest).toHaveBeenCalledTimes(0);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/ota_update/check',
JSON.stringify({"data":{"id": "bulb","updateAvailable":false},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
MQTT.publish.mockClear();
mapped.ota.isUpdateAvailable.mockReturnValueOnce(true);
MQTT.events.message('zigbee2mqtt/bridge/request/device/ota_update/check', "bulb");
await flushPromises();
expect(mapped.ota.isUpdateAvailable).toHaveBeenCalledTimes(2);
expect(mapped.ota.updateToLatest).toHaveBeenCalledTimes(0);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/ota_update/check',
JSON.stringify({"data":{"id": "bulb","updateAvailable":true},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should handle if OTA update check fails', async () => {
const device = zigbeeHerdsman.devices.bulb;
const mapped = zigbeeHerdsmanConverters.findByDevice(device)
mockClear(mapped);
mapped.ota.isUpdateAvailable.mockImplementationOnce(() => {throw new Error('RF singals disturbed because of dogs barking')});
MQTT.events.message('zigbee2mqtt/bridge/request/device/ota_update/check', "bulb");
await flushPromises();
expect(mapped.ota.isUpdateAvailable).toHaveBeenCalledTimes(1);
expect(mapped.ota.updateToLatest).toHaveBeenCalledTimes(0);
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/ota_update/check',
JSON.stringify({"data":{"id": "bulb"},"status":"error","error": `Failed to check if update available for 'bulb' (RF singals disturbed because of dogs barking)`}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should fail when device does not exist', async () => {
MQTT.events.message('zigbee2mqtt/bridge/request/device/ota_update/check', "not_existing_deviceooo");
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/ota_update/check',
JSON.stringify({"data":{"id": "not_existing_deviceooo"},"status":"error","error": `Device 'not_existing_deviceooo' does not exist`}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should not check for OTA when device does not support it', async () => {
MQTT.events.message('zigbee2mqtt/bridge/request/device/ota_update/check', "ZNLDP12LM");
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/ota_update/check',
JSON.stringify({"data":{"id": "ZNLDP12LM"},"status":"error","error": `Device 'ZNLDP12LM' does not support OTA updates`}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should refuse to check/update when already in progress', async () => {
jest.useFakeTimers();
const device = zigbeeHerdsman.devices.bulb;
const mapped = zigbeeHerdsmanConverters.findByDevice(device)
mockClear(mapped);
mapped.ota.isUpdateAvailable.mockImplementationOnce(() => {
return new Promise((resolve, reject) => {setTimeout(() => resolve(), 99999)})
});
MQTT.events.message('zigbee2mqtt/bridge/request/device/ota_update/check', "bulb");
await flushPromises();
MQTT.events.message('zigbee2mqtt/bridge/request/device/ota_update/check', "bulb");
await flushPromises();
expect(mapped.ota.isUpdateAvailable).toHaveBeenCalledTimes(1);
jest.runAllTimers();
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/ota_update/check',
JSON.stringify({"data":{"id": "bulb"},"status":"error","error": `Update or check for update already in progress for 'bulb'`}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Shouldnt crash when read modelID before/after OTA update fails', async () => {
const device = zigbeeHerdsman.devices.bulb;
const endpoint = device.endpoints[0];
let count = 0;
endpoint.read.mockImplementation(() => {throw new Error('Failed!')});
const mapped = zigbeeHerdsmanConverters.findByDevice(device)
mockClear(mapped);
MQTT.events.message('zigbee2mqtt/bridge/request/device/ota_update/update', "bulb");
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledWith(
'zigbee2mqtt/bridge/response/device/ota_update/update',
JSON.stringify({"data":{"id":"bulb","from":null,"to":null},"status":"ok"}),
{retain: false, qos: 0}, expect.any(Function)
);
});
it('Should check for update when device requests it', async () => {
const device = zigbeeHerdsman.devices.bulb;
const data = {imageType: 12382};
const mapped = zigbeeHerdsmanConverters.findByDevice(device)
mockClear(mapped);
mapped.ota.isUpdateAvailable.mockReturnValueOnce(true);
const payload = {data, cluster: 'genOta', device, endpoint: device.getEndpoint(1), type: 'commandQueryNextImageRequest', linkquality: 10};
logger.info.mockClear();
await zigbeeHerdsman.events.message(payload);
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(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);
await flushPromises();
expect(mapped.ota.isUpdateAvailable).toHaveBeenCalledTimes(1);
const extension = controller.extensions.find((e) => e.constructor.name === 'OTAUpdate');
extension.lastChecked = {};
logger.info.mockClear();
mapped.ota.isUpdateAvailable.mockReturnValueOnce(false);
await zigbeeHerdsman.events.message(payload);
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});
});
it('Shouldnt respond with NO_IMAGE_AVAILABLE when not supporting OTA and device has no OTA endpoint', async () => {
const device = zigbeeHerdsman.devices.QBKG03LM;
const data = {imageType: 12382};
const payload = {data, cluster: 'genOta', device, endpoint: device.getEndpoint(1), type: 'commandQueryNextImageRequest', linkquality: 10};
logger.error.mockClear();
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(device.endpoints[0].commandResponse).toHaveBeenCalledTimes(0);
expect(logger.error).toHaveBeenCalledTimes(0);
});
it('Legacy api: Should OTA update a device', async () => {
const device = zigbeeHerdsman.devices.bulb;
const endpoint = device.endpoints[0];
let count = 0;
endpoint.read.mockImplementation(() => {
count++;
return {swBuildId: count, dateCode: '2019010' + count}
});
const mapped = zigbeeHerdsmanConverters.findByDevice(device)
mockClear(mapped);
logger.info.mockClear();
logger.error.mockClear();
device.save.mockClear();
mapped.ota.updateToLatest.mockImplementationOnce((a, b, onUpdate) => {
onUpdate(0, null);
onUpdate(10, 3600);
});
MQTT.events.message('zigbee2mqtt/bridge/ota_update/update', 'bulb');
await flushPromises();
expect(logger.info).toHaveBeenCalledWith(`Updating 'bulb' to latest firmware`);
expect(mapped.ota.isUpdateAvailable).toHaveBeenCalledTimes(0);
expect(mapped.ota.updateToLatest).toHaveBeenCalledTimes(1);
expect(mapped.ota.updateToLatest).toHaveBeenCalledWith(device, logger, expect.any(Function));
expect(logger.info).toHaveBeenCalledWith(`Update of 'bulb' at 0.00%`);
expect(logger.info).toHaveBeenCalledWith(`Update of 'bulb' at 10.00%, +- 60 minutes remaining`);
expect(logger.info).toHaveBeenCalledWith(`Finished update of 'bulb', from '{"softwareBuildID":1,"dateCode":"20190101"}' to '{"softwareBuildID":2,"dateCode":"20190102"}'`);
expect(logger.error).toHaveBeenCalledTimes(0);
expect(device.save).toHaveBeenCalledTimes(1);
expect(device.dateCode).toBe('20190102');
expect(device.softwareBuildID).toBe(2);
});
it('Legacy api: Should handle when OTA update fails', async () => {
const device = zigbeeHerdsman.devices.bulb;
const endpoint = device.endpoints[0];
endpoint.read.mockImplementation(() => {return {swBuildId: 1, dateCode: '2019010'}});
const mapped = zigbeeHerdsmanConverters.findByDevice(device)
mockClear(mapped);
logger.info.mockClear();
logger.error.mockClear();
device.save.mockClear();
mapped.ota.updateToLatest.mockImplementationOnce((a, b, onUpdate) => {
throw new Error('Update failed');
});
MQTT.events.message('zigbee2mqtt/bridge/ota_update/update', 'bulb');
await flushPromises();
expect(logger.error).toHaveBeenCalledTimes(1);
expect(logger.error).toHaveBeenCalledWith(`Update of 'bulb' failed (Update failed)`);
});
it('Legacy api: Should be able to check if OTA update is available', async () => {
const device = zigbeeHerdsman.devices.bulb;
const mapped = zigbeeHerdsmanConverters.findByDevice(device)
mockClear(mapped);
logger.info.mockClear();
mapped.ota.isUpdateAvailable.mockReturnValueOnce(false);
MQTT.events.message('zigbee2mqtt/bridge/ota_update/check', 'bulb');
await flushPromises();
expect(mapped.ota.isUpdateAvailable).toHaveBeenCalledTimes(1);
expect(mapped.ota.updateToLatest).toHaveBeenCalledTimes(0);
expect(logger.info).toHaveBeenCalledWith(`No update available for 'bulb'`);
logger.info.mockClear();
mapped.ota.isUpdateAvailable.mockReturnValueOnce(true);
MQTT.events.message('zigbee2mqtt/bridge/ota_update/check', 'bulb');
await flushPromises();
expect(mapped.ota.isUpdateAvailable).toHaveBeenCalledTimes(2);
expect(mapped.ota.updateToLatest).toHaveBeenCalledTimes(0);
expect(logger.info).toHaveBeenCalledWith(`Update available for 'bulb'`);
});
it('Legacy api: Should handle if OTA update check fails', async () => {
const device = zigbeeHerdsman.devices.bulb;
const mapped = zigbeeHerdsmanConverters.findByDevice(device)
mockClear(mapped);
logger.error.mockClear();
mapped.ota.isUpdateAvailable.mockImplementationOnce(() => {throw new Error('RF singals disturbed because of dogs barking')});
MQTT.events.message('zigbee2mqtt/bridge/ota_update/check', 'bulb');
await flushPromises();
expect(mapped.ota.isUpdateAvailable).toHaveBeenCalledTimes(1);
expect(mapped.ota.updateToLatest).toHaveBeenCalledTimes(0);
expect(logger.error).toHaveBeenCalledWith(`Failed to check if update available for 'bulb' (RF singals disturbed because of dogs barking)`);
});
it('Legacy api: Should not check for OTA when device does not support it', async () => {
MQTT.events.message('zigbee2mqtt/bridge/ota_update/check', 'ZNLDP12LM');
await flushPromises();
expect(logger.error).toHaveBeenCalledWith(`Device 'ZNLDP12LM' does not support OTA updates`);
});
it('Legacy api: Shouldnt crash when read modelID after OTA update fails', async () => {
const device = zigbeeHerdsman.devices.bulb;
const endpoint = device.endpoints[0];
let count = 0;
endpoint.read.mockImplementation(() => {
if (count === 1) throw new Error('Failed!')
count++;
return {swBuildId: 1, dateCode: '2019010'}
});
const mapped = zigbeeHerdsmanConverters.findByDevice(device)
mockClear(mapped);
logger.info.mockClear();
MQTT.events.message('zigbee2mqtt/bridge/ota_update/update', 'bulb');
await flushPromises();
expect(logger.info).toHaveBeenCalledWith(`Finished update of 'bulb'`);
});
});
+1183
View File
File diff suppressed because it is too large Load Diff
+457
View File
@@ -0,0 +1,457 @@
const data = require('./stub/data');
const logger = require('./stub/logger');
const zigbeeHerdsman = require('./stub/zigbeeHerdsman');
const MQTT = require('./stub/mqtt');
const settings = require('../lib/util/settings');
const Controller = require('../lib/controller');
const flushPromises = () => new Promise(setImmediate);
const mocksClear = [MQTT.publish, logger.warn, logger.debug];
describe('Receive', () => {
let controller;
beforeEach(async () => {
jest.useRealTimers();
data.writeDefaultConfiguration();
settings._reRead();
data.writeEmptyState();
controller = new Controller();
await controller.start();
mocksClear.forEach((m) => m.mockClear());
});
it('Should handle a zigbee message', async () => {
const device = zigbeeHerdsman.devices.WXKG11LM;
const data = {onOff: 1}
const payload = {data, cluster: 'genOnOff', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(1);
expect(MQTT.publish.mock.calls[0][0]).toStrictEqual('zigbee2mqtt/button');
expect(JSON.parse(MQTT.publish.mock.calls[0][1])).toStrictEqual({click: 'single', linkquality: 10});
expect(MQTT.publish.mock.calls[0][2]).toStrictEqual({"qos": 0, "retain": false});
});
it('Should handle a zigbee message which uses ep (left)', async () => {
const device = zigbeeHerdsman.devices.WXKG02LM;
const data = {onOff: 1}
const payload = {data, cluster: 'genOnOff', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(1);
expect(MQTT.publish.mock.calls[0][0]).toStrictEqual('zigbee2mqtt/button_double_key');
expect(JSON.parse(MQTT.publish.mock.calls[0][1])).toStrictEqual({click: 'left', linkquality: 10});
expect(MQTT.publish.mock.calls[0][2]).toStrictEqual({"qos": 0, "retain": false});
});
it('Should handle a zigbee message which uses ep (right)', async () => {
const device = zigbeeHerdsman.devices.WXKG02LM;
const data = {onOff: 1}
const payload = {data, cluster: 'genOnOff', device, endpoint: device.getEndpoint(2), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(1);
expect(MQTT.publish.mock.calls[0][0]).toStrictEqual('zigbee2mqtt/button_double_key');
expect(JSON.parse(MQTT.publish.mock.calls[0][1])).toStrictEqual({click: 'right', linkquality: 10});
expect(MQTT.publish.mock.calls[0][2]).toStrictEqual({"qos": 0, "retain": false});
});
it('Should handle a zigbee message with default precision', async () => {
const device = zigbeeHerdsman.devices.WSDCGQ11LM;
const data = {measuredValue: -85}
const payload = {data, cluster: 'msTemperatureMeasurement', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
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.85, linkquality: 10});
expect(MQTT.publish.mock.calls[0][2]).toStrictEqual({"qos": 1, "retain": false});
});
it('Should debounce messages', async () => {
jest.useFakeTimers();
const device = zigbeeHerdsman.devices.WSDCGQ11LM;
settings.set(['devices', device.ieeeAddr, 'debounce'], 0.1);
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": 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;
settings.set(['devices', device.ieeeAddr, 'debounce'], 0.1);
settings.set(['devices', device.ieeeAddr, 'debounce_ignore'], ['temperature']);
const tempMsg = {data: {measuredValue: 8}, cluster: 'msTemperatureMeasurement', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 13};
await zigbeeHerdsman.events.message(tempMsg);
const pressureMsg = {data: {measuredValue: 2}, cluster: 'msPressureMeasurement', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 13};
await zigbeeHerdsman.events.message(pressureMsg);
const tempMsg2 = {data: {measuredValue: 7}, cluster: 'msTemperatureMeasurement', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 13};
await zigbeeHerdsman.events.message(tempMsg2);
const humidityMsg = {data: {measuredValue: 3}, cluster: 'msRelativeHumidity', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 13};
await zigbeeHerdsman.events.message(humidityMsg);
await flushPromises();
jest.advanceTimersByTime(50);
expect(MQTT.publish).toHaveBeenCalledTimes(1);
expect(JSON.parse(MQTT.publish.mock.calls[0][1])).toStrictEqual({temperature: 0.08, pressure: 2, linkquality: 13});
jest.runAllTimers();
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(2);
expect(JSON.parse(MQTT.publish.mock.calls[1][1])).toStrictEqual({temperature: 0.07, pressure: 2, humidity: 0.03, linkquality: 13});
});
it('Shouldnt republish old state', async () => {
// https://github.com/Koenkk/zigbee2mqtt/issues/3572
jest.useFakeTimers();
const device = zigbeeHerdsman.devices.bulb;
settings.set(['devices', device.ieeeAddr, 'debounce'], 0.1);
await zigbeeHerdsman.events.message({data: {onOff: 0}, cluster: 'genOnOff', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10});
await MQTT.events.message('zigbee2mqtt/bulb/set', JSON.stringify({state: 'ON'}));
await flushPromises();
jest.runAllTimers();
expect(MQTT.publish).toHaveBeenCalledTimes(2);
expect(JSON.parse(MQTT.publish.mock.calls[0][1])).toStrictEqual({state: 'ON'});
expect(JSON.parse(MQTT.publish.mock.calls[1][1])).toStrictEqual({state: 'ON', linkquality: 10});
});
it('Should handle a zigbee message with 1 precision', async () => {
const device = zigbeeHerdsman.devices.WSDCGQ11LM;
settings.set(['devices', device.ieeeAddr, 'temperature_precision'], 1);
const data = {measuredValue: -85}
const payload = {data, cluster: 'msTemperatureMeasurement', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
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.8, linkquality: 10});
expect(MQTT.publish.mock.calls[0][2]).toStrictEqual({"qos": 1, "retain": false});
});
it('Should handle a zigbee message with 0 precision', async () => {
const device = zigbeeHerdsman.devices.WSDCGQ11LM;
settings.set(['devices', device.ieeeAddr, 'temperature_precision'], 0);
const data = {measuredValue: -85}
const payload = {data, cluster: 'msTemperatureMeasurement', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
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: -1, linkquality: 10});
expect(MQTT.publish.mock.calls[0][2]).toStrictEqual({"qos": 1, "retain": false});
});
it('Should handle a zigbee message with 1 precision when set via device_options', async () => {
const device = zigbeeHerdsman.devices.WSDCGQ11LM;
settings.set(['device_options', 'temperature_precision'], 1);
const data = {measuredValue: -85}
const payload = {data, cluster: 'msTemperatureMeasurement', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
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.8, linkquality: 10});
expect(MQTT.publish.mock.calls[0][2]).toStrictEqual({"qos": 1, "retain": false});
});
it('Should handle a zigbee message with 2 precision when overrides device_options', async () => {
const device = zigbeeHerdsman.devices.WSDCGQ11LM;
settings.set(['device_options', 'temperature_precision'], 1);
settings.set(['devices', device.ieeeAddr, 'temperature_precision'], 0);
const data = {measuredValue: -85}
const payload = {data, cluster: 'msTemperatureMeasurement', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
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: -1, linkquality: 10});
expect(MQTT.publish.mock.calls[0][2]).toStrictEqual({"qos": 1, "retain": false});
});
it('WSDCGQ11LM pressure precision from non ZCL properties', async () => {
const device = zigbeeHerdsman.devices.WSDCGQ11LM;
settings.set(['devices', device.ieeeAddr, 'temperature_precision'], 1);
MQTT.publish.mockClear();
let payload = {data: {"65281":{"1":2985,"4":5032,"5":9,"6":[0,1],"10":0,"100":2345,"101":4608,"102":91552}}, cluster: 'genBasic', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(1);
expect(JSON.parse(MQTT.publish.mock.calls[0][1])).toStrictEqual({"battery":91,"voltage":2985,"temperature":23.5,"humidity":46.08,"pressure":915.5,"linkquality":10});
MQTT.publish.mockClear();
payload = {data: {"16":9354,"20":-1,"measuredValue":915}, cluster: 'msPressureMeasurement', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(1);
expect(JSON.parse(MQTT.publish.mock.calls[0][1])).toStrictEqual({"battery":91,"voltage":2985,"temperature":23.5,"humidity":46.08,"pressure":935.4,"linkquality":10});
});
it('Should handle a zigbee message with voltage 3010', async () => {
const device = zigbeeHerdsman.devices.WXKG02LM;
const data = {'65281': {'1': 3010}}
const payload = {data, cluster: 'genBasic', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(1);
expect(MQTT.publish.mock.calls[0][0]).toStrictEqual('zigbee2mqtt/button_double_key');
expect(JSON.parse(MQTT.publish.mock.calls[0][1])).toStrictEqual({battery: 100, voltage: 3010, linkquality: 10});
expect(MQTT.publish.mock.calls[0][2]).toStrictEqual({"qos": 0, "retain": false});
});
it('Should handle a zigbee message with voltage 2850', async () => {
const device = zigbeeHerdsman.devices.WXKG02LM;
const data = {'65281': {'1': 2850}}
const payload = {data, cluster: 'genBasic', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(1);
expect(MQTT.publish.mock.calls[0][0]).toStrictEqual('zigbee2mqtt/button_double_key');
expect(JSON.parse(MQTT.publish.mock.calls[0][1])).toStrictEqual({battery: 35, voltage: 2850, linkquality: 10});
expect(MQTT.publish.mock.calls[0][2]).toStrictEqual({"qos": 0, "retain": false});
});
it('Should handle a zigbee message with voltage 2650', async () => {
const device = zigbeeHerdsman.devices.WXKG02LM;
const data = {'65281': {'1': 2650}}
const payload = {data, cluster: 'genBasic', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(1);
expect(MQTT.publish.mock.calls[0][0]).toStrictEqual('zigbee2mqtt/button_double_key');
expect(JSON.parse(MQTT.publish.mock.calls[0][1])).toStrictEqual({battery: 14, voltage: 2650, linkquality: 10});
expect(MQTT.publish.mock.calls[0][2]).toStrictEqual({"qos": 0, "retain": false});
});
it('Should handle a zigbee message with voltage 2000', async () => {
const device = zigbeeHerdsman.devices.WXKG02LM;
const data = {'65281': {'1': 2000}}
const payload = {data, cluster: 'genBasic', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(1);
expect(MQTT.publish.mock.calls[0][0]).toStrictEqual('zigbee2mqtt/button_double_key');
expect(JSON.parse(MQTT.publish.mock.calls[0][1])).toStrictEqual({battery: 0, voltage: 2000, linkquality: 10});
expect(MQTT.publish.mock.calls[0][2]).toStrictEqual({"qos": 0, "retain": false});
});
it('Should publish 1 message when converted twice', async () => {
const device = zigbeeHerdsman.devices.RTCGQ11LM;
const data = {'65281': {'1': 3045, '3': 19, '4': 17320, '5': 35, '6': [0, 3], '10': 51107, '11': 381, '100': 0}}
const payload = {data, cluster: 'genBasic', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(1);
expect(MQTT.publish.mock.calls[0][0]).toStrictEqual('zigbee2mqtt/occupancy_sensor');
expect(JSON.parse(MQTT.publish.mock.calls[0][1])).toStrictEqual({'battery': 100, 'illuminance': 381, "illuminance_lux": 381, 'voltage': 3045, linkquality: 10});
expect(MQTT.publish.mock.calls[0][2]).toStrictEqual({"qos": 0, "retain": false});
});
it('Should publish 1 message when converted twice', async () => {
const device = zigbeeHerdsman.devices.RTCGQ11LM;
const data = {'9999': {'1': 3045}};
const payload = {data, cluster: 'genBasic', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(0);
});
it('Should publish last_seen epoch', async () => {
const device = zigbeeHerdsman.devices.WXKG02LM;
settings.set(['advanced', 'last_seen'], 'epoch');
const data = {onOff: 1};
const payload = {data, cluster: 'genOnOff', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(1);
expect(MQTT.publish.mock.calls[0][0]).toStrictEqual('zigbee2mqtt/button_double_key');
expect(typeof JSON.parse(MQTT.publish.mock.calls[0][1]).last_seen).toBe('number')
expect(MQTT.publish.mock.calls[0][2]).toStrictEqual({"qos": 0, "retain": false});
});
it('Should publish last_seen ISO_8601', async () => {
const device = zigbeeHerdsman.devices.WXKG02LM;
settings.set(['advanced', 'last_seen'], 'ISO_8601');
const data = {onOff: 1};
const payload = {data, cluster: 'genOnOff', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(1);
expect(MQTT.publish.mock.calls[0][0]).toStrictEqual('zigbee2mqtt/button_double_key');
expect(typeof JSON.parse(MQTT.publish.mock.calls[0][1]).last_seen).toBe('string')
expect(MQTT.publish.mock.calls[0][2]).toStrictEqual({"qos": 0, "retain": false});
});
it('Should publish last_seen ISO_8601_local', async () => {
const device = zigbeeHerdsman.devices.WXKG02LM;
settings.set(['advanced', 'last_seen'], 'ISO_8601_local');
const data = {onOff: 1};
const payload = {data, cluster: 'genOnOff', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(1);
expect(MQTT.publish.mock.calls[0][0]).toStrictEqual('zigbee2mqtt/button_double_key');
expect(typeof JSON.parse(MQTT.publish.mock.calls[0][1]).last_seen).toBe('string')
expect(MQTT.publish.mock.calls[0][2]).toStrictEqual({"qos": 0, "retain": false});
});
it('Should not handle messages forwarded Xiaomi messages', async () => {
const device = zigbeeHerdsman.devices.ZNCZ02LM;
const data = {onOff: 1};
const payload = {data, cluster: 'genOnOff', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10, groupID: 599};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(0);
});
it('Should handle messages from Xiaomi router devices', async () => {
const device = zigbeeHerdsman.devices.ZNCZ02LM;
const data = {onOff: 1};
const payload = {data, cluster: 'genOnOff', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 20};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(1);
expect(MQTT.publish.mock.calls[0][0]).toStrictEqual('zigbee2mqtt/power_plug');
expect(JSON.parse(MQTT.publish.mock.calls[0][1])).toStrictEqual({'state': 'ON', linkquality: 20});
expect(MQTT.publish.mock.calls[0][2]).toStrictEqual({"qos": 0, "retain": false});
});
it('Should not handle messages from coordinator', async () => {
const device = zigbeeHerdsman.devices.coordinator;
const data = {onOff: 1};
const payload = {data, cluster: 'genOnOff', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(0);
});
it('Should not handle messages from unsupported devices and link to docs', async () => {
const device = zigbeeHerdsman.devices.unsupported;
const data = {onOff: 1};
logger.warn.mockClear();
const payload = {data, cluster: 'genOnOff', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(logger.warn).toHaveBeenCalledWith(`Received message from unsupported device with Zigbee model 'notSupportedModelID'`);
expect(logger.warn).toHaveBeenCalledWith(`Please see: https://www.zigbee2mqtt.io/how_tos/how_to_support_new_devices.html.`);
expect(MQTT.publish).toHaveBeenCalledTimes(0);
});
it('Should not handle messages from still interviewing devices with unknown definition', async () => {
const device = zigbeeHerdsman.devices.interviewing;
const data = {onOff: 1};
logger.debug.mockClear();
const payload = {data, cluster: 'genOnOff', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(0);
expect(logger.debug).toHaveBeenCalledWith(`Skipping message, definition is undefined and still interviewing`);
});
it('Should handle a command', async () => {
const device = zigbeeHerdsman.devices.E1743;
const data = {};
const payload = {data, cluster: 'genLevelCtrl', device, endpoint: device.getEndpoint(1), type: 'commandStopWithOnOff', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(1);
expect(MQTT.publish.mock.calls[0][0]).toStrictEqual('zigbee2mqtt/ikea_onoff');
expect(JSON.parse(MQTT.publish.mock.calls[0][1])).toStrictEqual({'click': 'brightness_stop', linkquality: 10});
expect(MQTT.publish.mock.calls[0][2]).toStrictEqual({"qos": 0, "retain": false});
});
it('Should add elapsed', async () => {
settings.set(['advanced', 'elapsed'], true);
const device = zigbeeHerdsman.devices.E1743;
const payload = {data: {}, cluster: 'genLevelCtrl', device, endpoint: device.getEndpoint(1), type: 'commandStopWithOnOff'};
const oldNow = Date.now;
Date.now = jest.fn()
Date.now.mockReturnValue(new Date(150));
await zigbeeHerdsman.events.message(payload);
await flushPromises();
Date.now.mockReturnValue(new Date(200));
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(2);
expect(MQTT.publish.mock.calls[0][0]).toStrictEqual('zigbee2mqtt/ikea_onoff');
expect(JSON.parse(MQTT.publish.mock.calls[0][1])).toStrictEqual({'click': 'brightness_stop'});
expect(MQTT.publish.mock.calls[0][2]).toStrictEqual({"qos": 0, "retain": false});
expect(MQTT.publish.mock.calls[1][0]).toStrictEqual('zigbee2mqtt/ikea_onoff');
expect(JSON.parse(MQTT.publish.mock.calls[1][1])).toMatchObject({'click': 'brightness_stop'});
expect(JSON.parse(MQTT.publish.mock.calls[1][1]).elapsed).toBe(50);
expect(MQTT.publish.mock.calls[1][2]).toStrictEqual({"qos": 0, "retain": false});
Date.now = oldNow;
});
it('Should log when message is from supported device but has no converters', async () => {
const device = zigbeeHerdsman.devices.ZNCZ02LM;
const data = {inactiveText: 'hello'};
const payload = {data, cluster: 'genBinaryOutput', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 20};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(0);
expect(logger.debug).toHaveBeenCalledWith('No converter available for \'ZNCZ02LM\' with cluster \'genBinaryOutput\' and type \'attributeReport\' and data \'{"inactiveText":"hello"}\'');
});
it('Should report correct energy and power values for different versions of SP600', async () => {
// https://github.com/Koenkk/zigbee-herdsman-converters/issues/915, OLD and NEW use different date code
// divisor of OLD is not correct and therefore underreports by factor 10.
const data = {instantaneousDemand:496,currentSummDelivered:[0,6648]}
const SP600_NEW = zigbeeHerdsman.devices.SP600_NEW;
await zigbeeHerdsman.events.message({data, cluster: 'seMetering', device: SP600_NEW, endpoint: SP600_NEW.getEndpoint(1), type: 'attributeReport', linkquality: 10});
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(1);
expect(MQTT.publish.mock.calls[0][0]).toStrictEqual('zigbee2mqtt/SP600_NEW');
expect(JSON.parse(MQTT.publish.mock.calls[0][1])).toStrictEqual({energy: 0.66, power: 49.6, linkquality: 10});
MQTT.publish.mockClear();
const SP600_OLD = zigbeeHerdsman.devices.SP600_OLD;
await zigbeeHerdsman.events.message({data, cluster: 'seMetering', device: SP600_OLD, endpoint: SP600_OLD.getEndpoint(1), type: 'attributeReport', linkquality: 10});
await flushPromises();
expect(MQTT.publish).toHaveBeenCalledTimes(1);
expect(MQTT.publish.mock.calls[0][0]).toStrictEqual('zigbee2mqtt/SP600_OLD');
expect(JSON.parse(MQTT.publish.mock.calls[0][1])).toStrictEqual({energy: 6.648, power: 496, linkquality: 10});
});
});
+259
View File
@@ -0,0 +1,259 @@
const data = require('./stub/data');
const logger = require('./stub/logger');
const zigbeeHerdsman = require('./stub/zigbeeHerdsman');
zigbeeHerdsman.returnDevices.push('0x000b57fffec6a5b3');
zigbeeHerdsman.returnDevices.push('0x00124b00120144ae');
zigbeeHerdsman.returnDevices.push('0x000b57fffec6a5b2');
zigbeeHerdsman.returnDevices.push('0x0017880104e45553');
zigbeeHerdsman.returnDevices.push('0x0017880104e45559');
zigbeeHerdsman.returnDevices.push('0x000b57fffec6a5b4');
zigbeeHerdsman.returnDevices.push('0x000b57fffec6a5b7');
zigbeeHerdsman.returnDevices.push('0x90fd9ffffe4b64ax');
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));
jest.mock('debounce', () => jest.fn(fn => fn));
const debounce = require('debounce');
const mocksClear = [MQTT.publish, logger.warn, logger.debug, debounce];
describe('Report', () => {
let controller;
function expectOnOffBrightnessColorReport(endpoint, colorXY) {
const coordinatorEndpoint = zigbeeHerdsman.devices.coordinator.getEndpoint(1);
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.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}]);
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) => {
for (const endpoint of device.endpoints) {
endpoint.read.mockClear();
endpoint.write.mockClear();
endpoint.configureReporting.mockClear();
endpoint.bind.mockClear();
}
}
beforeEach(async () => {
data.writeDefaultConfiguration();
settings._reRead();
data.writeEmptyState();
settings.set(['advanced', 'report'], true);
controller = new Controller();
await controller.start();
mocksClear.forEach((m) => m.mockClear());
await flushPromises();
});
it('Should configure reporting on startup', async () => {
const device = zigbeeHerdsman.devices.bulb_color;
const endpoint = device.getEndpoint(1);
expectOnOffBrightnessColorReport(endpoint, true);
});
it('Should configure reporting when receicing message from device which has not been setup yet', async () => {
const device = zigbeeHerdsman.devices.bulb;
const endpoint = device.getEndpoint(1);
device.save.mockClear();
mockClear(device);
delete device.meta.reporting;
const data = {onOff: 1}
const payload = {data, cluster: 'genOnOff', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expectOnOffBrightnessColorReport(endpoint, false);
expect(device.save).toHaveBeenCalledTimes(1);
});
it('Should not configure reporting when still configuring', async () => {
jest.useFakeTimers();
const device = zigbeeHerdsman.devices.bulb;
const endpoint = device.getEndpoint(1);
endpoint.bind.mockImplementationOnce(async () => await wait(1000));
delete device.meta.reporting;
mockClear(device);
const payload = {data: {onOff: 1}, cluster: 'genOnOff', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(endpoint.bind).toHaveBeenCalledTimes(1);
jest.runAllTimers();
jest.useRealTimers();
});
it('Should not mark as configured when reporting setup fails', async () => {
const device = zigbeeHerdsman.devices.bulb;
const endpoint = device.getEndpoint(1);
endpoint.bind.mockImplementationOnce(async () => {throw new Error('failed')});
delete device.meta.reporting;
mockClear(device);
const payload = {data: {onOff: 1}, cluster: 'genOnOff', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(endpoint.bind).toHaveBeenCalledTimes(1);
expect(device.meta.reporting).toBeUndefined();
});
it('Should not configure reporting when interviewing', async () => {
const device = zigbeeHerdsman.devices.bulb_2;
const endpoint = device.getEndpoint(1);
device.interviewing = true;
delete device.meta.reporting;
mockClear(device);
const payload = {data: {onOff: 1}, cluster: 'genOnOff', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(endpoint.bind).toHaveBeenCalledTimes(0);
expect(endpoint.configureReporting).toHaveBeenCalledTimes(0);
expect(device.meta.reporting).toBeUndefined();
});
it('Should not configure reporting when receicing message from device which has already been setup yet', async () => {
const device = zigbeeHerdsman.devices.bulb;
const endpoint = device.getEndpoint(1);
mockClear(device);
const data = {onOff: 1}
const payload = {data, cluster: 'genOnOff', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(endpoint.bind).toHaveBeenCalledTimes(0);
expect(endpoint.configureReporting).toHaveBeenCalledTimes(0);
});
it('Should not configure reporting for end devices', async () => {
const device = zigbeeHerdsman.devices.E11_G13;
const endpoint = device.getEndpoint(1);
expect(endpoint.bind).toHaveBeenCalledTimes(0);
expect(endpoint.configureReporting).toHaveBeenCalledTimes(0);
});
it('Should configure reporting when deviceAnnounce message from IKEA device', async () => {
const device = zigbeeHerdsman.devices.bulb;
const endpoint = device.getEndpoint(1);
mockClear(device);
const payload = {device};
await zigbeeHerdsman.events.deviceAnnounce(payload);
await flushPromises();
expectOnOffBrightnessColorReport(endpoint, false);
});
it('Should not configure reporting on device leave', async () => {
const device = zigbeeHerdsman.devices.bulb;
const endpoint = device.getEndpoint(1);
delete device.meta.reporting;
mockClear(device);
await zigbeeHerdsman.events.deviceLeave({ieeeAddr: device.ieeeAddr});
await flushPromises();
expect(endpoint.bind).toHaveBeenCalledTimes(0);
expect(endpoint.configureReporting).toHaveBeenCalledTimes(0);
});
it('Should not configure reporting for the CC2530 router', async () => {
const device = zigbeeHerdsman.devices.CC2530_ROUTER;
const endpoint = device.getEndpoint(1);
delete device.meta.reporting;
mockClear(device);
await zigbeeHerdsman.events.deviceLeave({ieeeAddr: device.ieeeAddr});
await flushPromises();
expect(endpoint.bind).toHaveBeenCalledTimes(0);
expect(endpoint.configureReporting).toHaveBeenCalledTimes(0);
});
it('Should not configure reporting again when it already failed once', async () => {
const device = zigbeeHerdsman.devices.bulb;
const endpoint = device.getEndpoint(1);
endpoint.bind.mockImplementationOnce(async () => {throw new Error('failed')});
delete device.meta.reporting;
mockClear(device);
const payload = {data: {onOff: 1}, cluster: 'genOnOff', device, endpoint: device.getEndpoint(1), type: 'attributeReport', linkquality: 10};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(endpoint.bind).toHaveBeenCalledTimes(1);
});
it('Should poll bounded Hue bulb when receiving message from Hue dimmer', async () => {
const remote = zigbeeHerdsman.devices.remote;
const data = {"button":3,"unknown1":3145728,"type":2,"unknown2":0,"time":1};
const payload = {data, cluster: 'manuSpecificPhilips', device: remote, endpoint: remote.getEndpoint(2), type: 'commandHueNotification', linkquality: 10, groupID: 0};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(debounce).toHaveBeenCalledTimes(1);
expect(zigbeeHerdsman.devices.bulb_color.getEndpoint(1).read).toHaveBeenCalledWith("genLevelCtrl", ["currentLevel"]);
});
it('Should poll grouped Hue bulb when receiving message from TRADFRI remote and should', async () => {
const remote = zigbeeHerdsman.devices.tradfri_remote;
const data = {"stepmode":0,"stepsize":43,"transtime":5};
const payload = {data, cluster: 'genLevelCtrl', device: remote, endpoint: remote.getEndpoint(1), type: 'commandStepWithOnOff', linkquality: 10, groupID: 15071};
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(debounce).toHaveBeenCalledTimes(1);
expect(zigbeeHerdsman.devices.bulb_color_2.getEndpoint(1).read).toHaveBeenCalledTimes(1);
expect(zigbeeHerdsman.devices.bulb_color_2.getEndpoint(1).read).toHaveBeenCalledWith("genLevelCtrl", ["currentLevel"]);
// Should also only debounce once
await zigbeeHerdsman.events.message(payload);
await flushPromises();
expect(debounce).toHaveBeenCalledTimes(1);
expect(zigbeeHerdsman.devices.bulb_color_2.getEndpoint(1).read).toHaveBeenCalledTimes(2);
// Should only call Hue bulb, not e.g. tradfri
expect(zigbeeHerdsman.devices.bulb.getEndpoint(1).read).toHaveBeenCalledTimes(0);
});
it('Should not configure reporting for the ZNLDP12LM closuresWindowCovering as it is ignored', async () => {
const device = zigbeeHerdsman.devices.ZNLDP12LM;
const coordinatorEndpoint = zigbeeHerdsman.devices.coordinator.getEndpoint(1);
const endpoint = device.getEndpoint(1);
delete device.meta.reporting;
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.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);
});
});
+676
View File
@@ -0,0 +1,676 @@
require('./stub/logger');
require('./stub/data');
const data = require('../lib/util/data.js');
const utils = require('../lib/util/utils.js');
const settings = require('../lib/util/settings.js');
const fs = require('fs');
const configurationFile = data.joinPath('configuration.yaml');
const devicesFile = data.joinPath('devices.yaml');
const groupsFile = data.joinPath('groups.yaml');
const secretFile = data.joinPath('secret.yaml');
const yaml = require('js-yaml');
describe('Settings', () => {
const write = (file, json, reread=true) => {
fs.writeFileSync(file, yaml.safeDump(json))
if (reread) {
settings._reRead();
}
};
const read = (file) => yaml.safeLoad(fs.readFileSync(file, 'utf8'));
const remove = (file) => {
if (fs.existsSync(file)) fs.unlinkSync(file);
}
beforeEach(() => {
remove(configurationFile);
remove(devicesFile);
remove(groupsFile);
});
it('Should return default settings', () => {
write(configurationFile, {});
const s = settings.get();
const expected = settings._getDefaults();
expected.devices = {};
expected.groups = {};
expect(s).toStrictEqual(expected);
});
it('Should return settings', () => {
write(configurationFile, {permit_join: true});
const s = settings.get();
const expected = settings._getDefaults();
expected.devices = {};
expected.groups = {};
expected.permit_join = true;
expect(s).toStrictEqual(expected);
});
it('Should add devices', () => {
write(configurationFile, {});
settings.addDevice('0x12345678');
const actual = read(configurationFile);
const expected = {
devices: {
'0x12345678': {
friendly_name: '0x12345678',
},
},
};
expect(actual).toStrictEqual(expected);
});
it('Should read devices', () => {
const content = {
devices: {
'0x12345678': {
friendly_name: '0x12345678',
retain: false,
},
},
};
write(configurationFile, content);
const device = settings.getDevice('0x12345678');
const expected = {
ID: "0x12345678",
friendlyName: "0x12345678",
friendly_name: '0x12345678',
retain: false,
};
expect(device).toStrictEqual(expected);
});
it('Should not throw error when devices is null', () => {
const content = {devices: null};
write(configurationFile, content);
settings.getDevice('0x12345678');
});
it('Should read MQTT username and password form a separate file', () => {
const contentConfiguration = {
mqtt: {
server: 'my.mqtt.server',
user: '!secret username',
password: '!secret password',
},
advanced: {
network_key: '!secret network_key'
}
};
const contentSecret = {
username: 'mysecretusername',
password: 'mysecretpassword',
network_key: [1,2,3],
};
write(secretFile, contentSecret, false);
write(configurationFile, contentConfiguration);
const expected = {
include_device_information: false,
password: "mysecretpassword",
server: "my.mqtt.server",
user: "mysecretusername",
};
expect(settings.get().mqtt).toStrictEqual(expected);
expect(settings.get().advanced.network_key).toStrictEqual([1,2,3]);
settings._write();
expect(read(configurationFile)).toStrictEqual(contentConfiguration);
expect(read(secretFile)).toStrictEqual(contentSecret);
settings.set(['mqtt', 'user'], 'test123');
settings.set(['advanced', 'network_key'], [1,2,3, 4]);
expect(read(configurationFile)).toStrictEqual(contentConfiguration);
expect(read(secretFile)).toStrictEqual({...contentSecret, username: 'test123', network_key: [1,2,3,4]});
});
it('Should read devices form a separate file', () => {
const contentConfiguration = {
devices: 'devices.yaml',
};
const contentDevices = {
'0x12345678': {
friendly_name: '0x12345678',
retain: false,
},
};
write(configurationFile, contentConfiguration);
write(devicesFile, contentDevices);
const device = settings.getDevice('0x12345678');
const expected = {
ID: "0x12345678",
friendlyName: "0x12345678",
friendly_name: '0x12345678',
retain: false,
};
expect(device).toStrictEqual(expected);
});
it('Should add devices to a separate file', () => {
const contentConfiguration = {
devices: 'devices.yaml',
};
const contentDevices = {
'0x12345678': {
friendly_name: '0x12345678',
retain: false,
},
};
write(configurationFile, contentConfiguration);
write(devicesFile, contentDevices);
settings.addDevice('0x1234');
expect(read(configurationFile)).toStrictEqual({devices: 'devices.yaml'});
const expected = {
'0x12345678': {
friendly_name: '0x12345678',
retain: false,
},
'0x1234': {
friendly_name: '0x1234',
},
};
expect(read(devicesFile)).toStrictEqual(expected);
});
it('Should add devices to a separate file if devices.yaml doesnt exist', () => {
const contentConfiguration = {
devices: 'devices.yaml',
};
write(configurationFile, contentConfiguration);
settings.addDevice('0x1234');
expect(read(configurationFile)).toStrictEqual({devices: 'devices.yaml'});
const expected = {
'0x1234': {
friendly_name: '0x1234',
},
};
expect(read(devicesFile)).toStrictEqual(expected);
}
);
it('Should add and remove devices to a separate file if devices.yaml doesnt exist', () => {
const contentConfiguration = {
devices: 'devices.yaml',
};
write(configurationFile, contentConfiguration);
settings.addDevice('0x1234');
expect(read(configurationFile)).toStrictEqual({devices: 'devices.yaml'});
settings.removeDevice('0x1234');
expect(read(configurationFile)).toStrictEqual({devices: 'devices.yaml'});
expect(read(devicesFile)).toStrictEqual({});
}
);
it('Should read groups', () => {
const content = {
groups: {
'1': {
friendly_name: '123',
},
},
};
write(configurationFile, content);
const group = settings.getGroup('1');
const expected = {
ID: 1,
friendlyName: '123',
friendly_name: '123',
devices: [],
optimistic: true,
};
expect(group).toStrictEqual(expected);
});
it('Should read groups from a separate file', () => {
const contentConfiguration = {
groups: 'groups.yaml',
};
const contentGroups = {
'1': {
friendly_name: '123',
},
};
write(configurationFile, contentConfiguration);
write(groupsFile, contentGroups);
const group = settings.getGroup('1');
const expected = {
ID: 1,
friendlyName: '123',
friendly_name: '123',
devices: [],
optimistic: true,
};
expect(group).toStrictEqual(expected);
});
it('Combine everything! groups and devices from separate file :)', () => {
const contentConfiguration = {
devices: 'devices.yaml',
groups: 'groups.yaml',
};
const contentGroups = {
'1': {
friendly_name: '123',
devices: [],
},
};
write(configurationFile, contentConfiguration);
write(groupsFile, contentGroups);
const expectedConfiguration = {
devices: 'devices.yaml',
groups: 'groups.yaml',
};
expect(read(configurationFile)).toStrictEqual(expectedConfiguration);
settings.addDevice('0x1234');
expect(read(configurationFile)).toStrictEqual(expectedConfiguration);
const expectedDevice = {
'0x1234': {
friendly_name: '0x1234',
},
};
expect(read(devicesFile)).toStrictEqual(expectedDevice);
const group = settings.getGroup('1');
const expectedGroup = {
optimistic: true,
ID: 1,
friendlyName: '123',
friendly_name: '123',
devices: [],
};
expect(group).toStrictEqual(expectedGroup);
expect(read(configurationFile)).toStrictEqual(expectedConfiguration);
const expectedDevice2 = {
ID: '0x1234',
friendlyName: '0x1234',
friendly_name: '0x1234',
};
expect(settings.getDevice('0x1234')).toStrictEqual(expectedDevice2);
});
it('Should add groups', () => {
write(configurationFile, {});
const added = settings.addGroup('test123');
const expected = {
'1': {
friendly_name: 'test123',
},
};
expect(settings.get().groups).toStrictEqual(expected);
});
it('Should add groups with specific ID', () => {
write(configurationFile, {});
const added = settings.addGroup('test123', 123);
const expected = {
'123': {
friendly_name: 'test123',
},
};
expect(settings.get().groups).toStrictEqual(expected);
});
it('Should throw error when changing entity options of non-existing device', () => {
write(configurationFile, {});
expect(() => {
settings.changeEntityOptions('not_existing_123', {});
}).toThrow(new Error("Device or group 'not_existing_123' does not exist"));
});
it('Should not add duplicate groups', () => {
write(configurationFile, {});
settings.addGroup('test123');
expect(() => {
settings.addGroup('test123');
}).toThrow(new Error("friendly_name 'test123' is already in use"));
const expected = {
'1': {
friendly_name: 'test123',
},
};
expect(settings.get().groups).toStrictEqual(expected);
});
it('Should not add duplicate groups with specific ID', () => {
write(configurationFile, {});
settings.addGroup('test123', 123);
expect(() => {
settings.addGroup('test_id_123', 123);
}).toThrow(new Error("group id '123' is already in use"));
const expected = {
'123': {
friendly_name: 'test123',
},
};
expect(settings.get().groups).toStrictEqual(expected);
});
it('Should add devices to groups', () => {
write(configurationFile, {
devices: {
'0x123': {
friendly_name: 'bulb',
retain: true,
}
}
});
settings.addGroup('test123');
settings.addDeviceToGroup('test123', ['0x123']);
const expected = {
'1': {
friendly_name: 'test123',
devices: ['0x123'],
},
};
expect(settings.get().groups).toStrictEqual(expected);
});
it('Should remove devices from groups', () => {
write(configurationFile, {
devices: {
'0x123': {
friendly_name: 'bulb',
retain: true,
}
},
groups: {
'1': {
friendly_name: 'test123',
devices: ['0x123'],
}
}
});
settings.removeDeviceFromGroup('test123', ['0x123']);
const expected = {
'1': {
friendly_name: 'test123',
devices: [],
},
};
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: {
'0x123': {
friendly_name: 'bulb',
retain: true,
}
},
});
expect(() => {
settings.removeDeviceFromGroup('test123', 'bulb')
}).toThrow(new Error("Group 'test123' does not exist"));
});
it('Should throw when adding device which already exists', () => {
write(configurationFile, {
devices: {
'0x123': {
friendly_name: 'bulb',
retain: true,
}
},
});
expect(() => {
settings.addDevice('0x123')
}).toThrow(new Error("Device '0x123' already exists"));
});
it('Should not allow any string values for network_key', () => {
write(configurationFile, {
advanced: {network_key: 'NOT_GENERATE'},
});
settings._reRead();
expect(() => {
settings.validate();
}).toThrowError(`advanced.network_key: should be array or 'GENERATE' (is 'NOT_GENERATE')`);
});
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_blocklist', () => {
write(configurationFile, {
devices: {'0x0017880104e45519': {friendly_name: 'tain'}},
advanced: {availability_blocklist: ['0x0017880104e45519', 'non_existing']},
});
settings._reRead();
expect(() => {
settings.validate();
}).toThrowError(`Non-existing entity 'non_existing' specified in 'availability_blocklist'`);
});
it('Should ban devices', () => {
write(configurationFile, {});
settings.banDevice('0x123');
expect(settings.get().ban).toStrictEqual(['0x123']);
settings.banDevice('0x1234');
expect(settings.get().ban).toStrictEqual(['0x123', '0x1234']);
});
it('Should add devices to blocklist', () => {
write(configurationFile, {});
settings.blockDevice('0x123');
expect(settings.get().blocklist).toStrictEqual(['0x123']);
settings.blockDevice('0x1234');
expect(settings.get().blocklist).toStrictEqual(['0x123', '0x1234']);
});
it('Should throw error when yaml file is invalid', () => {
fs.writeFileSync(configurationFile, `
good: 9
\t wrong
`)
let error;
try {
settings._reRead();
} catch (e) {
error = e;
}
expect(error.message).toContain(`Your YAML file '${configurationFile}' is invalid`);
});
it('Should throw error when yaml file does not exist', () => {
let error;
try {
settings._reRead();
} catch (e) {
error = e;
}
expect(error.message).toContain(`no such file or directory, open`);
});
it('Configuration shouldnt be valid when duplicate friendly_name are used', async () => {
write(configurationFile, {
devices: {'0x0017880104e45519': {friendly_name: 'myname', retain: false}},
groups: {'1': {friendly_name: 'myname', retain: false}},
});
settings._reRead();
expect(() => {
settings.validate();
}).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}},
});
settings._reRead();
expect(() => {
settings.validate();
}).toThrowError(`Following friendly_name are not allowed: '${utils.getEndpointNames()}'`);
});
it('Configuration shouldnt be valid when duplicate friendly_name are used', async () => {
write(configurationFile, {
devices: {
'0x0017880104e45519': {friendly_name: 'myname', retain: false},
'0x0017880104e45511': {friendly_name: 'myname1', retain: false}
},
});
settings._reRead();
expect(() => {
settings.changeFriendlyName('myname1', 'myname');
}).toThrowError(`friendly_name 'myname' is already in use`);
});
it('Should throw when removing device which doesnt exist', async () => {
write(configurationFile, {
devices: {
'0x0017880104e45519': {friendly_name: 'myname', retain: false},
'0x0017880104e45511': {friendly_name: 'myname1', retain: false}
},
});
settings._reRead();
expect(() => {
settings.removeDevice('myname33');
}).toThrowError(`Device 'myname33' does not exist`);
});
it('Shouldnt write to configuration.yaml when there are no changes in it', () => {
const contentConfiguration = {devices: 'devices.yaml'};
const contentDevices = {};
write(configurationFile, contentConfiguration);
const before = fs.statSync(configurationFile).mtimeMs;
write(devicesFile, contentDevices);
settings.addDevice('0x1234');
const after = fs.statSync(configurationFile).mtimeMs;
expect(before).toBe(after);
});
});
+231
View File
@@ -0,0 +1,231 @@
const tmp = require('tmp');
const yaml = require('../../lib/util/yaml');
const path = require('path');
const fs = require('fs');
const mockDir = tmp.dirSync().name;
const mockDirStorage = tmp.dirSync().name;
const stateFile = path.join(mockDir, 'state.json');
function writeDefaultConfiguration() {
const config = {
homeassistant: false,
permit_join: true,
mqtt: {
base_topic: "zigbee2mqtt",
server: "mqtt://localhost",
},
serial: {
"port": "/dev/dummy",
},
devices: {
"0x000b57fffec6a5b2": {
retain: true,
friendly_name: "bulb"
},
"0x0017880104e45517": {
retain: true,
friendly_name: "remote"
},
"0x0017880104e45520": {
retain: false,
friendly_name: "button"
},
"0x0017880104e45521": {
retain: false,
friendly_name: "button_double_key"
},
"0x0017880104e45522": {
qos: 1,
retain: false,
friendly_name: "weather_sensor"
},
"0x0017880104e45523": {
retain: false,
friendly_name: "occupancy_sensor"
},
"0x0017880104e45524": {
retain: false,
friendly_name: "power_plug"
},
"0x0017880104e45530": {
retain: false,
friendly_name: "button_double_key_interviewing"
},
"0x0017880104e45540": {
friendly_name: "ikea_onoff"
},
'0x000b57fffec6a5b7': {
retain: false,
friendly_name: "bulb_2"
},
"0x000b57fffec6a5b3": {
retain: false,
friendly_name: "bulb_color"
},
'0x000b57fffec6a5b4': {
retain: false,
friendly_name: "bulb_color_2"
},
"0x0017880104e45541": {
retain: false,
friendly_name: "wall_switch"
},
"0x0017880104e45542": {
retain: false,
friendly_name: "wall_switch_double"
},
"0x0017880104e45543": {
retain: false,
friendly_name: "led_controller_1"
},
"0x0017880104e45544": {
retain: false,
friendly_name: "led_controller_2"
},
'0x0017880104e45545': {
retain: false,
friendly_name: "dimmer_wall_switch"
},
'0x0017880104e45547': {
retain: false,
friendly_name: "curtain"
},
'0x0017880104e45548': {
retain: false,
friendly_name: 'fan'
},
'0x0017880104e45549': {
retain: false,
friendly_name: 'siren'
},
'0x0017880104e45529': {
retain: false,
friendly_name: 'unsupported2'
},
'0x0017880104e45550': {
retain: false,
friendly_name: 'thermostat'
},
'0x0017880104e45551': {
retain: false,
friendly_name: 'smart_vent'
},
'0x0017880104e45552': {
retain: false,
friendly_name: 'j1'
},
'0x0017880104e45553': {
retain: false,
friendly_name: 'bulb_enddevice'
},
'0x0017880104e45559': {
retain: false,
friendly_name: 'cc2530_router'
},
'0x0017880104e45560': {
retain: false,
friendly_name: 'livolo'
},
'0x90fd9ffffe4b64ae': {
retain: false,
friendly_name: 'tradfri_remote',
},
'0x90fd9ffffe4b64af': {
friendly_name: 'roller_shutter',
},
'0x90fd9ffffe4b64ax': {
friendly_name: 'ZNLDP12LM',
},
'0x90fd9ffffe4b64aa': {
friendly_name: 'SP600_OLD',
},
'0x90fd9ffffe4b64ab': {
friendly_name: 'SP600_NEW',
},
'0x90fd9ffffe4b64ac': {
friendly_name: 'MKS-CM-W5',
},
'0x0017880104e45526': {
friendly_name: 'GL-S-007ZS',
},
'0x0017880104e43559': {
friendly_name: 'U202DST600ZB'
},
'0x0017880104e44559': {
friendly_name: '3157100_thermostat',
}
},
groups: {
'1': {
friendly_name: 'group_1',
retain: false,
},
'2': {
friendly_name: 'group_2',
retain: false,
},
'15071': {
friendly_name: 'group_tradfri_remote',
retain: false,
devices: ['bulb_color_2', 'bulb_2']
},
'11': {
friendly_name: 'group_with_tradfri',
retain: false,
devices: ['bulb_2']
},
},
external_converters: [],
};
yaml.writeIfChanged(path.join(mockDir, 'configuration.yaml'), config);
}
function writeEmptyState() {
fs.writeFileSync(stateFile, JSON.stringify({}));
}
function removeState() {
if (stateExists()) {
fs.unlinkSync(stateFile);
}
}
function stateExists() {
return fs.existsSync(stateFile);
}
function writeDefaultState() {
const state = {
"0x000b57fffec6a5b2": {
"state": "ON",
"brightness": 50,
"color_temp": 370,
"linkquality": 99,
},
"0x0017880104e45517": {
"brightness": 255
},
}
fs.writeFileSync(path.join(mockDir, 'state.json'), JSON.stringify(state));
}
jest.mock('../../lib/util/data', () => ({
joinPath: (file) => require('path').join(mockDir, file),
getPath: () => mockDir,
}));
writeDefaultConfiguration();
writeDefaultState();
module.exports = {
mockDir,
read: () => yaml.read(path.join(mockDir, 'configuration.yaml')),
writeDefaultConfiguration,
writeDefaultState,
removeState,
writeEmptyState,
stateExists,
};
+16
View File
@@ -0,0 +1,16 @@
let level = 'info';
const mock = {
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
debug: jest.fn(),
trace: jest.fn(),
cleanup: jest.fn(),
setLevel: (newLevel) => {level = newLevel},
getLevel: () => level,
};
jest.mock('../../lib/util/logger', () => (mock));
module.exports = {...mock};
+24
View File
@@ -0,0 +1,24 @@
const events = {};
const mock = {
publish: jest.fn().mockImplementation((topic, payload, options, cb) => cb()),
end: jest.fn(),
subscribe: jest.fn(),
on: (type, handler) => {
if (type === 'connect') {
handler();
}
events[type] = handler
},
};
const mockConnect = jest.fn().mockReturnValue(mock);
jest.mock('mqtt', () => {
return {connect: mockConnect};
});
module.exports = {
events, ...mock, connect: mockConnect,
};
+205
View File
@@ -0,0 +1,205 @@
const events = {};
const assert = require('assert');
class Group {
constructor(groupID, members) {
this.groupID = groupID;
this.command = jest.fn();
this.meta = {};
this.members = members;
this.removeFromDatabase = jest.fn();
this.removeFromNetwork = jest.fn();
this.hasMember = (endpoint) => this.members.includes(endpoint);
}
}
const clusters = {
'genBasic': 0,
'genOta': 25,
'genScenes': 5,
'genOnOff': 6,
'genLevelCtrl': 8,
'lightingColorCtrl': 768,
'closuresWindowCovering': 258,
}
class Endpoint {
constructor(ID, inputClusters, outputClusters, deviceIeeeAddress, binds=[], clusterValues={}) {
this.deviceIeeeAddress = deviceIeeeAddress;
this.clusterValues = clusterValues;
this.ID = ID;
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();
this.unbind = jest.fn();
this.configureReporting = jest.fn();
this.binds = binds;
this.supportsInputCluster = (cluster) => {
assert(clusters[cluster] !== undefined, `Undefined '${cluster}'`);
return this.inputClusters.includes(clusters[cluster]);
}
this.supportsOutputCluster = (cluster) => {
assert(clusters[cluster], `Undefined '${cluster}'`);
return this.outputClusters.includes(clusters[cluster]);
}
this.addToGroup = jest.fn();
this.addToGroup.mockImplementation((group) => {
if (!group.members.includes(this)) group.members.push(this);
})
this.getDevice = () => {
return Object.values(devices).find(d => d.ieeeAddr === deviceIeeeAddress);
}
this.removeFromGroup = (group) => {
const index = group.members.indexOf(this);
if (index != -1) {
group.members.splice(index, 1);
}
}
this.removeFromAllGroups = () => {
Object.values(groups).forEach((g) => this.removeFromGroup(g))
}
this.getClusterAttributeValue = (cluster, value) => {
return this.clusterValues[cluster][value];
}
}
}
class Device {
constructor(type, ieeeAddr, networkAddress, manufacturerID, endpoints, interviewCompleted, powerSource = null, modelID = null, interviewing=false, manufacturerName, dateCode= null) {
this.type = type;
this.ieeeAddr = ieeeAddr;
this.dateCode = dateCode;
this.networkAddress = networkAddress;
this.manufacturerID = manufacturerID;
this.endpoints = endpoints;
this.powerSource = powerSource;
this.interviewCompleted = interviewCompleted;
this.modelID = modelID;
this.interviewing = interviewing;
this.meta = {};
this.ping = jest.fn();
this.removeFromNetwork = jest.fn();
this.removeFromDatabase = jest.fn();
this.save = jest.fn();
this.manufacturerName = manufacturerName;
this.lastSeen = 1000;
}
getEndpoint(ID) {
return this.endpoints.find((e) => e.ID === ID);
}
}
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', [], {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', [], {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,
'remote': new Device('EndDevice', '0x0017880104e45517', 6535, 4107, [new Endpoint(1, [0], [0,3,4,6,8,5], '0x0017880104e45517', [{target: bulb_color.endpoints[0]}]), new Endpoint(2, [0,1,3,15,64512], [25, 6])], true, "Battery", "RWL021"),
'unsupported': new Device('EndDevice', '0x0017880104e45518', 6536, 0, [new Endpoint(1, [0], [0,3,4,6,8,5])], true, "Battery", "notSupportedModelID"),
'unsupported2': new Device('EndDevice', '0x0017880104e45529', 6536, 0, [new Endpoint(1, [0], [0,3,4,6,8,5])], true, "Battery", "notSupportedModelID"),
'interviewing': new Device('EndDevice', '0x0017880104e45530', 6536, 0, [new Endpoint(1, [0], [0,3,4,6,8,5])], true, "Battery", undefined, true),
'notInSettings': new Device('EndDevice', '0x0017880104e45519', 6537, 0, [new Endpoint(1, [0], [0,3,4,6,8,5])], true, "Battery", "lumi.sensor_switch.aq2"),
'WXKG11LM': new Device('EndDevice', '0x0017880104e45520', 6537,4151, [new Endpoint(1, [0], [0,3,4,6,8,5])], true, "Battery", "lumi.sensor_switch.aq2"),
'WXKG02LM': new Device('EndDevice', '0x0017880104e45521', 6538,4151, [new Endpoint(1, [0], []), new Endpoint(2, [0], [])], true, "Battery", "lumi.sensor_86sw2.es1"),
'WSDCGQ11LM': new Device('EndDevice', '0x0017880104e45522', 6539,4151, [new Endpoint(1, [0], [])], true, "Battery", "lumi.weather"),
'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], [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'),
'HGZB04D': new Device('Router', '0x0017880104e45545', 6540,4151, [new Endpoint(1, [0], [])], true, "Mains (single phase)", 'FB56+ZSC05HG1.0'),
'ZNCLDJ11LM': new Device('Router', '0x0017880104e45547', 6540,4151, [new Endpoint(1, [0], []), new Endpoint(2, [0], [])], true, "Mains (single phase)", 'lumi.curtain'),
'HAMPTON99432': new Device('Router', '0x0017880104e45548', 6540,4151, [new Endpoint(1, [0], []), new Endpoint(2, [0], [])], true, "Mains (single phase)", 'HDC52EastwindFan'),
'HS2WD': new Device('Router', '0x0017880104e45549', 6540,4151, [new Endpoint(1, [0], [])], true, "Mains (single phase)", 'WarningDevice'),
'1TST_EU': new Device('Router', '0x0017880104e45550', 6540,4151, [new Endpoint(1, [0], [])], true, "Mains (single phase)", 'Thermostat'),
'SV01': new Device('Router', '0x0017880104e45551', 6540,4151, [new Endpoint(1, [0], [])], true, "Mains (single phase)", 'SV01-410-MP-1.0'),
'J1': new Device('Router', '0x0017880104e45552', 6540,4151, [new Endpoint(1, [0], [])], true, "Mains (single phase)", 'J1 (5502)'),
'E11_G13': new Device('EndDevice', '0x0017880104e45553', 6540,4151, [new Endpoint(1, [0, 6], [])], true, "Mains (single phase)", 'E11-G13'),
'nomodel': new Device('Router', '0x0017880104e45535', 6536, 0, [new Endpoint(1, [0], [0,3,4,6,8,5])], true, "Mains (single phase)", undefined, true),
'unsupported_router': new Device('Router', '0x0017880104e45525', 6536, 0, [new Endpoint(1, [0], [0,3,4,6,8,5])], true, "Mains (single phase)", "notSupportedModelID", false, "Boef"),
'CC2530_ROUTER': new Device('Router', '0x0017880104e45559', 6540,4151, [new Endpoint(1, [0, 6], [])], true, "Mains (single phase)", 'lumi.router'),
'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', [], {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 = {
'group_1': new Group(1, []),
'group_tradfri_remote': new Group(15071, [bulb_color_2.endpoints[0], bulb_2.endpoints[0]]),
'group/with/slashes': new Group(99, []),
'group_with_tradfri': new Group(11, [bulb_2.endpoints[0]])
}
const mock = {
setTransmitPower: jest.fn(),
touchlinkFactoryReset: jest.fn(),
start: jest.fn(),
permitJoin: jest.fn(),
getCoordinatorVersion: jest.fn().mockReturnValue({type: 'z-Stack', meta: {version: 1, revision: 20190425}}),
getNetworkParameters: jest.fn().mockReturnValue({panID: 0x162a, extendedPanID: [0, 11, 22], channel: 15}),
on: (type, handler) => {
events[type] = handler;
},
stop: jest.fn(),
setLED: jest.fn(),
getDevices: jest.fn().mockImplementation(() => {
return Object.values(devices).filter((d) => returnDevices.length === 0 || returnDevices.includes(d.ieeeAddr));
}),
getDevicesByType: jest.fn().mockImplementation((type) => {
return Object.values(devices).filter((d) => returnDevices.length === 0 || returnDevices.includes(d.ieeeAddr)).filter((d) => d.type === type);
}),
getDeviceByIeeeAddr: jest.fn().mockImplementation((ieeeAddr) => {
return Object.values(devices).filter((d) => returnDevices.length === 0 || returnDevices.includes(d.ieeeAddr)).find((d) => d.ieeeAddr === ieeeAddr);
}),
getGroups: jest.fn().mockImplementation((query) => {
return Object.values(groups);
}),
getGroupByID: jest.fn().mockImplementation((groupID) => {
return Object.values(groups).find((d) => d.groupID === groupID);
}),
getPermitJoin: jest.fn().mockReturnValue(false),
reset: jest.fn(),
createGroup: jest.fn().mockImplementation((groupID) => {
const group = new Group(groupID, []);
groups[`group_${groupID}`] = group
return group;
})
};
const mockConstructor = jest.fn().mockImplementation(() => mock);
jest.mock('zigbee-herdsman', () => ({
Controller: mockConstructor,
Zcl: {ManufacturerCode: {Philips: 4107}},
}));
module.exports = {
events, ...mock, constructor: mockConstructor, devices, groups, returnDevices
};
+58
View File
@@ -0,0 +1,58 @@
const utils = require('../lib/util/utils.js');
const version = require('../package.json').version;
describe('Utils', () => {
describe('Is xiaomi device', () => {
it('Identify xiaomi device', () => {
const device = {type: 'Router', manufacturerID: 4151, manufacturerName: 'Xiaomi'};
expect(true).toBe(utils.isXiaomiDevice(device));
});
it('Identify xiaomi device without manufacturerName', () => {
const device = {type: 'Router', manufacturerID: 4447};
expect(true).toBe(utils.isXiaomiDevice(device));
});
it('Identify xiaomi device with different manufacturerName', () => {
const device = {type: 'Router', manufacturerID: 4151, manufacturerName: 'Trust International B.V.\u0000'};
expect(false).toBe(utils.isXiaomiDevice(device));
});
});
it('Convert milliseconds to seconds', () => {
expect(utils.millisecondsToSeconds(2000)).toBe(2);
})
it('Object has properties', () => {
expect(utils.objectHasProperties({a: 1, b: 2, c: 3}, ['a', 'b'])).toBeTruthy();
expect(utils.objectHasProperties({a: 1, b: 2, c: 3}, ['a', 'b', 'd'])).toBeFalsy();
})
it('git last commit', async () => {
let mockReturnValue = [];
jest.mock('git-last-commit', () => ({
getLastCommit: (cb) => cb(mockReturnValue[0], mockReturnValue[1])
}));
mockReturnValue = [false, {shortHash: '123'}]
expect(await utils.getZigbee2mqttVersion()).toStrictEqual({"commitHash": "123", "version": version});
mockReturnValue = [true, null]
expect(await utils.getZigbee2mqttVersion()).toStrictEqual({"commitHash": "unknown", "version": version});
})
it('To local iso string', async () => {
var date = new Date('August 19, 1975 23:15:30 UTC+00:00');
var getTimezoneOffset = Date.prototype.getTimezoneOffset;
Date.prototype.getTimezoneOffset = () => 60;
expect(utils.formatDate(date, 'ISO_8601_local').endsWith('-01:00')).toBeTruthy();
Date.prototype.getTimezoneOffset = () => -60;
expect(utils.formatDate(date, 'ISO_8601_local').endsWith('+01:00')).toBeTruthy();
Date.prototype.getTimezoneOffset = getTimezoneOffset;
})
it('Throw exception when formating with invalid date', async () => {
var date = new Date('August 19, 1975 23:15:30 UTC+00:00');
expect(() => utils.formatDate(date, 'invalid', 1)).toThrowError("Unsupported type 'invalid'")
})
});
Executable
+23
View File
@@ -0,0 +1,23 @@
#!/bin/bash -e
echo "Stopping zigbee2mqtt..."
sudo systemctl stop zigbee2mqtt
echo "Creating backup of configuration..."
cp -R data data-backup
echo "Updating..."
git checkout HEAD -- npm-shrinkwrap.json
git pull
echo "Installing dependencies..."
npm ci
echo "Restore configuration..."
cp -R data-backup/* data
rm -rf data-backup
echo "Starting zigbee2mqtt..."
sudo systemctl start zigbee2mqtt
echo "Done!"