mirror of
https://github.com/Koenkk/zigbee2mqtt.git
synced 2026-08-29 15:18:41 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6d30fa156c | ||
|
|
9b6035387b | ||
|
|
9ca85dfac8 | ||
|
|
334fa2a60d | ||
|
|
a7f1345a91 | ||
|
|
bae9bb8812 | ||
|
|
740edd8b58 | ||
|
|
267fee3414 | ||
|
|
fa99c6dcca | ||
|
|
91f4b76970 | ||
|
|
fd4282b98d | ||
|
|
403bd4a725 | ||
|
|
ce27ff3cbf | ||
|
|
5f474e03b8 | ||
|
|
110149fa20 | ||
|
|
445890a071 | ||
|
|
3dce8548ce | ||
|
|
4a020fd8de | ||
|
|
d411fc5c69 | ||
|
|
631c4f6a57 | ||
|
|
c02ed09211 | ||
|
|
49b4876768 | ||
|
|
802271ed37 | ||
|
|
42fc6e03a7 | ||
|
|
35d8a5da7f | ||
|
|
72d862f4a0 | ||
|
|
ad0696856a | ||
|
|
a61646d584 | ||
|
|
854df498bd | ||
|
|
e2232e9e91 | ||
|
|
6775c4f17b | ||
|
|
17520f7cfb | ||
|
|
1707bcab88 | ||
|
|
c577c8e5f0 | ||
|
|
7b8efbe2c4 | ||
|
|
459b695f60 | ||
|
|
f26ade4f93 | ||
|
|
3e2aefbcf8 | ||
|
|
ba77ce7c8d | ||
|
|
4c21b66079 | ||
|
|
be774a4d0d | ||
|
|
7b7b988960 | ||
|
|
d6bf5174be | ||
|
|
73225e2436 | ||
|
|
afedab9680 | ||
|
|
53b7eaabf0 | ||
|
|
16d0e56968 | ||
|
|
aea41b5c82 | ||
|
|
564e9ab9eb | ||
|
|
61c6ec6111 | ||
|
|
4794b3c81f | ||
|
|
517b286583 | ||
|
|
aee173d10a | ||
|
|
940fff244c | ||
|
|
8822aedb5e | ||
|
|
e788c520a9 | ||
|
|
39c5bc8c04 | ||
|
|
5c4e43fd10 | ||
|
|
5a6a9cf4d2 | ||
|
|
ad0e91e61e | ||
|
|
5797b56871 | ||
|
|
ea1c5a8f4e | ||
|
|
8099322cc2 | ||
|
|
619b939b14 | ||
|
|
eeed56ef2c | ||
|
|
e9b4a6221b | ||
|
|
6e001b48ec | ||
|
|
dc7749b57e | ||
|
|
40bf14b93c | ||
|
|
b2c31f89c6 | ||
|
|
faa65f78a2 | ||
|
|
c30630091d | ||
|
|
61d99b7ece | ||
|
|
e037a2c21c | ||
|
|
592c256f96 | ||
|
|
82f1092302 | ||
|
|
39e43d8f40 | ||
|
|
1ea7f650a2 | ||
|
|
003c81b745 | ||
|
|
6c48498e0d | ||
|
|
e96630669a | ||
|
|
961265ad5e | ||
|
|
8ac2f55d87 | ||
|
|
469d40c4aa | ||
|
|
5b844ea64e | ||
|
|
d719c1f368 | ||
|
|
0993652420 | ||
|
|
846b06ccab | ||
|
|
3330d2aaed | ||
|
|
bc650ccf82 | ||
|
|
968df11b16 | ||
|
|
c4c129987d | ||
|
|
05382a9692 | ||
|
|
ef15924260 | ||
|
|
c0190c18ed | ||
|
|
238ea7c4c8 | ||
|
|
174ba64449 | ||
|
|
408052282d | ||
|
|
d8fc69dac3 | ||
|
|
0da5fe6837 | ||
|
|
df70f11a15 | ||
|
|
3ecb0c5e41 | ||
|
|
52d250b72f | ||
|
|
feac6aa677 | ||
|
|
1d69715a5a | ||
|
|
eaaed1fec7 | ||
|
|
b81dcdbf40 | ||
|
|
129a80d1bb | ||
|
|
03a81c6ab1 | ||
|
|
799f71b9b4 | ||
|
|
38d305eee6 | ||
|
|
354d06aebc | ||
|
|
ad9b114b1a | ||
|
|
aa916ad604 | ||
|
|
bafc8e4284 | ||
|
|
9c19aa9494 | ||
|
|
85c894dc4f | ||
|
|
5f893c5657 | ||
|
|
8865429d79 | ||
|
|
1a77675043 | ||
|
|
8018422823 | ||
|
|
8b1f5a555c | ||
|
|
79a27e3b06 | ||
|
|
5f08c3e83b | ||
|
|
e24ec79980 | ||
|
|
d18dbb360d | ||
|
|
74335fbb68 | ||
|
|
8b4a4be2a4 | ||
|
|
548f646f2f | ||
|
|
a75a40b042 | ||
|
|
09fd675d0f | ||
|
|
1d38da6ac5 | ||
|
|
c66008b36b | ||
|
|
ab82f0e9a8 | ||
|
|
d1ce146542 | ||
|
|
cf93c649aa | ||
|
|
ca489daad8 | ||
|
|
16f3f4d649 | ||
|
|
4d247f3ae1 | ||
|
|
c9d01f4118 | ||
|
|
1283859a12 | ||
|
|
a0d91cc063 | ||
|
|
116634193a | ||
|
|
f6c0ce735f | ||
|
|
508318de57 | ||
|
|
26c74b5778 | ||
|
|
87c474d2f5 | ||
|
|
2c70deb411 | ||
|
|
a310627e19 | ||
|
|
77926bc1c3 | ||
|
|
892f92448e | ||
|
|
e8847d1a34 | ||
|
|
79c0c0933a | ||
|
|
a5e1e8c0c3 | ||
|
|
382d37e839 | ||
|
|
c3e1525f60 | ||
|
|
2cb7dcc12a | ||
|
|
b2f74607cc | ||
|
|
2edf85f6e1 | ||
|
|
09f33b31a9 | ||
|
|
3f258342d8 | ||
|
|
c28ca79d8a | ||
|
|
5f6fae0df7 | ||
|
|
15e00ea8a4 | ||
|
|
01d5863487 | ||
|
|
fefae9957c | ||
|
|
a297b9255b | ||
|
|
86b458111b | ||
|
|
f022f55be6 | ||
|
|
dc991be28f | ||
|
|
62b62d224f | ||
|
|
5f2630c93b | ||
|
|
e8e4977327 | ||
|
|
54d729e37a | ||
|
|
3018e40dae | ||
|
|
1df1f5d388 | ||
|
|
d44463a330 | ||
|
|
e52203a1b8 | ||
|
|
073a261738 | ||
|
|
64ebb98ad1 | ||
|
|
3f27f79d7d | ||
|
|
06862c7259 | ||
|
|
0482d8b4e9 | ||
|
|
e9889e5d20 | ||
|
|
77886530fe | ||
|
|
bf22ddac46 | ||
|
|
203019aa26 | ||
|
|
08903f68d9 | ||
|
|
bdeab61001 | ||
|
|
c07fce936f | ||
|
|
264440ebcc | ||
|
|
32d82651e2 | ||
|
|
9079c16d16 | ||
|
|
a8fd23b6cc | ||
|
|
2df363f3af | ||
|
|
0147441c93 | ||
|
|
4d52fdd290 | ||
|
|
8e6ba7975b | ||
|
|
7bd7bce69c | ||
|
|
4bd0c04bdc | ||
|
|
ccfab84e7f | ||
|
|
23f831a1fe | ||
|
|
384bd309a6 | ||
|
|
5f7c00515a | ||
|
|
bed8beccbc | ||
|
|
b21f926b3e | ||
|
|
6e7cc30da7 | ||
|
|
4c9784255b | ||
|
|
1dd6cc3da5 | ||
|
|
d04ab53f1d | ||
|
|
f4cfcbacde | ||
|
|
2b1780879a | ||
|
|
800b85c812 | ||
|
|
c5fa13215c | ||
|
|
6414ade05d | ||
|
|
5286570bd6 | ||
|
|
3160219824 | ||
|
|
bd1be88602 | ||
|
|
a102fac2c8 | ||
|
|
63a4207061 | ||
|
|
092c95b716 | ||
|
|
09f046c72d | ||
|
|
b7cbd9b5d8 | ||
|
|
e12add17be | ||
|
|
bda5bf9e96 | ||
|
|
2056b89bac | ||
|
|
d698770169 | ||
|
|
b41e3e781e | ||
|
|
b72abd675f | ||
|
|
9836f0e27a | ||
|
|
e8cec3542f | ||
|
|
050ebfc9f5 | ||
|
|
449b99b0c0 | ||
|
|
0bdc3fd1f7 | ||
|
|
376554943d | ||
|
|
9fcc41b199 | ||
|
|
fe5639ce40 | ||
|
|
0182c4b32e | ||
|
|
c12f07c5a0 | ||
|
|
31d3e19f38 | ||
|
|
ee1c884031 | ||
|
|
e5f677bdd1 | ||
|
|
6dd812f71c | ||
|
|
71cf2b4160 | ||
|
|
e9f2a3f532 | ||
|
|
0725374db7 | ||
|
|
6f7c6eec04 | ||
|
|
29e56adc15 | ||
|
|
caf91cd7ff | ||
|
|
6432571c61 | ||
|
|
713551b525 | ||
|
|
9a215efe26 | ||
|
|
65eef1b690 | ||
|
|
81bafa5520 | ||
|
|
d322dc2047 | ||
|
|
5f9019a95f | ||
|
|
4bc6a59ff3 | ||
|
|
e505a93a40 | ||
|
|
bc74d0b11b | ||
|
|
cc6f7b02bc | ||
|
|
74e9357a59 | ||
|
|
8b876823da | ||
|
|
db20369447 | ||
|
|
0e0a5618af | ||
|
|
21fa5cbded | ||
|
|
e2b7df9f84 | ||
|
|
ef07505b31 | ||
|
|
435a6cceb9 | ||
|
|
a51216e3c7 | ||
|
|
6ede403688 | ||
|
|
ecadda45e7 | ||
|
|
a837702b2c | ||
|
|
57e04bb547 | ||
|
|
ffdd353e16 | ||
|
|
0215e76118 | ||
|
|
833605b71f | ||
|
|
f4d821deca | ||
|
|
c465ef8352 | ||
|
|
0dd4b6a991 | ||
|
|
1b37baefd3 | ||
|
|
b4a9424d60 | ||
|
|
93c1824b1d | ||
|
|
8ceb08704f | ||
|
|
eb82973067 | ||
|
|
a3e7f69b3f | ||
|
|
373fa43136 | ||
|
|
e04732462c | ||
|
|
e663e86e09 | ||
|
|
163a15d664 | ||
|
|
4afdd4e892 | ||
|
|
190cfe99ac | ||
|
|
c9284f6b33 | ||
|
|
5063c7d3ad | ||
|
|
4dd7dabf08 | ||
|
|
917d8527a5 | ||
|
|
f307467e37 | ||
|
|
c0cd2c6b96 | ||
|
|
4a4ee8888d | ||
|
|
5285b7b95e | ||
|
|
c8dc26b241 | ||
|
|
25ea77e038 | ||
|
|
50c7d2d6ad | ||
|
|
3ccbaf21d2 | ||
|
|
6930fa6f3f | ||
|
|
16faef1511 | ||
|
|
c87d4524d5 | ||
|
|
33234d9ce4 | ||
|
|
4190ba43b4 | ||
|
|
b7d9c78309 | ||
|
|
50b0ffd7e7 | ||
|
|
15f3eaf966 | ||
|
|
0d5de750ff | ||
|
|
7109900bcf | ||
|
|
281e10c15f | ||
|
|
cdad6ccd75 | ||
|
|
b537f9a93a | ||
|
|
1b56e63aab | ||
|
|
f33d3606be | ||
|
|
fb60cfde38 | ||
|
|
de800450ad | ||
|
|
977672976f | ||
|
|
cd9b752ede | ||
|
|
242815e139 | ||
|
|
87ff0f3711 | ||
|
|
8ecb9be98e | ||
|
|
0e66b29983 | ||
|
|
6a8d20858e | ||
|
|
e4b253e08b | ||
|
|
56d3a8f9d8 | ||
|
|
f6c3887c81 | ||
|
|
2affe188c5 | ||
|
|
587a02f663 | ||
|
|
0181263d32 | ||
|
|
eaa3e458b5 | ||
|
|
252bfbaa20 | ||
|
|
66e1318a79 | ||
|
|
9a4ce6fcd0 | ||
|
|
4b95b54be7 | ||
|
|
f637e7d59c | ||
|
|
018fad27af | ||
|
|
4594142c09 | ||
|
|
ac80bb6430 | ||
|
|
1765fe8925 | ||
|
|
7e82a3d1e9 | ||
|
|
9df6cccd31 |
@@ -0,0 +1,55 @@
|
||||
name: External converter
|
||||
description: Submit an external converter
|
||||
title: '[External Converter]: '
|
||||
labels: [external converter]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
**IMPORTANT:** In case the external converter fully works, please consider submitting a [pull request](https://www.zigbee2mqtt.io/advanced/support-new-devices/01_support_new_devices.html#_4-create-a-pull-request) instead.
|
||||
- type: input
|
||||
id: link
|
||||
attributes:
|
||||
label: Link
|
||||
description: Link of this device (product page)
|
||||
placeholder: https://www.linktomydevice.org
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: database
|
||||
attributes:
|
||||
label: Database entry
|
||||
description: Entry of this device in `data/database.db` after pairing it
|
||||
placeholder: '{"id":53,"type":"Router","ieeeAddr":"0x10458d00024284f69","nwkAddr":10148,"manufId":4151,"manufName":"LUMI","powerSource":"DC Source","modelId":"lumi.relay.c2acn01","epList":[1,2],"endpoints":{"1":{"profId":260,"epId":1,"devId":257,"inClusterList":[0,3,4,5,1,2,10,6,16,2820,12],"outClusterList":[25,10],"clusters":{"genBasic":{"attributes":{"modelId":"lumi.relay.c2acn01","appVersion":1,"manufacturerName":"LUMI","powerSource":4,"zclVersion":0,"stackVersion":2,"hwVersion":18,"dateCode":"8-6-2020"}},"genAnalogInput":{"attributes":{"presentValue":129.04425048828125}},"genOnOff":{"attributes":{"61440":117440715,"onOff":1}}},"binds":[],"configuredReportings":[],"meta":{}},"2":{"profId":260,"epId":2,"devId":257,"inClusterList":[6,16,4,5],"outClusterList":[],"clusters":{"genOnOff":{"attributes":{"61440":237478966,"onOff":0}}},"binds":[],"configuredReportings":[],"meta":{}}},"appVersion":1,"stackVersion":2,"hwVersion":18,"dateCode":"8-6-2020","zclVersion":0,"interviewCompleted":true,"meta":{},"lastSeen":1640285631405}'
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: z2m_version
|
||||
attributes:
|
||||
label: Zigbee2MQTT version
|
||||
description: Can be found in the frontend -> settings -> about -> Zigbee2MQTT version. Are you running Zigbee2MQTT 1.18.1? Then read [this](https://github.com/Koenkk/zigbee2mqtt/releases/tag/1.19.0).
|
||||
placeholder: '1.22.1'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: external_definition
|
||||
attributes:
|
||||
label: External converter
|
||||
description: Code of the external converter, to retrieve in the Z2M frontend go to Settings -> Dev Console -> External Converters
|
||||
render: JavaScript
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: What does/doesn't work with the external definition?
|
||||
description: Indicate what works and what doesn't work with the external definition.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: notes
|
||||
attributes:
|
||||
label: Notes
|
||||
description: Any additional information or context that might be helpful
|
||||
placeholder: Add any relevant notes or context here
|
||||
validations:
|
||||
required: false
|
||||
@@ -36,17 +36,11 @@ body:
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: notes
|
||||
attributes:
|
||||
label: Comments
|
||||
placeholder: I tried to follow the supporting new device page but got stuck at...
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: external_definition
|
||||
attributes:
|
||||
label: External definition
|
||||
description: See [Creating the external definition](https://www.zigbee2mqtt.io/advanced/support-new-devices/01_support_new_devices.html#_2-creating-the-external-definition)
|
||||
render: shell
|
||||
render: JavaScript
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
@@ -55,3 +49,11 @@ body:
|
||||
description: Indicate what works and what doesn't work with the external definition.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: notes
|
||||
attributes:
|
||||
label: Notes
|
||||
description: Any additional information or context that might be helpful
|
||||
placeholder: Add any relevant notes or context here
|
||||
validations:
|
||||
required: false
|
||||
@@ -6,7 +6,7 @@ body:
|
||||
attributes:
|
||||
value: |
|
||||
**IMPORTANT:** Before submitting:
|
||||
- Zigbee2MQTT fails to start? Read [this](https://www.zigbee2mqtt.io/guide/installation/20_zigbee2mqtt-fails-to-start.html)
|
||||
- Zigbee2MQTT fails to start? Read [this](https://www.zigbee2mqtt.io/guide/installation/20_zigbee2mqtt-fails-to-start_crashes-runtime.html)
|
||||
- Raspberry Pi users? Make sure to check [this](https://www.zigbee2mqtt.io/guide/installation/20_zigbee2mqtt-fails-to-start_crashes-runtime.html#raspberry-pi-users-use-a-good-power-supply)
|
||||
- You read the [FAQ](https://www.zigbee2mqtt.io/guide/faq/)
|
||||
- Are you using an EZSP adapter (e.g. Dongle-E/SkyConnect)? Try the [new driver](https://github.com/Koenkk/zigbee2mqtt/discussions/21462)
|
||||
@@ -69,6 +69,12 @@ body:
|
||||
placeholder: Add-on on Home Assistant OS on Intel NUC, Plain on Docker container, ...
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: device
|
||||
attributes:
|
||||
label: Device `database.db` entry
|
||||
description: If the problem is related to a specific device, paste the `database.db` entry here
|
||||
placeholder: '{"id":117,"type":"EndDevice","ieeeAddr":"0x00158d0001d8e1d2","nwkAddr":25887 ...'
|
||||
- type: textarea
|
||||
id: log
|
||||
attributes:
|
||||
@@ -77,3 +83,11 @@ body:
|
||||
placeholder: Click here and drag the file into it or click on "Attach files by.." below
|
||||
validations:
|
||||
required: false
|
||||
- type: textarea
|
||||
id: notes
|
||||
attributes:
|
||||
label: Notes
|
||||
description: Any additional information or context that might be helpful
|
||||
placeholder: Add any relevant notes or context here
|
||||
validations:
|
||||
required: false
|
||||
|
||||
@@ -6,7 +6,10 @@ body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Only use this if the device is detected as **supported** and is **fully functional** but has a wrong picture, vendor, model or description.
|
||||
Submit this issue only if your device is detected as **supported** and works **fully**, but displays an incorrect picture, vendor, model, or description.
|
||||
|
||||
**IMPORTANT**: Before opening this issue, please review the [guide](https://www.zigbee2mqtt.io/advanced/support-new-devices/02_support_new_tuya_devices.html#fixing-tuya-device-detection) for instructions on fixing the device detection yourself.
|
||||
This usually only takes 5 minutes.
|
||||
- type: input
|
||||
id: link
|
||||
attributes:
|
||||
|
||||
@@ -0,0 +1,459 @@
|
||||
# GitHub Copilot Instructions
|
||||
|
||||
## Priority Guidelines
|
||||
|
||||
When generating code for this repository:
|
||||
|
||||
1. **Version Compatibility**: Always detect and respect the exact versions of languages, frameworks, and libraries used in this project
|
||||
2. **Context Files**: Prioritize patterns and standards defined in the .github/copilot directory
|
||||
3. **Codebase Patterns**: When context files don't provide specific guidance, scan the codebase for established patterns
|
||||
4. **Architectural Consistency**: Maintain our layered architectural style with clear separation between controller, extensions, models, and utilities
|
||||
5. **Code Quality**: Prioritize maintainability, performance, security, and testability in all generated code
|
||||
|
||||
## Technology Stack
|
||||
|
||||
### Core Technologies
|
||||
- **Language**: TypeScript 5.9.3 with target `esnext` and module `NodeNext`
|
||||
- **Runtime**: Node.js ^20 || ^22 || ^24
|
||||
- **Package Manager**: pnpm 10.12.1
|
||||
- **Testing**: Vitest 3.1.1 with @vitest/coverage-v8
|
||||
- **Linting/Formatting**: Biome 2.2.5 (configured with 4-space indents, 150 line width, no bracket spacing)
|
||||
|
||||
### Key Dependencies
|
||||
- **zigbee-herdsman**: 6.2.0 (exact version - critical for Zigbee protocol compatibility)
|
||||
- **zigbee-herdsman-converters**: 25.42.0 (exact version - device definitions)
|
||||
- **MQTT**: mqtt 5.14.1
|
||||
- **Logging**: winston 3.18.3
|
||||
- **YAML**: js-yaml 4.1.0
|
||||
- **Decorators**: bind-decorator 1.0.11
|
||||
- **WebSocket**: ws 8.18.1
|
||||
|
||||
### TypeScript Configuration
|
||||
- **Strict Mode**: Enabled with `noImplicitAny` and `noImplicitThis`
|
||||
- **Module System**: NodeNext with ESM interop
|
||||
- **Decorators**: Experimental decorators enabled
|
||||
- **Composite**: True (for project references)
|
||||
- **Source Maps**: Inline source maps enabled
|
||||
- **Output**: Compiled to `dist/` directory
|
||||
|
||||
## Project Architecture
|
||||
|
||||
### Directory Structure
|
||||
```
|
||||
lib/ # Source TypeScript files
|
||||
├── controller.ts # Main controller orchestrating all components
|
||||
├── mqtt.ts # MQTT client management
|
||||
├── zigbee.ts # Zigbee network management
|
||||
├── state.ts # State management
|
||||
├── eventBus.ts # Event-driven communication
|
||||
├── extension/ # Extension system (plugins)
|
||||
│ ├── extension.ts # Abstract base class
|
||||
│ ├── availability.ts
|
||||
│ ├── bind.ts
|
||||
│ ├── bridge.ts
|
||||
│ ├── configure.ts
|
||||
│ └── ...
|
||||
├── model/ # Domain models
|
||||
│ ├── device.ts
|
||||
│ └── group.ts
|
||||
├── util/ # Utility functions
|
||||
│ ├── logger.ts
|
||||
│ ├── settings.ts
|
||||
│ ├── utils.ts
|
||||
│ └── ...
|
||||
└── types/ # TypeScript type definitions
|
||||
└── api.ts
|
||||
test/ # Vitest test files
|
||||
data/ # Runtime configuration and data
|
||||
```
|
||||
|
||||
### Architectural Patterns
|
||||
|
||||
#### Extension Pattern
|
||||
All extensions inherit from the abstract `Extension` base class:
|
||||
```typescript
|
||||
abstract class Extension {
|
||||
protected zigbee: Zigbee;
|
||||
protected mqtt: Mqtt;
|
||||
protected state: State;
|
||||
protected publishEntityState: PublishEntityState;
|
||||
protected eventBus: EventBus;
|
||||
|
||||
async start(): Promise<void> {}
|
||||
async stop(): Promise<void> {}
|
||||
}
|
||||
```
|
||||
|
||||
#### Event-Driven Architecture
|
||||
Use the `EventBus` for component communication. Events are strongly typed:
|
||||
```typescript
|
||||
interface EventBusMap {
|
||||
deviceMessage: [data: eventdata.DeviceMessage];
|
||||
mqttMessage: [data: eventdata.MQTTMessage];
|
||||
publishEntityState: [data: eventdata.PublishEntityState];
|
||||
// ... other events
|
||||
}
|
||||
```
|
||||
|
||||
#### Dependency Injection
|
||||
The `Controller` class instantiates and injects dependencies into extensions. Follow this pattern when creating new extensions.
|
||||
|
||||
## Code Style and Conventions
|
||||
|
||||
### Naming Conventions
|
||||
- **Classes**: PascalCase (e.g., `Extension`, `Device`, `EventBus`)
|
||||
- **Interfaces/Types**: PascalCase (e.g., `MqttPublishOptions`, `DeviceOptions`)
|
||||
- **Functions/Methods**: camelCase (e.g., `publishEntityState`, `enableDisableExtension`)
|
||||
- **Constants**: SCREAMING_SNAKE_CASE for top-level constants (e.g., `CURRENT_VERSION`, `LOG_LEVELS`)
|
||||
- **Private members**: Prefix with underscore for private class fields only when needed to distinguish from public properties (e.g., `_definitionModelID`)
|
||||
- **Files**: camelCase for TypeScript files (e.g., `eventBus.ts`, `externalJS.ts`)
|
||||
|
||||
### Import Organization
|
||||
Follow this import order (separated by blank lines):
|
||||
1. Node.js built-in modules (use `node:` prefix: `import fs from "node:fs"`)
|
||||
2. Third-party libraries (e.g., `bind-decorator`, `mqtt`)
|
||||
3. Type-only imports from external packages (using `type` keyword)
|
||||
4. Internal absolute imports from project root
|
||||
5. Type-only imports from internal modules
|
||||
|
||||
Example:
|
||||
```typescript
|
||||
import fs from "node:fs";
|
||||
import bind from "bind-decorator";
|
||||
import type {IClientOptions} from "mqtt";
|
||||
import {connectAsync} from "mqtt";
|
||||
import type {Zigbee2MQTTAPI} from "./types/api";
|
||||
import logger from "./util/logger";
|
||||
import * as settings from "./util/settings";
|
||||
```
|
||||
|
||||
### Type Annotations
|
||||
- Use `type` imports for TypeScript types: `import type * as zhc from "zigbee-herdsman-converters"`
|
||||
- Explicitly type function parameters and return types
|
||||
- Use `KeyValue` type for generic object payloads: `type KeyValue = Record<string, any>`
|
||||
- Prefer interfaces for object shapes, type aliases for unions/intersections
|
||||
- Use namespace exports for related types: `export type * as ZSpec from "zigbee-herdsman/dist/zspec"`
|
||||
|
||||
### Async/Await Patterns
|
||||
- Always use `async/await` for asynchronous operations
|
||||
- Return types should be explicitly `Promise<Type>`
|
||||
- Methods that don't return values should be `Promise<void>`
|
||||
- Use `Awaited<ReturnType<typeof fn>>` for inferring async function return types
|
||||
|
||||
### Decorators
|
||||
Use `@bind` decorator from `bind-decorator` for methods that need `this` binding:
|
||||
```typescript
|
||||
@bind async onMQTTMessage(data: eventdata.MQTTMessage): Promise<void> {
|
||||
// Implementation
|
||||
}
|
||||
```
|
||||
|
||||
### Error Handling
|
||||
- Use `throw new Error("message")` for explicit errors
|
||||
- Include descriptive error messages
|
||||
- Log errors using the logger: `logger.error("message")`
|
||||
- For Zigbee-herdsman errors, log the stack trace: `logger.error((error as Error).stack!)`
|
||||
- Catch and handle errors at appropriate boundaries (controller level)
|
||||
|
||||
### Logging
|
||||
Use the centralized logger (winston-based):
|
||||
```typescript
|
||||
import logger from "./util/logger";
|
||||
|
||||
logger.info("message");
|
||||
logger.warning("message");
|
||||
logger.error("message");
|
||||
logger.debug("message");
|
||||
```
|
||||
|
||||
- Use namespaced loggers for specific modules (created internally by logger)
|
||||
- Log levels: `error`, `warning`, `info`, `debug` (from most to least critical)
|
||||
- Include relevant context in log messages (device names, IEEE addresses, etc.)
|
||||
|
||||
## Code Quality Standards
|
||||
|
||||
### Maintainability
|
||||
- Write self-documenting code with clear, descriptive names
|
||||
- Keep methods focused on single responsibilities
|
||||
- Abstract classes should define clear contracts with protected members for subclasses
|
||||
- Use constructor dependency injection for required dependencies
|
||||
- Limit function complexity - methods should be concise and focused
|
||||
- Use TypeScript's strict mode features (`noImplicitAny`, `noImplicitThis`)
|
||||
|
||||
### Performance
|
||||
- Use `rimrafSync` for synchronous file deletion when appropriate
|
||||
- Leverage async/await for I/O operations to avoid blocking
|
||||
- Use JSON stable stringify for consistent object serialization: `json-stable-stringify-without-jsonify`
|
||||
- Cache computed values when appropriate (see device model patterns)
|
||||
- Use getter methods for computed properties that should be cached
|
||||
|
||||
### Security
|
||||
- Validate input using Ajv JSON schema validation (see `settings.ts` pattern)
|
||||
- Sanitize file paths using `path.join` from Node.js
|
||||
- Use YAML safe loading: `yaml.safeLoad()`
|
||||
- Handle sensitive data (credentials, tokens) through settings with proper defaults
|
||||
- Never log sensitive information (passwords, tokens)
|
||||
|
||||
### Testability
|
||||
- Write tests using Vitest with describe/it/expect patterns
|
||||
- Mock external dependencies using Vitest's `vi.mock()`
|
||||
- Use `beforeEach`, `afterEach`, `beforeAll`, `afterAll` for test setup/teardown
|
||||
- Place test files in `test/` directory with `.test.ts` extension
|
||||
- Mock constructors and modules in the pattern shown in `test/controller.test.ts`
|
||||
- Use `flushPromises()` utility for async test synchronization
|
||||
- Target 100% code coverage (configured in vitest.config.mts)
|
||||
|
||||
## Testing Standards
|
||||
|
||||
### Unit Testing Structure
|
||||
```typescript
|
||||
import {afterAll, beforeAll, beforeEach, describe, expect, it, vi} from "vitest";
|
||||
|
||||
describe("ComponentName", () => {
|
||||
beforeEach(() => {
|
||||
// Setup
|
||||
});
|
||||
|
||||
it("Should do something specific", async () => {
|
||||
// Arrange
|
||||
const input = {};
|
||||
|
||||
// Act
|
||||
const result = await someFunction(input);
|
||||
|
||||
// Assert
|
||||
expect(result).toBe(expected);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### Mocking Patterns
|
||||
- Create mock modules in `test/mocks/` directory
|
||||
- Use `vi.fn()` for function mocks
|
||||
- Use `vi.mock()` for module mocks
|
||||
- Clear mocks in `afterEach` or between tests
|
||||
- Mock external libraries like `mqtt`, `zigbee-herdsman` consistently
|
||||
|
||||
### Test Coverage
|
||||
- All code in `lib/**` should be covered
|
||||
- Use coverage reports: `pnpm test:coverage`
|
||||
- Thresholds set to 100% (can be adjusted per project needs)
|
||||
- Tests should cover both success and failure paths
|
||||
|
||||
## Documentation Standards
|
||||
|
||||
### JSDoc Comments
|
||||
Use JSDoc-style comments for classes and public methods:
|
||||
```typescript
|
||||
/**
|
||||
* Besides initializing 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: Zigbee, mqtt: Mqtt, state: State, ...) {
|
||||
```
|
||||
|
||||
### Comment Style
|
||||
- Use single-line comments (`//`) for implementation notes
|
||||
- Use JSDoc (`/** */`) for public APIs and class/method documentation
|
||||
- Include context for non-obvious logic
|
||||
- Document parameters with their types and purposes
|
||||
- Use `@param` tags with TypeScript types in braces
|
||||
- Use biome-ignore comments when necessary: `// biome-ignore lint/rule: reason`
|
||||
|
||||
### Code Documentation
|
||||
- Document complex algorithms or business logic
|
||||
- Explain "why" not just "what" when logic is non-trivial
|
||||
- Include links to relevant issues or documentation when applicable
|
||||
- Document deprecations and breaking changes
|
||||
|
||||
## TypeScript-Specific Guidelines
|
||||
|
||||
### Module System
|
||||
- Use ES modules with `import`/`export` syntax
|
||||
- Default exports for main classes: `export default class Device {}`
|
||||
- Named exports for utilities and types: `export const LOG_LEVELS = ...`
|
||||
- Namespace exports for related types: `export type * as ZSpec from ...`
|
||||
- Use `.js` extension in imports for local modules when using dynamic imports: `await import("./extension/frontend.js")`
|
||||
|
||||
### Type Safety
|
||||
- Enable all strict type checking options
|
||||
- Use type guards and assertions when necessary: `asserts expose is zhc.Numeric`
|
||||
- Prefer `unknown` over `any` when type is truly unknown
|
||||
- Use `// biome-ignore lint/suspicious/noExplicitAny: API` when `any` is necessary
|
||||
- Define proper interfaces for external module types (e.g., `unix-dgram.d.ts`)
|
||||
|
||||
### Generic Types
|
||||
- Use generics for reusable, type-safe abstractions
|
||||
- Example: `abstract class ExternalJSExtension<M> extends Extension`
|
||||
- Constrain generics when appropriate
|
||||
- Document generic type parameters
|
||||
|
||||
### Utility Types
|
||||
- Use built-in utility types: `Partial`, `Required`, `Pick`, `Omit`, `Record`
|
||||
- Use `Awaited<ReturnType<typeof fn>>` for async function return types
|
||||
- Define custom utility types when patterns emerge
|
||||
- Use `type` for aliases, `interface` for object shapes
|
||||
|
||||
## Version Control and Releases
|
||||
|
||||
### Versioning Strategy
|
||||
- Follow Semantic Versioning (MAJOR.MINOR.PATCH)
|
||||
- Current version managed in `package.json`
|
||||
- Use `-dev` suffix for development versions (e.g., `2.6.2-dev`)
|
||||
- Configuration version tracked separately: `CURRENT_VERSION = 4`
|
||||
|
||||
### Changelog
|
||||
- Maintain CHANGELOG.md with all changes
|
||||
- Group changes by type: Bug Fixes, Features, Breaking Changes
|
||||
- Include issue/PR references: `([#28583](url))`
|
||||
- Include commit references: `([09f33b3](url))`
|
||||
- Use conventional commits format
|
||||
|
||||
### Git Workflow
|
||||
- Development on `dev` branch
|
||||
- Production releases from `master` branch
|
||||
- Use meaningful commit messages
|
||||
- Reference issues in commits
|
||||
|
||||
## Project-Specific Patterns
|
||||
|
||||
### Settings Management
|
||||
- All configuration loaded through `util/settings.ts`
|
||||
- Validate settings using Ajv with JSON schema
|
||||
- Schema defined in `settings.schema.json`
|
||||
- Support runtime setting changes with restart detection
|
||||
- Use `settings.get()` to access current configuration
|
||||
- Use `settings.getDevice(ieeeAddr)` for device-specific config
|
||||
|
||||
### Device and Group Models
|
||||
- Devices and groups are domain models wrapping `zigbee-herdsman` entities
|
||||
- Access underlying entity via `.zh` property
|
||||
- Expose computed properties as getters
|
||||
- Include definition from `zigbee-herdsman-converters`
|
||||
- Handle coordinator devices specially (type checking)
|
||||
|
||||
### MQTT Integration
|
||||
- MQTT client wrapped in `Mqtt` class
|
||||
- Publish options: `retain`, `qos` properties
|
||||
- Topics follow pattern: `{base_topic}/{device}/{attribute}`
|
||||
- Event-based message handling via EventBus
|
||||
- Clean disconnect handling with retry logic
|
||||
|
||||
### Extension System
|
||||
- Extensions are loosely coupled plugins
|
||||
- Lifecycle: constructor → start() → stop()
|
||||
- Constructor should only assign properties (no side effects)
|
||||
- Use EventBus for inter-extension communication
|
||||
- Extensions can be enabled/disabled at runtime
|
||||
- External extensions loaded from `data/external_extensions/`
|
||||
|
||||
### State Management
|
||||
- State persisted to `state.json`
|
||||
- Cached in memory for performance
|
||||
- Device states include all exposed attributes
|
||||
- State changes trigger events via EventBus
|
||||
|
||||
## Best Practices Specific to This Project
|
||||
|
||||
1. **Never use language features beyond TypeScript 5.9.3 or ES2024**
|
||||
2. **Always respect exact versions of zigbee-herdsman and zigbee-herdsman-converters** - these are critical for device compatibility
|
||||
3. **Use the EventBus for all component communication** - avoid direct coupling
|
||||
4. **Follow the Extension pattern for new features** - don't add logic directly to Controller
|
||||
5. **Log appropriately** - info for user-relevant events, debug for developer info, error for failures
|
||||
6. **Test with real Zigbee scenarios** - many edge cases exist with different device types
|
||||
7. **Handle coordinator specially** - coordinator is a device but with unique behavior
|
||||
8. **Validate all external input** - MQTT messages, configuration files, device data
|
||||
9. **Use the bind decorator** for event handlers to preserve `this` context
|
||||
10. **Match the exact code formatting** - Biome enforces 4 spaces, 150 line width, no bracket spacing
|
||||
|
||||
## Common Patterns to Follow
|
||||
|
||||
### Creating a New Extension
|
||||
1. Extend `Extension` abstract class
|
||||
2. Accept all dependencies in constructor
|
||||
3. Implement `start()` method for initialization
|
||||
4. Subscribe to EventBus events in `start()`
|
||||
5. Implement `stop()` method for cleanup
|
||||
6. Export as default: `export default class MyExtension extends Extension`
|
||||
|
||||
### Accessing Device Information
|
||||
```typescript
|
||||
const device: Device; // Our wrapper
|
||||
device.ieeeAddr; // IEEE address
|
||||
device.name; // Friendly name
|
||||
device.zh; // Underlying zigbee-herdsman device
|
||||
device.definition; // zigbee-herdsman-converters definition
|
||||
device.options; // User configuration
|
||||
```
|
||||
|
||||
### Publishing MQTT Messages
|
||||
```typescript
|
||||
await this.mqtt.publish(topic, message, {retain: true, qos: 0});
|
||||
```
|
||||
|
||||
### Emitting Events
|
||||
```typescript
|
||||
this.eventBus.emit('deviceMessage', {device, message});
|
||||
```
|
||||
|
||||
### Listening to Events
|
||||
```typescript
|
||||
this.eventBus.on('deviceMessage', this.onDeviceMessage, this);
|
||||
```
|
||||
|
||||
## Integration Points
|
||||
|
||||
### Zigbee-Herdsman Integration
|
||||
- Start controller: `await this.zigbee.start()`
|
||||
- Access coordinator: `this.zigbee.coordinator()`
|
||||
- Device operations through `zigbee-herdsman` API
|
||||
- Event handling through EventBus wrappers
|
||||
|
||||
### MQTT Integration
|
||||
- Connect: `await this.mqtt.connect()`
|
||||
- Subscribe: `await this.mqtt.subscribe(topic)`
|
||||
- Publish: `await this.mqtt.publish(topic, message, options)`
|
||||
- Handle messages via EventBus `mqttMessage` event
|
||||
|
||||
### Frontend Integration
|
||||
- Optional extension loaded dynamically
|
||||
- Serves static files with compression
|
||||
- WebSocket support for real-time updates
|
||||
- Configurable port and base URL
|
||||
|
||||
### Home Assistant Integration
|
||||
- Optional extension for discovery
|
||||
- Publishes discovery messages to MQTT
|
||||
- Supports entities, sensors, and devices
|
||||
- Configurable discovery topic
|
||||
|
||||
## Critical Compatibility Notes
|
||||
|
||||
1. **Node.js**: Only versions 20, 22, and 24 are supported
|
||||
2. **TypeScript**: Features must be compatible with 5.9.3
|
||||
3. **Zigbee Libraries**: Exact versions are critical - do not suggest upgrades without testing
|
||||
4. **MQTT Protocol**: Uses MQTT 3.1.1 and 5.0 features
|
||||
5. **ES Modules**: Project uses ESM with NodeNext resolution
|
||||
6. **Experimental Decorators**: Required for `@bind` decorator support
|
||||
|
||||
## When in Doubt
|
||||
|
||||
1. **Search for similar patterns** in the existing codebase
|
||||
2. **Check existing extensions** for implementation examples
|
||||
3. **Follow the controller and extension architecture** - don't bypass it
|
||||
4. **Consult the test files** for usage examples
|
||||
5. **Match the exact style** - run `pnpm check` to verify
|
||||
6. **Prioritize consistency** over external best practices
|
||||
7. **Test thoroughly** - this project controls real hardware
|
||||
|
||||
## Resources
|
||||
|
||||
- Repository: https://github.com/Koenkk/zigbee2mqtt
|
||||
- Documentation: https://koenkk.github.io/zigbee2mqtt
|
||||
- License: GPL-3.0
|
||||
- Issue Tracker: https://github.com/Koenkk/zigbee2mqtt/issues
|
||||
@@ -1,6 +1,7 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: npm
|
||||
versioning-strategy: increase
|
||||
directory: /
|
||||
schedule:
|
||||
interval: weekly
|
||||
@@ -14,7 +15,7 @@ updates:
|
||||
- minor
|
||||
- patch
|
||||
- package-ecosystem: docker
|
||||
directory: /
|
||||
directory: /docker
|
||||
schedule:
|
||||
interval: weekly
|
||||
target-branch: dev
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
---
|
||||
description: 'Technology-agnostic blueprint generator for creating comprehensive copilot-instructions.md files that guide GitHub Copilot to produce code consistent with project standards, architecture patterns, and exact technology versions by analyzing existing codebase patterns and avoiding assumptions.'
|
||||
mode: 'agent'
|
||||
---
|
||||
|
||||
# Copilot Instructions Blueprint Generator
|
||||
|
||||
## Configuration Variables
|
||||
${PROJECT_TYPE="Auto-detect|.NET|Java|JavaScript|TypeScript|React|Angular|Python|Multiple|Other"} <!-- Primary technology -->
|
||||
${ARCHITECTURE_STYLE="Layered|Microservices|Monolithic|Domain-Driven|Event-Driven|Serverless|Mixed"} <!-- Architectural approach -->
|
||||
${CODE_QUALITY_FOCUS="Maintainability|Performance|Security|Accessibility|Testability|All"} <!-- Quality priorities -->
|
||||
${DOCUMENTATION_LEVEL="Minimal|Standard|Comprehensive"} <!-- Documentation requirements -->
|
||||
${TESTING_REQUIREMENTS="Unit|Integration|E2E|TDD|BDD|All"} <!-- Testing approach -->
|
||||
${VERSIONING="Semantic|CalVer|Custom"} <!-- Versioning approach -->
|
||||
|
||||
## Generated Prompt
|
||||
|
||||
"Generate a comprehensive copilot-instructions.md file that will guide GitHub Copilot to produce code consistent with our project's standards, architecture, and technology versions. The instructions must be strictly based on actual code patterns in our codebase and avoid making any assumptions. Follow this approach:
|
||||
|
||||
### 1. Core Instruction Structure
|
||||
|
||||
```markdown
|
||||
# GitHub Copilot Instructions
|
||||
|
||||
## Priority Guidelines
|
||||
|
||||
When generating code for this repository:
|
||||
|
||||
1. **Version Compatibility**: Always detect and respect the exact versions of languages, frameworks, and libraries used in this project
|
||||
2. **Context Files**: Prioritize patterns and standards defined in the .github/copilot directory
|
||||
3. **Codebase Patterns**: When context files don't provide specific guidance, scan the codebase for established patterns
|
||||
4. **Architectural Consistency**: Maintain our ${ARCHITECTURE_STYLE} architectural style and established boundaries
|
||||
5. **Code Quality**: Prioritize ${CODE_QUALITY_FOCUS == "All" ? "maintainability, performance, security, accessibility, and testability" : CODE_QUALITY_FOCUS} in all generated code
|
||||
|
||||
## Technology Version Detection
|
||||
|
||||
Before generating code, scan the codebase to identify:
|
||||
|
||||
1. **Language Versions**: Detect the exact versions of programming languages in use
|
||||
- Examine project files, configuration files, and package managers
|
||||
- Look for language-specific version indicators (e.g., <LangVersion> in .NET projects)
|
||||
- Never use language features beyond the detected version
|
||||
|
||||
2. **Framework Versions**: Identify the exact versions of all frameworks
|
||||
- Check package.json, .csproj, pom.xml, requirements.txt, etc.
|
||||
- Respect version constraints when generating code
|
||||
- Never suggest features not available in the detected framework versions
|
||||
|
||||
3. **Library Versions**: Note the exact versions of key libraries and dependencies
|
||||
- Generate code compatible with these specific versions
|
||||
- Never use APIs or features not available in the detected versions
|
||||
|
||||
## Context Files
|
||||
|
||||
Prioritize the following files in .github/copilot directory (if they exist):
|
||||
|
||||
- **architecture.md**: System architecture guidelines
|
||||
- **tech-stack.md**: Technology versions and framework details
|
||||
- **coding-standards.md**: Code style and formatting standards
|
||||
- **folder-structure.md**: Project organization guidelines
|
||||
- **exemplars.md**: Exemplary code patterns to follow
|
||||
|
||||
## Codebase Scanning Instructions
|
||||
|
||||
When context files don't provide specific guidance:
|
||||
|
||||
1. Identify similar files to the one being modified or created
|
||||
2. Analyze patterns for:
|
||||
- Naming conventions
|
||||
- Code organization
|
||||
- Error handling
|
||||
- Logging approaches
|
||||
- Documentation style
|
||||
- Testing patterns
|
||||
|
||||
3. Follow the most consistent patterns found in the codebase
|
||||
4. When conflicting patterns exist, prioritize patterns in newer files or files with higher test coverage
|
||||
5. Never introduce patterns not found in the existing codebase
|
||||
|
||||
## Code Quality Standards
|
||||
|
||||
${CODE_QUALITY_FOCUS.includes("Maintainability") || CODE_QUALITY_FOCUS == "All" ? `### Maintainability
|
||||
- Write self-documenting code with clear naming
|
||||
- Follow the naming and organization conventions evident in the codebase
|
||||
- Follow established patterns for consistency
|
||||
- Keep functions focused on single responsibilities
|
||||
- Limit function complexity and length to match existing patterns` : ""}
|
||||
|
||||
${CODE_QUALITY_FOCUS.includes("Performance") || CODE_QUALITY_FOCUS == "All" ? `### Performance
|
||||
- Follow existing patterns for memory and resource management
|
||||
- Match existing patterns for handling computationally expensive operations
|
||||
- Follow established patterns for asynchronous operations
|
||||
- Apply caching consistently with existing patterns
|
||||
- Optimize according to patterns evident in the codebase` : ""}
|
||||
|
||||
${CODE_QUALITY_FOCUS.includes("Security") || CODE_QUALITY_FOCUS == "All" ? `### Security
|
||||
- Follow existing patterns for input validation
|
||||
- Apply the same sanitization techniques used in the codebase
|
||||
- Use parameterized queries matching existing patterns
|
||||
- Follow established authentication and authorization patterns
|
||||
- Handle sensitive data according to existing patterns` : ""}
|
||||
|
||||
${CODE_QUALITY_FOCUS.includes("Accessibility") || CODE_QUALITY_FOCUS == "All" ? `### Accessibility
|
||||
- Follow existing accessibility patterns in the codebase
|
||||
- Match ARIA attribute usage with existing components
|
||||
- Maintain keyboard navigation support consistent with existing code
|
||||
- Follow established patterns for color and contrast
|
||||
- Apply text alternative patterns consistent with the codebase` : ""}
|
||||
|
||||
${CODE_QUALITY_FOCUS.includes("Testability") || CODE_QUALITY_FOCUS == "All" ? `### Testability
|
||||
- Follow established patterns for testable code
|
||||
- Match dependency injection approaches used in the codebase
|
||||
- Apply the same patterns for managing dependencies
|
||||
- Follow established mocking and test double patterns
|
||||
- Match the testing style used in existing tests` : ""}
|
||||
|
||||
## Documentation Requirements
|
||||
|
||||
${DOCUMENTATION_LEVEL == "Minimal" ?
|
||||
`- Match the level and style of comments found in existing code
|
||||
- Document according to patterns observed in the codebase
|
||||
- Follow existing patterns for documenting non-obvious behavior
|
||||
- Use the same format for parameter descriptions as existing code` : ""}
|
||||
|
||||
${DOCUMENTATION_LEVEL == "Standard" ?
|
||||
`- Follow the exact documentation format found in the codebase
|
||||
- Match the XML/JSDoc style and completeness of existing comments
|
||||
- Document parameters, returns, and exceptions in the same style
|
||||
- Follow existing patterns for usage examples
|
||||
- Match class-level documentation style and content` : ""}
|
||||
|
||||
${DOCUMENTATION_LEVEL == "Comprehensive" ?
|
||||
`- Follow the most detailed documentation patterns found in the codebase
|
||||
- Match the style and completeness of the best-documented code
|
||||
- Document exactly as the most thoroughly documented files do
|
||||
- Follow existing patterns for linking documentation
|
||||
- Match the level of detail in explanations of design decisions` : ""}
|
||||
|
||||
## Testing Approach
|
||||
|
||||
${TESTING_REQUIREMENTS.includes("Unit") || TESTING_REQUIREMENTS == "All" ?
|
||||
`### Unit Testing
|
||||
- Match the exact structure and style of existing unit tests
|
||||
- Follow the same naming conventions for test classes and methods
|
||||
- Use the same assertion patterns found in existing tests
|
||||
- Apply the same mocking approach used in the codebase
|
||||
- Follow existing patterns for test isolation` : ""}
|
||||
|
||||
${TESTING_REQUIREMENTS.includes("Integration") || TESTING_REQUIREMENTS == "All" ?
|
||||
`### Integration Testing
|
||||
- Follow the same integration test patterns found in the codebase
|
||||
- Match existing patterns for test data setup and teardown
|
||||
- Use the same approach for testing component interactions
|
||||
- Follow existing patterns for verifying system behavior` : ""}
|
||||
|
||||
${TESTING_REQUIREMENTS.includes("E2E") || TESTING_REQUIREMENTS == "All" ?
|
||||
`### End-to-End Testing
|
||||
- Match the existing E2E test structure and patterns
|
||||
- Follow established patterns for UI testing
|
||||
- Apply the same approach for verifying user journeys` : ""}
|
||||
|
||||
${TESTING_REQUIREMENTS.includes("TDD") || TESTING_REQUIREMENTS == "All" ?
|
||||
`### Test-Driven Development
|
||||
- Follow TDD patterns evident in the codebase
|
||||
- Match the progression of test cases seen in existing code
|
||||
- Apply the same refactoring patterns after tests pass` : ""}
|
||||
|
||||
${TESTING_REQUIREMENTS.includes("BDD") || TESTING_REQUIREMENTS == "All" ?
|
||||
`### Behavior-Driven Development
|
||||
- Match the existing Given-When-Then structure in tests
|
||||
- Follow the same patterns for behavior descriptions
|
||||
- Apply the same level of business focus in test cases` : ""}
|
||||
|
||||
## Technology-Specific Guidelines
|
||||
|
||||
${PROJECT_TYPE == ".NET" || PROJECT_TYPE == "Auto-detect" || PROJECT_TYPE == "Multiple" ? `### .NET Guidelines
|
||||
- Detect and strictly adhere to the specific .NET version in use
|
||||
- Use only C# language features compatible with the detected version
|
||||
- Follow LINQ usage patterns exactly as they appear in the codebase
|
||||
- Match async/await usage patterns from existing code
|
||||
- Apply the same dependency injection approach used in the codebase
|
||||
- Use the same collection types and patterns found in existing code` : ""}
|
||||
|
||||
${PROJECT_TYPE == "Java" || PROJECT_TYPE == "Auto-detect" || PROJECT_TYPE == "Multiple" ? `### Java Guidelines
|
||||
- Detect and adhere to the specific Java version in use
|
||||
- Follow the exact same design patterns found in the codebase
|
||||
- Match exception handling patterns from existing code
|
||||
- Use the same collection types and approaches found in the codebase
|
||||
- Apply the dependency injection patterns evident in existing code` : ""}
|
||||
|
||||
${PROJECT_TYPE == "JavaScript" || PROJECT_TYPE == "TypeScript" || PROJECT_TYPE == "Auto-detect" || PROJECT_TYPE == "Multiple" ? `### JavaScript/TypeScript Guidelines
|
||||
- Detect and adhere to the specific ECMAScript/TypeScript version in use
|
||||
- Follow the same module import/export patterns found in the codebase
|
||||
- Match TypeScript type definitions with existing patterns
|
||||
- Use the same async patterns (promises, async/await) as existing code
|
||||
- Follow error handling patterns from similar files` : ""}
|
||||
|
||||
${PROJECT_TYPE == "React" || PROJECT_TYPE == "Auto-detect" || PROJECT_TYPE == "Multiple" ? `### React Guidelines
|
||||
- Detect and adhere to the specific React version in use
|
||||
- Match component structure patterns from existing components
|
||||
- Follow the same hooks and lifecycle patterns found in the codebase
|
||||
- Apply the same state management approach used in existing components
|
||||
- Match prop typing and validation patterns from existing code` : ""}
|
||||
|
||||
${PROJECT_TYPE == "Angular" || PROJECT_TYPE == "Auto-detect" || PROJECT_TYPE == "Multiple" ? `### Angular Guidelines
|
||||
- Detect and adhere to the specific Angular version in use
|
||||
- Follow the same component and module patterns found in the codebase
|
||||
- Match decorator usage exactly as seen in existing code
|
||||
- Apply the same RxJS patterns found in the codebase
|
||||
- Follow existing patterns for component communication` : ""}
|
||||
|
||||
${PROJECT_TYPE == "Python" || PROJECT_TYPE == "Auto-detect" || PROJECT_TYPE == "Multiple" ? `### Python Guidelines
|
||||
- Detect and adhere to the specific Python version in use
|
||||
- Follow the same import organization found in existing modules
|
||||
- Match type hinting approaches if used in the codebase
|
||||
- Apply the same error handling patterns found in existing code
|
||||
- Follow the same module organization patterns` : ""}
|
||||
|
||||
## Version Control Guidelines
|
||||
|
||||
${VERSIONING == "Semantic" ?
|
||||
`- Follow Semantic Versioning patterns as applied in the codebase
|
||||
- Match existing patterns for documenting breaking changes
|
||||
- Follow the same approach for deprecation notices` : ""}
|
||||
|
||||
${VERSIONING == "CalVer" ?
|
||||
`- Follow Calendar Versioning patterns as applied in the codebase
|
||||
- Match existing patterns for documenting changes
|
||||
- Follow the same approach for highlighting significant changes` : ""}
|
||||
|
||||
${VERSIONING == "Custom" ?
|
||||
`- Match the exact versioning pattern observed in the codebase
|
||||
- Follow the same changelog format used in existing documentation
|
||||
- Apply the same tagging conventions used in the project` : ""}
|
||||
|
||||
## General Best Practices
|
||||
|
||||
- Follow naming conventions exactly as they appear in existing code
|
||||
- Match code organization patterns from similar files
|
||||
- Apply error handling consistent with existing patterns
|
||||
- Follow the same approach to testing as seen in the codebase
|
||||
- Match logging patterns from existing code
|
||||
- Use the same approach to configuration as seen in the codebase
|
||||
|
||||
## Project-Specific Guidance
|
||||
|
||||
- Scan the codebase thoroughly before generating any code
|
||||
- Respect existing architectural boundaries without exception
|
||||
- Match the style and patterns of surrounding code
|
||||
- When in doubt, prioritize consistency with existing code over external best practices
|
||||
```
|
||||
|
||||
### 2. Codebase Analysis Instructions
|
||||
|
||||
To create the copilot-instructions.md file, first analyze the codebase to:
|
||||
|
||||
1. **Identify Exact Technology Versions**:
|
||||
- ${PROJECT_TYPE == "Auto-detect" ? "Detect all programming languages, frameworks, and libraries by scanning file extensions and configuration files" : `Focus on ${PROJECT_TYPE} technologies`}
|
||||
- Extract precise version information from project files, package.json, .csproj, etc.
|
||||
- Document version constraints and compatibility requirements
|
||||
|
||||
2. **Understand Architecture**:
|
||||
- Analyze folder structure and module organization
|
||||
- Identify clear layer boundaries and component relationships
|
||||
- Document communication patterns between components
|
||||
|
||||
3. **Document Code Patterns**:
|
||||
- Catalog naming conventions for different code elements
|
||||
- Note documentation styles and completeness
|
||||
- Document error handling patterns
|
||||
- Map testing approaches and coverage
|
||||
|
||||
4. **Note Quality Standards**:
|
||||
- Identify performance optimization techniques actually used
|
||||
- Document security practices implemented in the code
|
||||
- Note accessibility features present (if applicable)
|
||||
- Document code quality patterns evident in the codebase
|
||||
|
||||
### 3. Implementation Notes
|
||||
|
||||
The final copilot-instructions.md should:
|
||||
- Be placed in the .github directory
|
||||
- Reference only patterns and standards that exist in the codebase
|
||||
- Include explicit version compatibility requirements
|
||||
- Avoid prescribing any practices not evident in the code
|
||||
- Provide concrete examples from the codebase
|
||||
- Be comprehensive yet concise enough for Copilot to effectively use
|
||||
|
||||
Important: Only include guidance based on patterns actually observed in the codebase. Explicitly instruct Copilot to prioritize consistency with existing code over external best practices or newer language features.
|
||||
"
|
||||
|
||||
## Expected Output
|
||||
|
||||
A comprehensive copilot-instructions.md file that will guide GitHub Copilot to produce code that is perfectly compatible with your existing technology versions and follows your established patterns and architecture.
|
||||
@@ -0,0 +1,249 @@
|
||||
---
|
||||
description: "Prompt for generating an AGENTS.md file for a repository"
|
||||
mode: "agent"
|
||||
---
|
||||
|
||||
# Create high‑quality AGENTS.md file
|
||||
|
||||
You are a code agent. Your task is to create a complete, accurate AGENTS.md at the root of this repository that follows the public guidance at https://agents.md/.
|
||||
|
||||
AGENTS.md is an open format designed to provide coding agents with the context and instructions they need to work effectively on a project.
|
||||
|
||||
## What is AGENTS.md?
|
||||
|
||||
AGENTS.md is a Markdown file that serves as a "README for agents" - a dedicated, predictable place to provide context and instructions to help AI coding agents work on your project. It complements README.md by containing detailed technical context that coding agents need but might clutter a human-focused README.
|
||||
|
||||
## Key Principles
|
||||
|
||||
- **Agent-focused**: Contains detailed technical instructions for automated tools
|
||||
- **Complements README.md**: Doesn't replace human documentation but adds agent-specific context
|
||||
- **Standardized location**: Placed at repository root (or subproject roots for monorepos)
|
||||
- **Open format**: Uses standard Markdown with flexible structure
|
||||
- **Ecosystem compatibility**: Works across 20+ different AI coding tools and agents
|
||||
|
||||
## File Structure and Content Guidelines
|
||||
|
||||
### 1. Required Setup
|
||||
|
||||
- Create the file as `AGENTS.md` in the repository root
|
||||
- Use standard Markdown formatting
|
||||
- No required fields - flexible structure based on project needs
|
||||
|
||||
### 2. Essential Sections to Include
|
||||
|
||||
#### Project Overview
|
||||
|
||||
- Brief description of what the project does
|
||||
- Architecture overview if complex
|
||||
- Key technologies and frameworks used
|
||||
|
||||
#### Setup Commands
|
||||
|
||||
- Installation instructions
|
||||
- Environment setup steps
|
||||
- Dependency management commands
|
||||
- Database setup if applicable
|
||||
|
||||
#### Development Workflow
|
||||
|
||||
- How to start development server
|
||||
- Build commands
|
||||
- Watch/hot-reload setup
|
||||
- Package manager specifics (npm, pnpm, yarn, etc.)
|
||||
|
||||
#### Testing Instructions
|
||||
|
||||
- How to run tests (unit, integration, e2e)
|
||||
- Test file locations and naming conventions
|
||||
- Coverage requirements
|
||||
- Specific test patterns or frameworks used
|
||||
- How to run subset of tests or focus on specific areas
|
||||
|
||||
#### Code Style Guidelines
|
||||
|
||||
- Language-specific conventions
|
||||
- Linting and formatting rules
|
||||
- File organization patterns
|
||||
- Naming conventions
|
||||
- Import/export patterns
|
||||
|
||||
#### Build and Deployment
|
||||
|
||||
- Build commands and outputs
|
||||
- Environment configurations
|
||||
- Deployment steps and requirements
|
||||
- CI/CD pipeline information
|
||||
|
||||
### 3. Optional but Recommended Sections
|
||||
|
||||
#### Security Considerations
|
||||
|
||||
- Security testing requirements
|
||||
- Secrets management
|
||||
- Authentication patterns
|
||||
- Permission models
|
||||
|
||||
#### Monorepo Instructions (if applicable)
|
||||
|
||||
- How to work with multiple packages
|
||||
- Cross-package dependencies
|
||||
- Selective building/testing
|
||||
- Package-specific commands
|
||||
|
||||
#### Pull Request Guidelines
|
||||
|
||||
- Title format requirements
|
||||
- Required checks before submission
|
||||
- Review process
|
||||
- Commit message conventions
|
||||
|
||||
#### Debugging and Troubleshooting
|
||||
|
||||
- Common issues and solutions
|
||||
- Logging patterns
|
||||
- Debug configuration
|
||||
- Performance considerations
|
||||
|
||||
## Example Template
|
||||
|
||||
Use this as a starting template and customize based on the specific project:
|
||||
|
||||
```markdown
|
||||
# AGENTS.md
|
||||
|
||||
## Project Overview
|
||||
|
||||
[Brief description of the project, its purpose, and key technologies]
|
||||
|
||||
## Setup Commands
|
||||
|
||||
- Install dependencies: `[package manager] install`
|
||||
- Start development server: `[command]`
|
||||
- Build for production: `[command]`
|
||||
|
||||
## Development Workflow
|
||||
|
||||
- [Development server startup instructions]
|
||||
- [Hot reload/watch mode information]
|
||||
- [Environment variable setup]
|
||||
|
||||
## Testing Instructions
|
||||
|
||||
- Run all tests: `[command]`
|
||||
- Run unit tests: `[command]`
|
||||
- Run integration tests: `[command]`
|
||||
- Test coverage: `[command]`
|
||||
- [Specific testing patterns or requirements]
|
||||
|
||||
## Code Style
|
||||
|
||||
- [Language and framework conventions]
|
||||
- [Linting rules and commands]
|
||||
- [Formatting requirements]
|
||||
- [File organization patterns]
|
||||
|
||||
## Build and Deployment
|
||||
|
||||
- [Build process details]
|
||||
- [Output directories]
|
||||
- [Environment-specific builds]
|
||||
- [Deployment commands]
|
||||
|
||||
## Pull Request Guidelines
|
||||
|
||||
- Title format: [component] Brief description
|
||||
- Required checks: `[lint command]`, `[test command]`
|
||||
- [Review requirements]
|
||||
|
||||
## Additional Notes
|
||||
|
||||
- [Any project-specific context]
|
||||
- [Common gotchas or troubleshooting tips]
|
||||
- [Performance considerations]
|
||||
```
|
||||
|
||||
## Working Example from agents.md
|
||||
|
||||
Here's a real example from the agents.md website:
|
||||
|
||||
```markdown
|
||||
# Sample AGENTS.md file
|
||||
|
||||
## Dev environment tips
|
||||
|
||||
- Use `pnpm dlx turbo run where <project_name>` to jump to a package instead of scanning with `ls`.
|
||||
- Run `pnpm install --filter <project_name>` to add the package to your workspace so Vite, ESLint, and TypeScript can see it.
|
||||
- Use `pnpm create vite@latest <project_name> -- --template react-ts` to spin up a new React + Vite package with TypeScript checks ready.
|
||||
- Check the name field inside each package's package.json to confirm the right name—skip the top-level one.
|
||||
|
||||
## Testing instructions
|
||||
|
||||
- Find the CI plan in the .github/workflows folder.
|
||||
- Run `pnpm turbo run test --filter <project_name>` to run every check defined for that package.
|
||||
- From the package root you can just call `pnpm test`. The commit should pass all tests before you merge.
|
||||
- To focus on one step, add the Vitest pattern: `pnpm vitest run -t "<test name>"`.
|
||||
- Fix any test or type errors until the whole suite is green.
|
||||
- After moving files or changing imports, run `pnpm lint --filter <project_name>` to be sure ESLint and TypeScript rules still pass.
|
||||
- Add or update tests for the code you change, even if nobody asked.
|
||||
|
||||
## PR instructions
|
||||
|
||||
- Title format: [<project_name>] <Title>
|
||||
- Always run `pnpm lint` and `pnpm test` before committing.
|
||||
```
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
1. **Analyze the project structure** to understand:
|
||||
|
||||
- Programming languages and frameworks used
|
||||
- Package managers and build tools
|
||||
- Testing frameworks
|
||||
- Project architecture (monorepo, single package, etc.)
|
||||
|
||||
2. **Identify key workflows** by examining:
|
||||
|
||||
- package.json scripts
|
||||
- Makefile or other build files
|
||||
- CI/CD configuration files
|
||||
- Documentation files
|
||||
|
||||
3. **Create comprehensive sections** covering:
|
||||
|
||||
- All essential setup and development commands
|
||||
- Testing strategies and commands
|
||||
- Code style and conventions
|
||||
- Build and deployment processes
|
||||
|
||||
4. **Include specific, actionable commands** that agents can execute directly
|
||||
|
||||
5. **Test the instructions** by ensuring all commands work as documented
|
||||
|
||||
6. **Keep it focused** on what agents need to know, not general project information
|
||||
|
||||
## Best Practices
|
||||
|
||||
- **Be specific**: Include exact commands, not vague descriptions
|
||||
- **Use code blocks**: Wrap commands in backticks for clarity
|
||||
- **Include context**: Explain why certain steps are needed
|
||||
- **Stay current**: Update as the project evolves
|
||||
- **Test commands**: Ensure all listed commands actually work
|
||||
- **Consider nested files**: For monorepos, create AGENTS.md files in subprojects as needed
|
||||
|
||||
## Monorepo Considerations
|
||||
|
||||
For large monorepos:
|
||||
|
||||
- Place a main AGENTS.md at the repository root
|
||||
- Create additional AGENTS.md files in subproject directories
|
||||
- The closest AGENTS.md file takes precedence for any given location
|
||||
- Include navigation tips between packages/projects
|
||||
|
||||
## Final Notes
|
||||
|
||||
- AGENTS.md works with 20+ AI coding tools including Cursor, Aider, Gemini CLI, and many others
|
||||
- The format is intentionally flexible - adapt it to your project's needs
|
||||
- Focus on actionable instructions that help agents understand and work with your codebase
|
||||
- This is living documentation - update it as your project evolves
|
||||
|
||||
When creating the AGENTS.md file, prioritize clarity, completeness, and actionability. The goal is to give any coding agent enough context to effectively contribute to the project without requiring additional human guidance.
|
||||
@@ -0,0 +1,127 @@
|
||||
---
|
||||
mode: 'agent'
|
||||
description: 'Create a new specification file for the solution, optimized for Generative AI consumption.'
|
||||
tools: ['changes', 'codebase', 'editFiles', 'extensions', 'fetch', 'githubRepo', 'openSimpleBrowser', 'problems', 'runTasks', 'search', 'searchResults', 'terminalLastCommand', 'terminalSelection', 'testFailure', 'usages', 'vscodeAPI']
|
||||
---
|
||||
# Create Specification
|
||||
|
||||
Your goal is to create a new specification file for `${input:SpecPurpose}`.
|
||||
|
||||
The specification file must define the requirements, constraints, and interfaces for the solution components in a manner that is clear, unambiguous, and structured for effective use by Generative AIs. Follow established documentation standards and ensure the content is machine-readable and self-contained.
|
||||
|
||||
## Best Practices for AI-Ready Specifications
|
||||
|
||||
- Use precise, explicit, and unambiguous language.
|
||||
- Clearly distinguish between requirements, constraints, and recommendations.
|
||||
- Use structured formatting (headings, lists, tables) for easy parsing.
|
||||
- Avoid idioms, metaphors, or context-dependent references.
|
||||
- Define all acronyms and domain-specific terms.
|
||||
- Include examples and edge cases where applicable.
|
||||
- Ensure the document is self-contained and does not rely on external context.
|
||||
|
||||
The specification should be saved in the [/spec/](/spec/) directory and named according to the following convention: `spec-[a-z0-9-]+.md`, where the name should be descriptive of the specification's content and starting with the highlevel purpose, which is one of [schema, tool, data, infrastructure, process, architecture, or design].
|
||||
|
||||
The specification file must be formatted in well formed Markdown.
|
||||
|
||||
Specification files must follow the template below, ensuring that all sections are filled out appropriately. The front matter for the markdown should be structured correctly as per the example following:
|
||||
|
||||
```md
|
||||
---
|
||||
title: [Concise Title Describing the Specification's Focus]
|
||||
version: [Optional: e.g., 1.0, Date]
|
||||
date_created: [YYYY-MM-DD]
|
||||
last_updated: [Optional: YYYY-MM-DD]
|
||||
owner: [Optional: Team/Individual responsible for this spec]
|
||||
tags: [Optional: List of relevant tags or categories, e.g., `infrastructure`, `process`, `design`, `app` etc]
|
||||
---
|
||||
|
||||
# Introduction
|
||||
|
||||
[A short concise introduction to the specification and the goal it is intended to achieve.]
|
||||
|
||||
## 1. Purpose & Scope
|
||||
|
||||
[Provide a clear, concise description of the specification's purpose and the scope of its application. State the intended audience and any assumptions.]
|
||||
|
||||
## 2. Definitions
|
||||
|
||||
[List and define all acronyms, abbreviations, and domain-specific terms used in this specification.]
|
||||
|
||||
## 3. Requirements, Constraints & Guidelines
|
||||
|
||||
[Explicitly list all requirements, constraints, rules, and guidelines. Use bullet points or tables for clarity.]
|
||||
|
||||
- **REQ-001**: Requirement 1
|
||||
- **SEC-001**: Security Requirement 1
|
||||
- **[3 LETTERS]-001**: Other Requirement 1
|
||||
- **CON-001**: Constraint 1
|
||||
- **GUD-001**: Guideline 1
|
||||
- **PAT-001**: Pattern to follow 1
|
||||
|
||||
## 4. Interfaces & Data Contracts
|
||||
|
||||
[Describe the interfaces, APIs, data contracts, or integration points. Use tables or code blocks for schemas and examples.]
|
||||
|
||||
## 5. Acceptance Criteria
|
||||
|
||||
[Define clear, testable acceptance criteria for each requirement using Given-When-Then format where appropriate.]
|
||||
|
||||
- **AC-001**: Given [context], When [action], Then [expected outcome]
|
||||
- **AC-002**: The system shall [specific behavior] when [condition]
|
||||
- **AC-003**: [Additional acceptance criteria as needed]
|
||||
|
||||
## 6. Test Automation Strategy
|
||||
|
||||
[Define the testing approach, frameworks, and automation requirements.]
|
||||
|
||||
- **Test Levels**: Unit, Integration, End-to-End
|
||||
- **Frameworks**: MSTest, FluentAssertions, Moq (for .NET applications)
|
||||
- **Test Data Management**: [approach for test data creation and cleanup]
|
||||
- **CI/CD Integration**: [automated testing in GitHub Actions pipelines]
|
||||
- **Coverage Requirements**: [minimum code coverage thresholds]
|
||||
- **Performance Testing**: [approach for load and performance testing]
|
||||
|
||||
## 7. Rationale & Context
|
||||
|
||||
[Explain the reasoning behind the requirements, constraints, and guidelines. Provide context for design decisions.]
|
||||
|
||||
## 8. Dependencies & External Integrations
|
||||
|
||||
[Define the external systems, services, and architectural dependencies required for this specification. Focus on **what** is needed rather than **how** it's implemented. Avoid specific package or library versions unless they represent architectural constraints.]
|
||||
|
||||
### External Systems
|
||||
- **EXT-001**: [External system name] - [Purpose and integration type]
|
||||
|
||||
### Third-Party Services
|
||||
- **SVC-001**: [Service name] - [Required capabilities and SLA requirements]
|
||||
|
||||
### Infrastructure Dependencies
|
||||
- **INF-001**: [Infrastructure component] - [Requirements and constraints]
|
||||
|
||||
### Data Dependencies
|
||||
- **DAT-001**: [External data source] - [Format, frequency, and access requirements]
|
||||
|
||||
### Technology Platform Dependencies
|
||||
- **PLT-001**: [Platform/runtime requirement] - [Version constraints and rationale]
|
||||
|
||||
### Compliance Dependencies
|
||||
- **COM-001**: [Regulatory or compliance requirement] - [Impact on implementation]
|
||||
|
||||
**Note**: This section should focus on architectural and business dependencies, not specific package implementations. For example, specify "OAuth 2.0 authentication library" rather than "Microsoft.AspNetCore.Authentication.JwtBearer v6.0.1".
|
||||
|
||||
## 9. Examples & Edge Cases
|
||||
|
||||
```code
|
||||
// Code snippet or data example demonstrating the correct application of the guidelines, including edge cases
|
||||
```
|
||||
|
||||
## 10. Validation Criteria
|
||||
|
||||
[List the criteria or tests that must be satisfied for compliance with this specification.]
|
||||
|
||||
## 11. Related Specifications / Further Reading
|
||||
|
||||
[Link to related spec 1]
|
||||
[Link to relevant external documentation]
|
||||
|
||||
```
|
||||
@@ -0,0 +1,15 @@
|
||||
---
|
||||
mode: 'agent'
|
||||
description: 'Review and refactor code in your project according to defined instructions'
|
||||
---
|
||||
|
||||
## Role
|
||||
|
||||
You're a senior expert software engineer with extensive experience in maintaining projects over a long time and ensuring clean code and best practices.
|
||||
|
||||
## Task
|
||||
|
||||
1. Take a deep breath, and review all coding guidelines instructions in `.github/instructions/*.md` and `.github/copilot-instructions.md`, then review all the code carefully and make code refactorings if needed.
|
||||
2. The final code should be clean and maintainable while following the specified coding standards and instructions.
|
||||
3. Do not split up the code, keep the existing files intact.
|
||||
4. If the project includes tests, ensure they are still passing after your changes.
|
||||
@@ -0,0 +1,127 @@
|
||||
---
|
||||
mode: 'agent'
|
||||
description: 'Update an existing specification file for the solution, optimized for Generative AI consumption based on new requirements or updates to any existing code.'
|
||||
tools: ['changes', 'codebase', 'editFiles', 'extensions', 'fetch', 'githubRepo', 'openSimpleBrowser', 'problems', 'runTasks', 'search', 'searchResults', 'terminalLastCommand', 'terminalSelection', 'testFailure', 'usages', 'vscodeAPI']
|
||||
---
|
||||
# Update Specification
|
||||
|
||||
Your goal is to update the existing specification file `${file}` based on new requirements or updates to any existing code.
|
||||
|
||||
The specification file must define the requirements, constraints, and interfaces for the solution components in a manner that is clear, unambiguous, and structured for effective use by Generative AIs. Follow established documentation standards and ensure the content is machine-readable and self-contained.
|
||||
|
||||
## Best Practices for AI-Ready Specifications
|
||||
|
||||
- Use precise, explicit, and unambiguous language.
|
||||
- Clearly distinguish between requirements, constraints, and recommendations.
|
||||
- Use structured formatting (headings, lists, tables) for easy parsing.
|
||||
- Avoid idioms, metaphors, or context-dependent references.
|
||||
- Define all acronyms and domain-specific terms.
|
||||
- Include examples and edge cases where applicable.
|
||||
- Ensure the document is self-contained and does not rely on external context.
|
||||
|
||||
The specification should be saved in the [/spec/](/spec/) directory and named according to the following convention: `[a-z0-9-]+.md`, where the name should be descriptive of the specification's content and starting with the highlevel purpose, which is one of [schema, tool, data, infrastructure, process, architecture, or design].
|
||||
|
||||
The specification file must be formatted in well formed Markdown.
|
||||
|
||||
Specification files must follow the template below, ensuring that all sections are filled out appropriately. The front matter for the markdown should be structured correctly as per the example following:
|
||||
|
||||
```md
|
||||
---
|
||||
title: [Concise Title Describing the Specification's Focus]
|
||||
version: [Optional: e.g., 1.0, Date]
|
||||
date_created: [YYYY-MM-DD]
|
||||
last_updated: [Optional: YYYY-MM-DD]
|
||||
owner: [Optional: Team/Individual responsible for this spec]
|
||||
tags: [Optional: List of relevant tags or categories, e.g., `infrastructure`, `process`, `design`, `app` etc]
|
||||
---
|
||||
|
||||
# Introduction
|
||||
|
||||
[A short concise introduction to the specification and the goal it is intended to achieve.]
|
||||
|
||||
## 1. Purpose & Scope
|
||||
|
||||
[Provide a clear, concise description of the specification's purpose and the scope of its application. State the intended audience and any assumptions.]
|
||||
|
||||
## 2. Definitions
|
||||
|
||||
[List and define all acronyms, abbreviations, and domain-specific terms used in this specification.]
|
||||
|
||||
## 3. Requirements, Constraints & Guidelines
|
||||
|
||||
[Explicitly list all requirements, constraints, rules, and guidelines. Use bullet points or tables for clarity.]
|
||||
|
||||
- **REQ-001**: Requirement 1
|
||||
- **SEC-001**: Security Requirement 1
|
||||
- **[3 LETTERS]-001**: Other Requirement 1
|
||||
- **CON-001**: Constraint 1
|
||||
- **GUD-001**: Guideline 1
|
||||
- **PAT-001**: Pattern to follow 1
|
||||
|
||||
## 4. Interfaces & Data Contracts
|
||||
|
||||
[Describe the interfaces, APIs, data contracts, or integration points. Use tables or code blocks for schemas and examples.]
|
||||
|
||||
## 5. Acceptance Criteria
|
||||
|
||||
[Define clear, testable acceptance criteria for each requirement using Given-When-Then format where appropriate.]
|
||||
|
||||
- **AC-001**: Given [context], When [action], Then [expected outcome]
|
||||
- **AC-002**: The system shall [specific behavior] when [condition]
|
||||
- **AC-003**: [Additional acceptance criteria as needed]
|
||||
|
||||
## 6. Test Automation Strategy
|
||||
|
||||
[Define the testing approach, frameworks, and automation requirements.]
|
||||
|
||||
- **Test Levels**: Unit, Integration, End-to-End
|
||||
- **Frameworks**: MSTest, FluentAssertions, Moq (for .NET applications)
|
||||
- **Test Data Management**: [approach for test data creation and cleanup]
|
||||
- **CI/CD Integration**: [automated testing in GitHub Actions pipelines]
|
||||
- **Coverage Requirements**: [minimum code coverage thresholds]
|
||||
- **Performance Testing**: [approach for load and performance testing]
|
||||
|
||||
## 7. Rationale & Context
|
||||
|
||||
[Explain the reasoning behind the requirements, constraints, and guidelines. Provide context for design decisions.]
|
||||
|
||||
## 8. Dependencies & External Integrations
|
||||
|
||||
[Define the external systems, services, and architectural dependencies required for this specification. Focus on **what** is needed rather than **how** it's implemented. Avoid specific package or library versions unless they represent architectural constraints.]
|
||||
|
||||
### External Systems
|
||||
- **EXT-001**: [External system name] - [Purpose and integration type]
|
||||
|
||||
### Third-Party Services
|
||||
- **SVC-001**: [Service name] - [Required capabilities and SLA requirements]
|
||||
|
||||
### Infrastructure Dependencies
|
||||
- **INF-001**: [Infrastructure component] - [Requirements and constraints]
|
||||
|
||||
### Data Dependencies
|
||||
- **DAT-001**: [External data source] - [Format, frequency, and access requirements]
|
||||
|
||||
### Technology Platform Dependencies
|
||||
- **PLT-001**: [Platform/runtime requirement] - [Version constraints and rationale]
|
||||
|
||||
### Compliance Dependencies
|
||||
- **COM-001**: [Regulatory or compliance requirement] - [Impact on implementation]
|
||||
|
||||
**Note**: This section should focus on architectural and business dependencies, not specific package implementations. For example, specify "OAuth 2.0 authentication library" rather than "Microsoft.AspNetCore.Authentication.JwtBearer v6.0.1".
|
||||
|
||||
## 9. Examples & Edge Cases
|
||||
|
||||
```code
|
||||
// Code snippet or data example demonstrating the correct application of the guidelines, including edge cases
|
||||
```
|
||||
|
||||
## 10. Validation Criteria
|
||||
|
||||
[List the criteria or tests that must be satisfied for compliance with this specification.]
|
||||
|
||||
## 11. Related Specifications / Further Reading
|
||||
|
||||
[Link to related spec 1]
|
||||
[Link to relevant external documentation]
|
||||
|
||||
```
|
||||
@@ -1,29 +1,39 @@
|
||||
name: CI
|
||||
|
||||
on: [pull_request, push]
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- '[0-9]+.[0-9]+.[0-9]+'
|
||||
branches:
|
||||
- dev
|
||||
- master
|
||||
pull_request:
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
id-token: write
|
||||
|
||||
jobs:
|
||||
ci:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
id-token: write
|
||||
id-token: write # for npm publish
|
||||
actions: read # for Nerivec/action-ci-bench
|
||||
pull-requests: write # for Nerivec/action-ci-bench
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v6
|
||||
if: (github.ref == 'refs/heads/dev' || startsWith(github.ref, 'refs/tags/')) && github.event_name == 'push'
|
||||
with:
|
||||
# Required for `release: merge dev -> master and promote dev`
|
||||
token: ${{ secrets.GH_TOKEN }}
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v6
|
||||
if: ((github.ref == 'refs/heads/dev' || startsWith(github.ref, 'refs/tags/')) && github.event_name == 'push') == false
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24
|
||||
registry-url: https://registry.npmjs.org/
|
||||
@@ -41,6 +51,16 @@ jobs:
|
||||
- name: Test
|
||||
run: pnpm run test:coverage
|
||||
|
||||
- name: Bench
|
||||
if: github.ref == 'refs/heads/dev' || (github.event_name == 'pull_request' && !startsWith(github.head_ref, 'release-please-'))
|
||||
uses: Nerivec/action-ci-bench@main
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
compare-against: dev
|
||||
base-cmd: npx vitest bench --run --config ./test/vitest.config.mts --outputJson bench.json
|
||||
compare-cmd: npx vitest bench --run --config ./test/vitest.config.mts --compare bench.json
|
||||
base-result: bench.json
|
||||
|
||||
- name: Log in to the Docker container registry
|
||||
if: (github.ref == 'refs/heads/dev' || startsWith(github.ref, 'refs/tags/')) && github.event_name == 'push'
|
||||
uses: docker/login-action@v3
|
||||
@@ -83,6 +103,27 @@ jobs:
|
||||
VERSION=dev
|
||||
DATE=${{ github.event.repository.updated_at }}
|
||||
|
||||
- name: dev - Publish types
|
||||
if: github.ref == 'refs/heads/dev' && github.event_name == 'push'
|
||||
run: |
|
||||
pnpm run build:types
|
||||
temp_dir=$(mktemp -d)
|
||||
cp -R package.json LICENSE dist $temp_dir
|
||||
git fetch --unshallow
|
||||
git checkout dev-types
|
||||
rm -rf *
|
||||
cp -R $temp_dir/* .
|
||||
# remove unnecessary dependencies
|
||||
KEEP_DEPS='["zigbee-herdsman","zigbee-herdsman-converters"]'
|
||||
tmp_pkg=$(mktemp)
|
||||
jq --indent 4 --argjson keep "$KEEP_DEPS" 'def filterDeps: (. // {}) | with_entries(select(.key as $k | $keep | index($k))); .dependencies |= filterDeps | .devDependencies |= filterDeps | .optionalDependencies |= filterDeps' package.json > "$tmp_pkg"
|
||||
mv "$tmp_pkg" package.json
|
||||
git add -A
|
||||
git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git config --local user.name "github-actions[bot]"
|
||||
git commit -m "$GITHUB_SHA" || echo 'Nothing to commit'
|
||||
git push --force --set-upstream origin dev-types
|
||||
|
||||
- name: release - Docker meta
|
||||
if: startsWith(github.ref, 'refs/tags/') && github.event_name == 'push'
|
||||
uses: docker/metadata-action@v5
|
||||
@@ -179,11 +220,11 @@ jobs:
|
||||
runs-on: ${{ matrix.os }}
|
||||
continue-on-error: true
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: ${{ matrix.node }}
|
||||
cache: pnpm
|
||||
|
||||
@@ -10,6 +10,6 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: 'Checkout repository'
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
- name: 'Dependency review'
|
||||
uses: actions/dependency-review-action@v4
|
||||
|
||||
@@ -10,7 +10,7 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Delete untagged images
|
||||
uses: actions/github-script@v7
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
github-token: ${{ secrets.GH_TOKEN }}
|
||||
script: |
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
name: Issue Bot
|
||||
|
||||
on:
|
||||
issues:
|
||||
types: [opened, edited]
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
comment:
|
||||
runs-on: ubuntu-latest
|
||||
if: |
|
||||
contains(github.event.issue.labels.*.name, 'new device support') ||
|
||||
contains(github.event.issue.labels.*.name, 'external converter') ||
|
||||
startsWith(github.event.issue.title, '[New device support]') ||
|
||||
startsWith(github.event.issue.title, '[External Converter]')
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
sparse-checkout: |
|
||||
scripts
|
||||
path: z2m
|
||||
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
repository: Koenkk/zigbee-herdsman-converters
|
||||
ref: master
|
||||
fetch-depth: 1
|
||||
path: zhc
|
||||
|
||||
- name: Comment on new device support/external converter issue
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
const {newDeviceSupport} = await import("${{ github.workspace }}/z2m/scripts/issueBot.mjs")
|
||||
await newDeviceSupport(github, core, context, "${{ github.workspace }}/zhc")
|
||||
@@ -9,7 +9,7 @@ jobs:
|
||||
merge-master-to-dev:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v6
|
||||
- uses: devmasx/merge-branch@master
|
||||
with:
|
||||
type: now
|
||||
|
||||
@@ -20,7 +20,7 @@ jobs:
|
||||
with:
|
||||
version: 9
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
@@ -31,11 +31,11 @@ jobs:
|
||||
token: ${{secrets.GH_TOKEN}}
|
||||
|
||||
# Checkout repos
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
repository: koenkk/zigbee2mqtt
|
||||
path: ./z2m
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
repository: koenkk/zigbee2mqtt
|
||||
path: ./z2m-master
|
||||
@@ -54,10 +54,11 @@ jobs:
|
||||
MASTER_ZHC_VERSION=$(cat z2m-master/package.json | jq -r '.dependencies."zigbee-herdsman-converters"')
|
||||
MASTER_ZH_VERSION=$(cat z2m-master/package.json | jq -r '.dependencies."zigbee-herdsman"')
|
||||
MASTER_FRONTEND_VERSION=$(cat z2m-master/package.json | jq -r '.dependencies."zigbee2mqtt-frontend"')
|
||||
MASTER_WINDFRONT_VERSION=$(cat z2m-master/package.json | jq -r '.dependencies."zigbee2mqtt-windfront"')
|
||||
wget -q -O - https://raw.githubusercontent.com/Koenkk/zigbee2mqtt/release-please--branches--dev--components--zigbee2mqtt/CHANGELOG.md > z2m/CHANGELOG.md
|
||||
cd z2m
|
||||
pnpm i --frozen-lockfile
|
||||
node scripts/generateChangelog.js $MASTER_Z2M_VERSION $MASTER_ZHC_VERSION $MASTER_ZH_VERSION $MASTER_FRONTEND_VERSION >> ../changelog.md
|
||||
node scripts/generateChangelog.mjs $MASTER_Z2M_VERSION $MASTER_ZHC_VERSION $MASTER_ZH_VERSION $MASTER_FRONTEND_VERSION $MASTER_WINDFRONT_VERSION >> ../changelog.md
|
||||
env:
|
||||
GH_TOKEN: ${{secrets.GH_TOKEN}}
|
||||
- name: Update changelog gist
|
||||
|
||||
@@ -9,7 +9,7 @@ jobs:
|
||||
stale:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/stale@v9
|
||||
- uses: actions/stale@v10
|
||||
with:
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
stale-issue-message: 'This issue is stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 7 days'
|
||||
|
||||
@@ -13,12 +13,12 @@ jobs:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
ref: dev
|
||||
token: ${{ secrets.GH_TOKEN }}
|
||||
- uses: pnpm/action-setup@v4
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24
|
||||
cache: pnpm
|
||||
|
||||
@@ -53,6 +53,7 @@ typings/
|
||||
|
||||
# Build cache
|
||||
tsconfig.tsbuildinfo
|
||||
tsconfig.types.tsbuildinfo
|
||||
|
||||
# Optional REPL history
|
||||
.node_repl_history
|
||||
@@ -76,6 +77,7 @@ tsconfig.tsbuildinfo
|
||||
# Ignore config
|
||||
data/*
|
||||
!data/configuration.example.yaml
|
||||
data-bench
|
||||
|
||||
# commit-user-lookup.json
|
||||
scripts/commit-user-lookup.json
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
{
|
||||
".": "2.4.0"
|
||||
".": "2.7.1"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,386 @@
|
||||
# AGENTS.md
|
||||
|
||||
## Project Overview
|
||||
|
||||
Zigbee2MQTT is a Zigbee to MQTT bridge that allows you to use your Zigbee devices without the vendor's bridge or gateway. It bridges events and allows you to control Zigbee devices via MQTT, integrating them with any smart home infrastructure.
|
||||
|
||||
### Architecture
|
||||
|
||||
- **Language**: TypeScript 5.9.3 compiled to JavaScript (ES modules with NodeNext resolution)
|
||||
- **Runtime**: Node.js (versions 20, 22, or 24)
|
||||
- **Package Manager**: pnpm 10.12.1 (strictly enforced via `packageManager` field)
|
||||
- **Core Dependencies**:
|
||||
- `zigbee-herdsman` (6.2.0 - exact version, handles Zigbee adapter communication)
|
||||
- `zigbee-herdsman-converters` (25.42.0 - exact version, device definitions)
|
||||
- `mqtt` (5.14.1 - MQTT client)
|
||||
- `winston` (3.18.3 - logging)
|
||||
|
||||
### Project Structure
|
||||
|
||||
```
|
||||
lib/ # TypeScript source code
|
||||
├── controller.ts # Main controller orchestrating components
|
||||
├── mqtt.ts # MQTT client management
|
||||
├── zigbee.ts # Zigbee network management
|
||||
├── state.ts # State management
|
||||
├── eventBus.ts # Event-driven communication
|
||||
├── extension/ # Extension system (plugins)
|
||||
│ └── extension.ts # Abstract base class
|
||||
├── model/ # Domain models (Device, Group)
|
||||
├── util/ # Utility functions
|
||||
└── types/ # TypeScript type definitions
|
||||
test/ # Vitest test files with mocks
|
||||
data/ # Runtime configuration and database
|
||||
dist/ # Compiled JavaScript output
|
||||
```
|
||||
|
||||
## Setup Commands
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Node.js version 20, 22, or 24
|
||||
- pnpm 10.12.1 (will be auto-installed via corepack if not present)
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
# Install dependencies (uses pnpm lockfile)
|
||||
pnpm install --frozen-lockfile
|
||||
|
||||
# For development without lockfile restrictions
|
||||
pnpm install
|
||||
```
|
||||
|
||||
### Initial Build
|
||||
|
||||
```bash
|
||||
# Full build (TypeScript compilation + hash generation)
|
||||
pnpm run build
|
||||
|
||||
# Build type definitions only
|
||||
pnpm run build:types
|
||||
```
|
||||
|
||||
## Development Workflow
|
||||
|
||||
### Starting Development
|
||||
|
||||
```bash
|
||||
# Watch mode - recompile on file changes
|
||||
pnpm run build:watch
|
||||
|
||||
# In another terminal, start Zigbee2MQTT
|
||||
pnpm start
|
||||
```
|
||||
|
||||
### Code Quality Checks
|
||||
|
||||
```bash
|
||||
# Run Biome linter and formatter (check only)
|
||||
pnpm run check
|
||||
|
||||
# Auto-fix linting and formatting issues
|
||||
pnpm run check:w
|
||||
|
||||
# The check runs with --error-on-warnings flag
|
||||
# Configuration: biome.json (4-space indent, 150 line width, no bracket spacing)
|
||||
```
|
||||
|
||||
### Clean Build
|
||||
|
||||
```bash
|
||||
# Remove build artifacts
|
||||
pnpm run clean
|
||||
|
||||
# Removes: coverage/, dist/, tsconfig.tsbuildinfo
|
||||
```
|
||||
|
||||
## Testing Instructions
|
||||
|
||||
### Running Tests
|
||||
|
||||
```bash
|
||||
# Run all tests once
|
||||
pnpm test
|
||||
|
||||
# Run tests with coverage report
|
||||
pnpm run test:coverage
|
||||
|
||||
# Watch mode - re-run tests on changes
|
||||
pnpm run test:watch
|
||||
|
||||
# Run benchmarks
|
||||
pnpm run bench
|
||||
```
|
||||
|
||||
### Test Requirements
|
||||
|
||||
- **Coverage**: 100% code coverage is enforced (configured in `test/vitest.config.mts`)
|
||||
- **Framework**: Vitest 3.1.1 with @vitest/coverage-v8
|
||||
- **Test Files**: Located in `test/` directory with `.test.ts` extension
|
||||
- **Mocks**: Centralized in `test/mocks/` directory
|
||||
- **Coverage Report**: Generated in `coverage/` directory (HTML report at `coverage/index.html`)
|
||||
|
||||
### Running Specific Tests
|
||||
|
||||
```bash
|
||||
# Run tests matching a pattern
|
||||
pnpm vitest run -t "test name pattern" --config ./test/vitest.config.mts
|
||||
|
||||
# Run specific test file
|
||||
pnpm vitest run test/controller.test.ts --config ./test/vitest.config.mts
|
||||
|
||||
# Focus on one test area in watch mode
|
||||
pnpm vitest watch -t "Extension" --config ./test/vitest.config.mts
|
||||
```
|
||||
|
||||
## Code Style Guidelines
|
||||
|
||||
### TypeScript Conventions
|
||||
|
||||
- **Module System**: ES modules with NodeNext resolution
|
||||
- **Target**: ESNext
|
||||
- **Strict Mode**: Enabled (`noImplicitAny`, `noImplicitThis`)
|
||||
- **Decorators**: Experimental decorators enabled (used for `@bind` from `bind-decorator`)
|
||||
|
||||
### Import Order
|
||||
|
||||
1. Node.js built-in modules (with `node:` prefix)
|
||||
2. Third-party libraries
|
||||
3. Type-only imports from external packages (using `type` keyword)
|
||||
4. Internal absolute imports
|
||||
5. Type-only imports from internal modules
|
||||
|
||||
Example:
|
||||
```typescript
|
||||
import fs from "node:fs";
|
||||
import bind from "bind-decorator";
|
||||
import type {IClientOptions} from "mqtt";
|
||||
import {connectAsync} from "mqtt";
|
||||
import type {Zigbee2MQTTAPI} from "./types/api";
|
||||
import logger from "./util/logger";
|
||||
```
|
||||
|
||||
### Naming Conventions
|
||||
|
||||
- **Classes**: PascalCase (e.g., `Extension`, `Device`)
|
||||
- **Functions/Methods**: camelCase (e.g., `publishEntityState`)
|
||||
- **Constants**: SCREAMING_SNAKE_CASE (e.g., `CURRENT_VERSION`)
|
||||
- **Interfaces/Types**: PascalCase (e.g., `MqttPublishOptions`)
|
||||
- **Files**: camelCase for TypeScript (e.g., `eventBus.ts`)
|
||||
|
||||
### Code Patterns
|
||||
|
||||
- **Async/Await**: Always use async/await, explicitly type return as `Promise<Type>`
|
||||
- **Error Handling**: Use `throw new Error("message")`, log with winston logger
|
||||
- **Event Handlers**: Use `@bind` decorator to preserve `this` context
|
||||
- **Logging**: Use `logger.info()`, `logger.warning()`, `logger.error()`, `logger.debug()`
|
||||
|
||||
### Formatting Rules (Biome)
|
||||
|
||||
- 4-space indentation
|
||||
- 150 character line width
|
||||
- No bracket spacing in objects
|
||||
- Run `pnpm run check:w` to auto-format
|
||||
|
||||
## Build and Deployment
|
||||
|
||||
### Build Process
|
||||
|
||||
```bash
|
||||
# Production build
|
||||
pnpm run build
|
||||
|
||||
# Outputs:
|
||||
# - Compiled JavaScript in dist/
|
||||
# - Type definitions in dist/types/
|
||||
# - Includes hash generation for version tracking
|
||||
```
|
||||
|
||||
### Pre-publish
|
||||
|
||||
```bash
|
||||
# Automatically runs before publishing
|
||||
pnpm run prepack
|
||||
|
||||
# Performs: clean + build
|
||||
```
|
||||
|
||||
### Environment Setup
|
||||
|
||||
- Configuration stored in `data/configuration.yaml`
|
||||
- Database in `data/database.db`
|
||||
- Logs in `data/log/`
|
||||
- External extensions in `data/external_extensions/`
|
||||
- External converters in `data/external_converters/`
|
||||
|
||||
## Architecture Patterns
|
||||
|
||||
### Extension System
|
||||
|
||||
All features are implemented as extensions that inherit from the abstract `Extension` base class:
|
||||
|
||||
```typescript
|
||||
abstract class Extension {
|
||||
protected zigbee: Zigbee;
|
||||
protected mqtt: Mqtt;
|
||||
protected state: State;
|
||||
protected publishEntityState: PublishEntityState;
|
||||
protected eventBus: EventBus;
|
||||
|
||||
async start(): Promise<void> {} // Initialize extension
|
||||
async stop(): Promise<void> {} // Cleanup extension
|
||||
}
|
||||
```
|
||||
|
||||
**Key Points**:
|
||||
- Constructor should only assign properties (no side effects)
|
||||
- Initialization happens in `start()` method
|
||||
- Use EventBus for inter-component communication
|
||||
- Extensions are loaded and managed by the Controller
|
||||
|
||||
### Event-Driven Communication
|
||||
|
||||
Components communicate via the strongly-typed EventBus:
|
||||
|
||||
```typescript
|
||||
// Emit events
|
||||
this.eventBus.emit('deviceMessage', {device, message});
|
||||
|
||||
// Listen to events
|
||||
this.eventBus.on('deviceMessage', this.onDeviceMessage, this);
|
||||
```
|
||||
|
||||
### Dependency Injection
|
||||
|
||||
The Controller instantiates and injects dependencies into all extensions. Follow this pattern when creating new extensions.
|
||||
|
||||
## Pull Request Guidelines
|
||||
|
||||
### Target Branch
|
||||
|
||||
- **Always create PRs against the `dev` branch**
|
||||
- The `master` branch is for production releases only
|
||||
|
||||
### Before Submitting
|
||||
|
||||
```bash
|
||||
# Run all checks
|
||||
pnpm run check
|
||||
pnpm test
|
||||
|
||||
# Ensure 100% code coverage
|
||||
pnpm run test:coverage
|
||||
|
||||
# Build successfully
|
||||
pnpm run build
|
||||
```
|
||||
|
||||
### PR Requirements
|
||||
|
||||
- All CI checks must pass (linting, tests, build)
|
||||
- 100% test coverage maintained
|
||||
- Code follows Biome formatting rules
|
||||
- Commit messages should be descriptive
|
||||
- Reference related issues when applicable
|
||||
|
||||
### CI Pipeline
|
||||
|
||||
The GitHub Actions CI workflow (`.github/workflows/ci.yml`) runs:
|
||||
1. Biome code quality checks (`pnpm run check`)
|
||||
2. TypeScript compilation (`pnpm run build`)
|
||||
3. Full test suite with coverage (`pnpm run test:coverage`)
|
||||
4. Benchmarks (on dev branch and PRs)
|
||||
5. Docker image builds (on dev branch and tags)
|
||||
|
||||
## Working with Device Support
|
||||
|
||||
### Adding New Devices
|
||||
|
||||
**Important**: Device support is NOT added to this repository. All device definitions live in `zigbee-herdsman-converters`.
|
||||
|
||||
- Follow the guide at: https://www.zigbee2mqtt.io/advanced/support-new-devices/01_support_new_devices.html
|
||||
- No changes to zigbee2mqtt codebase are needed for new devices
|
||||
- Device definitions are automatically picked up from `zigbee-herdsman-converters`
|
||||
|
||||
## Debugging and Troubleshooting
|
||||
|
||||
### Development Setup
|
||||
|
||||
For the easiest development experience, set up a bare-metal installation following:
|
||||
https://www.zigbee2mqtt.io/guide/installation/01_linux.html
|
||||
|
||||
### Logging
|
||||
|
||||
- Winston logger is initialized in `lib/util/logger.ts`
|
||||
- Log levels: `error`, `warning`, `info`, `debug`
|
||||
- Logs are written to console and/or file based on configuration
|
||||
- Use structured logging with context (device names, IEEE addresses)
|
||||
|
||||
### Common Issues
|
||||
|
||||
1. **Import errors after file moves**: Run `pnpm run check` to verify TypeScript and ESLint
|
||||
2. **Test failures**: Check if mocks in `test/mocks/` need updates
|
||||
3. **Build errors**: Ensure Node.js version is 20, 22, or 24
|
||||
4. **Coverage issues**: View HTML report at `coverage/index.html` to identify uncovered code
|
||||
|
||||
### Performance Considerations
|
||||
|
||||
- Use `rimrafSync` for synchronous file operations
|
||||
- Leverage async/await to avoid blocking
|
||||
- Cache computed values in getters when appropriate
|
||||
- EventBus provides loose coupling between components
|
||||
|
||||
## Critical Version Requirements
|
||||
|
||||
### Exact Versions
|
||||
|
||||
These dependencies use **exact versions** (no semver ranges) - do not upgrade without thorough testing:
|
||||
|
||||
- `zigbee-herdsman@6.2.0` - Critical for Zigbee protocol compatibility
|
||||
- `zigbee-herdsman-converters@25.42.0` - Device definitions must match herdsman version
|
||||
|
||||
### Node.js Compatibility
|
||||
|
||||
Only these Node.js versions are supported:
|
||||
- Node.js 20.x
|
||||
- Node.js 22.x
|
||||
- Node.js 24.x
|
||||
|
||||
Using other versions may cause runtime errors or incompatibilities.
|
||||
|
||||
## Additional Notes
|
||||
|
||||
### Package Manager
|
||||
|
||||
This project **requires pnpm 10.12.1**. The `packageManager` field in package.json enforces this via Corepack.
|
||||
|
||||
Do not use npm or yarn - they will not respect the pnpm-specific configuration.
|
||||
|
||||
### TypeScript Compilation
|
||||
|
||||
- Source files in `lib/` are compiled to `dist/`
|
||||
- Type definitions exported from `dist/types/api.d.ts`
|
||||
- Source maps are inlined for debugging
|
||||
- Uses composite project references for faster incremental builds
|
||||
|
||||
### External Extensions
|
||||
|
||||
To load external extensions:
|
||||
1. Place JavaScript files in `data/external_extensions/`
|
||||
2. They will be automatically loaded on startup
|
||||
3. No configuration changes needed
|
||||
|
||||
### Code Quality Tools
|
||||
|
||||
- **Linting/Formatting**: Biome 2.2.5 (replaces ESLint + Prettier)
|
||||
- **Type Checking**: TypeScript 5.9.3
|
||||
- **Testing**: Vitest 3.1.1
|
||||
- **Coverage**: @vitest/coverage-v8
|
||||
|
||||
### Documentation
|
||||
|
||||
- Main documentation: https://www.zigbee2mqtt.io/
|
||||
- Contributing guide: `CONTRIBUTING.md`
|
||||
- Coding standards: `.github/copilot-instructions.md`
|
||||
- Issue tracker: https://github.com/Koenkk/zigbee2mqtt/issues
|
||||
+323
-1
@@ -1,5 +1,327 @@
|
||||
# Changelog
|
||||
|
||||
## [2.7.1](https://github.com/Koenkk/zigbee2mqtt/compare/2.7.0...2.7.1) (2025-12-06)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Home Assistant: Accept multiple access levels for `current_humidity` source property ([#29936](https://github.com/Koenkk/zigbee2mqtt/issues/29936)) ([fa99c6d](https://github.com/Koenkk/zigbee2mqtt/commit/fa99c6dcca97d2c8c90136249293dea3d42e0998))
|
||||
* Home Assistant: Translate boolean to state topic for `current_humidity_topic` ([#30014](https://github.com/Koenkk/zigbee2mqtt/issues/30014)) ([9ca85df](https://github.com/Koenkk/zigbee2mqtt/commit/9ca85dfac8b0f0421ad0622dfdbe36c8766d22b4))
|
||||
* **ignore:** bump finalhandler from 2.1.0 to 2.1.1 in the minor-patch group ([#29920](https://github.com/Koenkk/zigbee2mqtt/issues/29920)) ([ce27ff3](https://github.com/Koenkk/zigbee2mqtt/commit/ce27ff3cbfac204579b38d034e71733e4e4bb18f))
|
||||
* **ignore:** update zigbee-herdsman to 7.0.2 ([#29956](https://github.com/Koenkk/zigbee2mqtt/issues/29956)) ([403bd4a](https://github.com/Koenkk/zigbee2mqtt/commit/403bd4a72541bf7342de246b033c5090b186df32))
|
||||
* **ignore:** update zigbee-herdsman to 7.0.3 ([#30008](https://github.com/Koenkk/zigbee2mqtt/issues/30008)) ([bae9bb8](https://github.com/Koenkk/zigbee2mqtt/commit/bae9bb8812c81e46d4068b4284e0f9957821f88a))
|
||||
* **ignore:** update zigbee-herdsman to 7.0.4 ([#30041](https://github.com/Koenkk/zigbee2mqtt/issues/30041)) ([334fa2a](https://github.com/Koenkk/zigbee2mqtt/commit/334fa2a60d04c66749978b8b8f4b9b5af6c7c7eb))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.81.0 ([#29959](https://github.com/Koenkk/zigbee2mqtt/issues/29959)) ([fd4282b](https://github.com/Koenkk/zigbee2mqtt/commit/fd4282b98d9630f9a98e82f627c12c5920d810b4))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.82.0 ([#29990](https://github.com/Koenkk/zigbee2mqtt/issues/29990)) ([740edd8](https://github.com/Koenkk/zigbee2mqtt/commit/740edd8b58b7d72b7a2a5247f7f6ac8ee99ff0fa))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.83.0 ([#30011](https://github.com/Koenkk/zigbee2mqtt/issues/30011)) ([a7f1345](https://github.com/Koenkk/zigbee2mqtt/commit/a7f1345a9164f6c83cb81688c33511b14646fab8))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.83.1 ([#30050](https://github.com/Koenkk/zigbee2mqtt/issues/30050)) ([9b60353](https://github.com/Koenkk/zigbee2mqtt/commit/9b6035387be6f285fab455f7845baa75f3f722be))
|
||||
|
||||
## [2.7.0](https://github.com/Koenkk/zigbee2mqtt/compare/2.6.3...2.7.0) (2025-12-01)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* Add `action` bridge/request API ([#29730](https://github.com/Koenkk/zigbee2mqtt/issues/29730)) ([a61646d](https://github.com/Koenkk/zigbee2mqtt/commit/a61646d584c0a0de46abb3545cd964f65d84312d))
|
||||
* Add new bind/reporting/map features ([#29750](https://github.com/Koenkk/zigbee2mqtt/issues/29750)) ([f26ade4](https://github.com/Koenkk/zigbee2mqtt/commit/f26ade4f938350d10ed22a32a2e30365f7514a72))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Add port 8080 `EXPOSE` to container ([#29754](https://github.com/Koenkk/zigbee2mqtt/issues/29754)) ([4c21b66](https://github.com/Koenkk/zigbee2mqtt/commit/4c21b660794ee3b85c9a9a6d01b0df5ec8bce639))
|
||||
* Home Assistant: expose `current_humidity` for `climate` devices exposing `humidity` ([#29842](https://github.com/Koenkk/zigbee2mqtt/issues/29842)) ([631c4f6](https://github.com/Koenkk/zigbee2mqtt/commit/631c4f6a5729888d65a1125e0cca8f9ba2ff0e59))
|
||||
* **ignore:** bump @biomejs/biome from 2.3.3 to 2.3.4 in the minor-patch group ([#29571](https://github.com/Koenkk/zigbee2mqtt/issues/29571)) ([517b286](https://github.com/Koenkk/zigbee2mqtt/commit/517b2865835a7c21b4c5ce68018fd30ae45d1a3f))
|
||||
* **ignore:** bump debounce from 2.2.0 to 3.0.0 ([#29444](https://github.com/Koenkk/zigbee2mqtt/issues/29444)) ([8099322](https://github.com/Koenkk/zigbee2mqtt/commit/8099322cc2e93e5c1faf355d41485f2c673e0cea))
|
||||
* **ignore:** bump the minor-patch group with 2 updates ([#29443](https://github.com/Koenkk/zigbee2mqtt/issues/29443)) ([619b939](https://github.com/Koenkk/zigbee2mqtt/commit/619b939b148394bd6a083c17cc5cf254c8eb3aea))
|
||||
* **ignore:** bump the minor-patch group with 2 updates ([#29859](https://github.com/Koenkk/zigbee2mqtt/issues/29859)) ([c02ed09](https://github.com/Koenkk/zigbee2mqtt/commit/c02ed092116c7454220c0611bff5d078e12a8ecc))
|
||||
* **ignore:** bump the minor-patch group with 3 updates ([#29804](https://github.com/Koenkk/zigbee2mqtt/issues/29804)) ([e2232e9](https://github.com/Koenkk/zigbee2mqtt/commit/e2232e9e9173ea9ec55152ac33bc0ee0141471bb))
|
||||
* **ignore:** bump zigbee2mqtt-windfront from 2.4.0 to 2.4.1 in the minor-patch group ([#29905](https://github.com/Koenkk/zigbee2mqtt/issues/29905)) ([4a020fd](https://github.com/Koenkk/zigbee2mqtt/commit/4a020fd8de2dab2973b859c34b934416a15e82a5))
|
||||
* **ignore:** bump zigbee2mqtt-windfront to 2.4.2 ([#29919](https://github.com/Koenkk/zigbee2mqtt/issues/29919)) ([3dce854](https://github.com/Koenkk/zigbee2mqtt/commit/3dce8548ceee111f49a5b3460fdb2cbb4f47da62))
|
||||
* **ignore:** prop name convention on new API endpoints ([#29820](https://github.com/Koenkk/zigbee2mqtt/issues/29820)) ([ad06968](https://github.com/Koenkk/zigbee2mqtt/commit/ad0696856a9a63fc74b9c2115f08d7fd97850545))
|
||||
* **ignore:** update zigbee-herdsman to 6.3.3 ([#29500](https://github.com/Koenkk/zigbee2mqtt/issues/29500)) ([39c5bc8](https://github.com/Koenkk/zigbee2mqtt/commit/39c5bc8c0446a7ccdffe6f82ae9e7f31f60f20ba))
|
||||
* **ignore:** update zigbee-herdsman to 6.4.0 ([#29522](https://github.com/Koenkk/zigbee2mqtt/issues/29522)) ([e788c52](https://github.com/Koenkk/zigbee2mqtt/commit/e788c520a9268498daf0f88d7bedb289546d226e))
|
||||
* **ignore:** update zigbee-herdsman to 6.4.1 ([#29595](https://github.com/Koenkk/zigbee2mqtt/issues/29595)) ([61c6ec6](https://github.com/Koenkk/zigbee2mqtt/commit/61c6ec611174529e4c041a56146ba8405cfe9ed8))
|
||||
* **ignore:** update zigbee-herdsman to 6.4.2 ([#29683](https://github.com/Koenkk/zigbee2mqtt/issues/29683)) ([53b7eaa](https://github.com/Koenkk/zigbee2mqtt/commit/53b7eaabf0647c8d1edb0de24b89776991af576c))
|
||||
* **ignore:** update zigbee-herdsman to 7.0.0 ([3e2aefb](https://github.com/Koenkk/zigbee2mqtt/commit/3e2aefbcf84f43d45c1d6ca33397c8bb76648822))
|
||||
* **ignore:** update zigbee-herdsman to 7.0.1 ([#29855](https://github.com/Koenkk/zigbee2mqtt/issues/29855)) ([802271e](https://github.com/Koenkk/zigbee2mqtt/commit/802271ed37d404944d315f83f3b623ba9e424bb9))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.60.0 ([#29426](https://github.com/Koenkk/zigbee2mqtt/issues/29426)) ([eeed56e](https://github.com/Koenkk/zigbee2mqtt/commit/eeed56ef2c01dfe67e7a0cd7cafd35ef1876f5b4))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.62.0 ([#29449](https://github.com/Koenkk/zigbee2mqtt/issues/29449)) ([ea1c5a8](https://github.com/Koenkk/zigbee2mqtt/commit/ea1c5a8f4e8537a2f8c59988bb712f62a0adffd7))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.63.0 ([#29482](https://github.com/Koenkk/zigbee2mqtt/issues/29482)) ([5a6a9cf](https://github.com/Koenkk/zigbee2mqtt/commit/5a6a9cf4d2de803a10cd38bc19f3ec256eff5929))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.64.0 ([#29499](https://github.com/Koenkk/zigbee2mqtt/issues/29499)) ([5c4e43f](https://github.com/Koenkk/zigbee2mqtt/commit/5c4e43fd109321ddcfad3a67b60423f0197c51a6))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.65.0 ([#29523](https://github.com/Koenkk/zigbee2mqtt/issues/29523)) ([8822aed](https://github.com/Koenkk/zigbee2mqtt/commit/8822aedb5e254f5be5f6cda0cfe18fc6f69c84d6))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.66.0 ([#29558](https://github.com/Koenkk/zigbee2mqtt/issues/29558)) ([940fff2](https://github.com/Koenkk/zigbee2mqtt/commit/940fff244c39da04d0de5d7e4076359dc6245aed))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.67.0 ([#29572](https://github.com/Koenkk/zigbee2mqtt/issues/29572)) ([4794b3c](https://github.com/Koenkk/zigbee2mqtt/commit/4794b3c81f9e38660f8549995b7f3ef8b4cd4318))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.68.0 ([#29606](https://github.com/Koenkk/zigbee2mqtt/issues/29606)) ([564e9ab](https://github.com/Koenkk/zigbee2mqtt/commit/564e9ab9eb49c3517913917af8b23d4758c6b6c7))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.69.0 ([#29659](https://github.com/Koenkk/zigbee2mqtt/issues/29659)) ([16d0e56](https://github.com/Koenkk/zigbee2mqtt/commit/16d0e5696859e79be4701154dd35f7780e47acae))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.70.0 ([#29684](https://github.com/Koenkk/zigbee2mqtt/issues/29684)) ([73225e2](https://github.com/Koenkk/zigbee2mqtt/commit/73225e2436bb56ff4ed47d787e8a1793fd10998d))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.71.0 ([#29716](https://github.com/Koenkk/zigbee2mqtt/issues/29716)) ([d6bf517](https://github.com/Koenkk/zigbee2mqtt/commit/d6bf5174be905128432e90d54b3c43c2a68e75ac))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.72.0 ([#29735](https://github.com/Koenkk/zigbee2mqtt/issues/29735)) ([7b7b988](https://github.com/Koenkk/zigbee2mqtt/commit/7b7b9889607a6e48001ae3cda5950386c24f5fd6))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.73.0 ([#29752](https://github.com/Koenkk/zigbee2mqtt/issues/29752)) ([be774a4](https://github.com/Koenkk/zigbee2mqtt/commit/be774a4d0d70122ced0f6ca79f49c060a7d2d2cb))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.74.0 ([#29770](https://github.com/Koenkk/zigbee2mqtt/issues/29770)) ([ba77ce7](https://github.com/Koenkk/zigbee2mqtt/commit/ba77ce7c8df0b29845a090c9defb4ce8aaf0f924))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.75.0 ([#29811](https://github.com/Koenkk/zigbee2mqtt/issues/29811)) ([854df49](https://github.com/Koenkk/zigbee2mqtt/commit/854df498bd3c8999393b683052dfba6b906ba669))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.76.0 ([#29823](https://github.com/Koenkk/zigbee2mqtt/issues/29823)) ([72d862f](https://github.com/Koenkk/zigbee2mqtt/commit/72d862f4a080bfcd91bf99d4c13387e719dfdb8e))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.77.0 ([#29838](https://github.com/Koenkk/zigbee2mqtt/issues/29838)) ([35d8a5d](https://github.com/Koenkk/zigbee2mqtt/commit/35d8a5da7f1d817727f8b029da1992901f5b4115))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.78.0 ([#29856](https://github.com/Koenkk/zigbee2mqtt/issues/29856)) ([49b4876](https://github.com/Koenkk/zigbee2mqtt/commit/49b4876768c5d15fcff1ad0c9c2d02dda96543d0))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.79.0 ([#29903](https://github.com/Koenkk/zigbee2mqtt/issues/29903)) ([d411fc5](https://github.com/Koenkk/zigbee2mqtt/commit/d411fc5c693300863a19c2798f0a7a05cfc7e55f))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.80.0 ([#29924](https://github.com/Koenkk/zigbee2mqtt/issues/29924)) ([445890a](https://github.com/Koenkk/zigbee2mqtt/commit/445890a0710ba7f6b101b651bf379f10390f9e7e))
|
||||
* **ignore:** update zigbee2mqtt-windfront to 2.3.1 ([#29788](https://github.com/Koenkk/zigbee2mqtt/issues/29788)) ([17520f7](https://github.com/Koenkk/zigbee2mqtt/commit/17520f7cfb69b577ebd986b86da80931a15a39db))
|
||||
* Reporting payload detection fixes ([#29854](https://github.com/Koenkk/zigbee2mqtt/issues/29854)) ([42fc6e0](https://github.com/Koenkk/zigbee2mqtt/commit/42fc6e03a7a3092502e3c3d1defbcb3ed6438230))
|
||||
|
||||
## [2.6.3](https://github.com/Koenkk/zigbee2mqtt/compare/2.6.2...2.6.3) (2025-11-01)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Add pi cooling demand to Home Assistant auto discovery ([#28843](https://github.com/Koenkk/zigbee2mqtt/issues/28843)) ([09fd675](https://github.com/Koenkk/zigbee2mqtt/commit/09fd675d0f215af11e64515ea60b91ed28b5e683))
|
||||
* Fix `onEvent` called twice first time when device options are changed ([#29322](https://github.com/Koenkk/zigbee2mqtt/issues/29322)) ([e037a2c](https://github.com/Koenkk/zigbee2mqtt/commit/e037a2c21cb985b6e71d9c1fa169f0886e8af832))
|
||||
* Fix input onboarding environment variable disabled check ([#29354](https://github.com/Koenkk/zigbee2mqtt/issues/29354)) ([c306300](https://github.com/Koenkk/zigbee2mqtt/commit/c30630091d1ac14fed6df9c5ee43a275db877821))
|
||||
* Home Assistant: fix device and group configuration URL ([#29211](https://github.com/Koenkk/zigbee2mqtt/issues/29211)) ([c0190c1](https://github.com/Koenkk/zigbee2mqtt/commit/c0190c18ede7accb407b805f6016c3242c11146a))
|
||||
* Home Assistant: make PI heating demand from writable ([#29188](https://github.com/Koenkk/zigbee2mqtt/issues/29188)) ([174ba64](https://github.com/Koenkk/zigbee2mqtt/commit/174ba64449b04777d1d5743fbb7b498a29c40ae2))
|
||||
* **ignore:** bump @types/node from 24.7.2 to 24.8.1 in the minor-patch group ([#29191](https://github.com/Koenkk/zigbee2mqtt/issues/29191)) ([d8fc69d](https://github.com/Koenkk/zigbee2mqtt/commit/d8fc69dac3cba33f3d69e377e338e03facbc19e7))
|
||||
* **ignore:** bump @types/serve-static from 1.15.10 to 2.2.0 ([#29394](https://github.com/Koenkk/zigbee2mqtt/issues/29394)) ([b2c31f8](https://github.com/Koenkk/zigbee2mqtt/commit/b2c31f89c69cfe04d0d671235bd18eb3cfa7ed72))
|
||||
* **ignore:** bump the minor-patch group across 1 directory with 4 updates ([#29395](https://github.com/Koenkk/zigbee2mqtt/issues/29395)) ([dc7749b](https://github.com/Koenkk/zigbee2mqtt/commit/dc7749b57e188835f1243fad4b1d9dcccd7dca7d))
|
||||
* **ignore:** bump the minor-patch group with 3 updates ([#29068](https://github.com/Koenkk/zigbee2mqtt/issues/29068)) ([aa916ad](https://github.com/Koenkk/zigbee2mqtt/commit/aa916ad60451fea471217e65fbdbb38635879c8e))
|
||||
* **ignore:** bump the minor-patch group with 4 updates ([#28916](https://github.com/Koenkk/zigbee2mqtt/issues/28916)) ([e24ec79](https://github.com/Koenkk/zigbee2mqtt/commit/e24ec79980535d62b02e849359e23a189f2255ed))
|
||||
* **ignore:** bump the minor-patch group with 5 updates ([#29314](https://github.com/Koenkk/zigbee2mqtt/issues/29314)) ([82f1092](https://github.com/Koenkk/zigbee2mqtt/commit/82f10923027806f5cd3b31e27184883e07768c71))
|
||||
* **ignore:** update zigbee-herdsman to 6.2.0 ([#28900](https://github.com/Koenkk/zigbee2mqtt/issues/28900)) ([8b4a4be](https://github.com/Koenkk/zigbee2mqtt/commit/8b4a4be2a4404a8b165bb62c43bca73894d6b13f))
|
||||
* **ignore:** update zigbee-herdsman to 6.3.0 ([#29113](https://github.com/Koenkk/zigbee2mqtt/issues/29113)) ([354d06a](https://github.com/Koenkk/zigbee2mqtt/commit/354d06aebc8fc786309ce9d66403e335799d46ab))
|
||||
* **ignore:** update zigbee-herdsman to 6.3.1 ([#29153](https://github.com/Koenkk/zigbee2mqtt/issues/29153)) ([feac6aa](https://github.com/Koenkk/zigbee2mqtt/commit/feac6aa677cb169bf3c9b47aa4e6687ea8e6432d))
|
||||
* **ignore:** update zigbee-herdsman to 6.3.2 ([#29246](https://github.com/Koenkk/zigbee2mqtt/issues/29246)) ([ef15924](https://github.com/Koenkk/zigbee2mqtt/commit/ef15924260cf2aa0094f2f93db0ddd8fcfa0ac6f))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.36.0 ([#28790](https://github.com/Koenkk/zigbee2mqtt/issues/28790)) ([ca489da](https://github.com/Koenkk/zigbee2mqtt/commit/ca489daad8def2683f4a5c248e8098d01cc7cc6f))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.37.0 ([#28837](https://github.com/Koenkk/zigbee2mqtt/issues/28837)) ([d1ce146](https://github.com/Koenkk/zigbee2mqtt/commit/d1ce1465421f81a68e03ffe76e928e2ea33cdde0))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.37.1 ([#28857](https://github.com/Koenkk/zigbee2mqtt/issues/28857)) ([c66008b](https://github.com/Koenkk/zigbee2mqtt/commit/c66008b36bccdc1626a7f095f1af498b100610e3))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.37.2 ([#28859](https://github.com/Koenkk/zigbee2mqtt/issues/28859)) ([1d38da6](https://github.com/Koenkk/zigbee2mqtt/commit/1d38da6ac5ac6a54c1c13a09003545f9accbfa7a))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.38.0 ([#28872](https://github.com/Koenkk/zigbee2mqtt/issues/28872)) ([a75a40b](https://github.com/Koenkk/zigbee2mqtt/commit/a75a40b042c8276e2b52c666b555fae4f656fa04))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.39.0 ([#28899](https://github.com/Koenkk/zigbee2mqtt/issues/28899)) ([548f646](https://github.com/Koenkk/zigbee2mqtt/commit/548f646f2fc1f53e18f84aec817f845de8edb04d))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.40.0 ([#28928](https://github.com/Koenkk/zigbee2mqtt/issues/28928)) ([5f08c3e](https://github.com/Koenkk/zigbee2mqtt/commit/5f08c3e83beaa98f6e5cf5fd32e106730e86f611))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.41.0 ([#28945](https://github.com/Koenkk/zigbee2mqtt/issues/28945)) ([79a27e3](https://github.com/Koenkk/zigbee2mqtt/commit/79a27e3b060dd552110a1851252dd6a17524be9b))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.42.0 ([#28963](https://github.com/Koenkk/zigbee2mqtt/issues/28963)) ([8b1f5a5](https://github.com/Koenkk/zigbee2mqtt/commit/8b1f5a555c571990e9e895b285060872ba27402f))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.43.0 ([#29014](https://github.com/Koenkk/zigbee2mqtt/issues/29014)) ([9c19aa9](https://github.com/Koenkk/zigbee2mqtt/commit/9c19aa94948205489b50ac79063b2a065495a8a8))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.44.0 ([#29050](https://github.com/Koenkk/zigbee2mqtt/issues/29050)) ([bafc8e4](https://github.com/Koenkk/zigbee2mqtt/commit/bafc8e4284d9493388c8ad8497bb55781238c547))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.46.0 ([#29096](https://github.com/Koenkk/zigbee2mqtt/issues/29096)) ([ad9b114](https://github.com/Koenkk/zigbee2mqtt/commit/ad9b114b1af8225e8e1414ffa23b322271fb1694))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.47.0 ([#29130](https://github.com/Koenkk/zigbee2mqtt/issues/29130)) ([03a81c6](https://github.com/Koenkk/zigbee2mqtt/commit/03a81c6ab14d9ae7b2a9fdd7513dcbbe55cdc16c))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.48.0 ([#29141](https://github.com/Koenkk/zigbee2mqtt/issues/29141)) ([1d69715](https://github.com/Koenkk/zigbee2mqtt/commit/1d69715a5a75779509f81788a1541dd4c492ca9e))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.49.0 ([#29154](https://github.com/Koenkk/zigbee2mqtt/issues/29154)) ([3ecb0c5](https://github.com/Koenkk/zigbee2mqtt/commit/3ecb0c5e41b514bfb824926fc9cf19636ec68ff5))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.50.0 ([#29180](https://github.com/Koenkk/zigbee2mqtt/issues/29180)) ([df70f11](https://github.com/Koenkk/zigbee2mqtt/commit/df70f11a154e27208188432be453fac821f73597))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.51.0 ([#29195](https://github.com/Koenkk/zigbee2mqtt/issues/29195)) ([4080522](https://github.com/Koenkk/zigbee2mqtt/commit/408052282d9a28f46df33266112cf52dbc0f98c0))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.51.1 ([#29212](https://github.com/Koenkk/zigbee2mqtt/issues/29212)) ([238ea7c](https://github.com/Koenkk/zigbee2mqtt/commit/238ea7c4c8073cb0164281cc0cdec05a3212d6ad))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.52.0 ([#29247](https://github.com/Koenkk/zigbee2mqtt/issues/29247)) ([05382a9](https://github.com/Koenkk/zigbee2mqtt/commit/05382a969232d5c1a286ba1a85c6422d0a81a39f))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.53.0 ([#29266](https://github.com/Koenkk/zigbee2mqtt/issues/29266)) ([d719c1f](https://github.com/Koenkk/zigbee2mqtt/commit/d719c1f36848c08efaad3eda8e90fb5d61c4c657))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.54.0 ([#29306](https://github.com/Koenkk/zigbee2mqtt/issues/29306)) ([003c81b](https://github.com/Koenkk/zigbee2mqtt/commit/003c81b745be7f3262d6e778957aec6a9cf3a404))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.55.0 ([#29323](https://github.com/Koenkk/zigbee2mqtt/issues/29323)) ([592c256](https://github.com/Koenkk/zigbee2mqtt/commit/592c256f96cca5219eb8620422f3ebf73fba3c1e))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.56.0 ([#29338](https://github.com/Koenkk/zigbee2mqtt/issues/29338)) ([61d99b7](https://github.com/Koenkk/zigbee2mqtt/commit/61d99b7ece63af35055fabbd9c07d43b3cbc80f9))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.57.0 ([#29370](https://github.com/Koenkk/zigbee2mqtt/issues/29370)) ([faa65f7](https://github.com/Koenkk/zigbee2mqtt/commit/faa65f78a29f5738a83d6fd67dd749f7d02adb39))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.59.0 ([#29382](https://github.com/Koenkk/zigbee2mqtt/issues/29382)) ([40bf14b](https://github.com/Koenkk/zigbee2mqtt/commit/40bf14b93cb94292cce954916eba30f48d3170e2))
|
||||
* Remove Moment.js dependency ([#28797](https://github.com/Koenkk/zigbee2mqtt/issues/28797)) ([74335fb](https://github.com/Koenkk/zigbee2mqtt/commit/74335fbb686edd63e5965c50b6cfc853abd07717))
|
||||
* Rename `ZigBee` -> `Zigbee` ([#29131](https://github.com/Koenkk/zigbee2mqtt/issues/29131)) ([eaaed1f](https://github.com/Koenkk/zigbee2mqtt/commit/eaaed1fec79401cb0b15b6e4bb4ddfba7bcf3d39))
|
||||
* Require at least Node ^20.15.0 ([#29284](https://github.com/Koenkk/zigbee2mqtt/issues/29284)) ([8ac2f55](https://github.com/Koenkk/zigbee2mqtt/commit/8ac2f55d87c3bebbda31cf1e9f1806e98b78c114))
|
||||
* Require at least Node ^22.2.0 ([#29285](https://github.com/Koenkk/zigbee2mqtt/issues/29285)) ([6c48498](https://github.com/Koenkk/zigbee2mqtt/commit/6c48498e0d1cbf49ab5ccc4d7539c932ea92a22e))
|
||||
|
||||
## [2.6.2](https://github.com/Koenkk/zigbee2mqtt/compare/2.6.1...2.6.2) (2025-10-01)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Fix `DatabaseEntry with ID 'X' does not exist` when adding device to delete group ID ([#28583](https://github.com/Koenkk/zigbee2mqtt/issues/28583)) ([09f33b3](https://github.com/Koenkk/zigbee2mqtt/commit/09f33b31a940c72ecfd42586427f54b3567b097b))
|
||||
* Handle empty or null Home Assistant name in device settings ([#28364](https://github.com/Koenkk/zigbee2mqtt/issues/28364)) ([a5e1e8c](https://github.com/Koenkk/zigbee2mqtt/commit/a5e1e8c0c316f500cdc19d7c47b5156ed0b1e0f0))
|
||||
* HomeAssistant: add `default_entity_id` to discovery message ([#28560](https://github.com/Koenkk/zigbee2mqtt/issues/28560)) ([15e00ea](https://github.com/Koenkk/zigbee2mqtt/commit/15e00ea8a49cc26e6c359bb60fbec0e76499fbf1))
|
||||
* **ignore:** bump @types/node from 24.4.0 to 24.5.2 in the minor-patch group ([#28700](https://github.com/Koenkk/zigbee2mqtt/issues/28700)) ([e8847d1](https://github.com/Koenkk/zigbee2mqtt/commit/e8847d1a342d04cd2e82704518cfb23745010dd1))
|
||||
* **ignore:** bump the minor-patch group with 3 updates ([#28541](https://github.com/Koenkk/zigbee2mqtt/issues/28541)) ([86b4581](https://github.com/Koenkk/zigbee2mqtt/commit/86b458111b44a2e99f4abacaaadc4caf0d6b912c))
|
||||
* **ignore:** bump the minor-patch group with 3 updates ([#28638](https://github.com/Koenkk/zigbee2mqtt/issues/28638)) ([c3e1525](https://github.com/Koenkk/zigbee2mqtt/commit/c3e1525f60d577ff2669761516fcfb23b4ee1bb7))
|
||||
* **ignore:** bump the minor-patch group with 4 updates ([#28778](https://github.com/Koenkk/zigbee2mqtt/issues/28778)) ([c9d01f4](https://github.com/Koenkk/zigbee2mqtt/commit/c9d01f4118cdef2a54bae43b09edb5e54c4f3042))
|
||||
* **ignore:** bump zigbee2mqtt-windfront from 2.1.0 to 2.2.0 in the minor-patch group ([#28764](https://github.com/Koenkk/zigbee2mqtt/issues/28764)) ([1166341](https://github.com/Koenkk/zigbee2mqtt/commit/116634193a0c7693c6431ceccb373cf5e3f99e40))
|
||||
* **ignore:** update zigbee-herdsman to 6.1.0 ([#28460](https://github.com/Koenkk/zigbee2mqtt/issues/28460)) ([06862c7](https://github.com/Koenkk/zigbee2mqtt/commit/06862c72594abf083411cf517c8dfb3db12fd4a9))
|
||||
* **ignore:** update zigbee-herdsman to 6.1.1 ([#28597](https://github.com/Koenkk/zigbee2mqtt/issues/28597)) ([c28ca79](https://github.com/Koenkk/zigbee2mqtt/commit/c28ca79d8a8d5264c3e53f1d1eb96ce5dce1f90e))
|
||||
* **ignore:** update zigbee-herdsman to 6.1.2 ([#28689](https://github.com/Koenkk/zigbee2mqtt/issues/28689)) ([79c0c09](https://github.com/Koenkk/zigbee2mqtt/commit/79c0c0933ab2500ae4d5bd42dea57923729f8d86))
|
||||
* **ignore:** update zigbee-herdsman to 6.1.3 ([#28717](https://github.com/Koenkk/zigbee2mqtt/issues/28717)) ([892f924](https://github.com/Koenkk/zigbee2mqtt/commit/892f92448e256acd59d329cde4b7519d18cd829a))
|
||||
* **ignore:** update zigbee-herdsman to 6.1.4 ([#28762](https://github.com/Koenkk/zigbee2mqtt/issues/28762)) ([508318d](https://github.com/Koenkk/zigbee2mqtt/commit/508318de57267791422d731fcb9a423fa01c8062))
|
||||
* **ignore:** update zigbee-herdsman to 6.1.5 ([#28773](https://github.com/Koenkk/zigbee2mqtt/issues/28773)) ([a0d91cc](https://github.com/Koenkk/zigbee2mqtt/commit/a0d91cc063437cc595dd693e33fe5b1f044cd6bf))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.15.0 ([#28462](https://github.com/Koenkk/zigbee2mqtt/issues/28462)) ([3f27f79](https://github.com/Koenkk/zigbee2mqtt/commit/3f27f79d7dabd1951c9c1f2f3dfc24d6bc741edd))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.17.0 ([#28480](https://github.com/Koenkk/zigbee2mqtt/issues/28480)) ([3018e40](https://github.com/Koenkk/zigbee2mqtt/commit/3018e40daef092d74de4eea9e2cb8f174899cd71))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.17.1 ([#28511](https://github.com/Koenkk/zigbee2mqtt/issues/28511)) ([54d729e](https://github.com/Koenkk/zigbee2mqtt/commit/54d729e37a80b0d7a22b67b6223e28685cbf1974))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.18.0 ([#28518](https://github.com/Koenkk/zigbee2mqtt/issues/28518)) ([e8e4977](https://github.com/Koenkk/zigbee2mqtt/commit/e8e4977327c147f6338d323662823dd3316d54a3))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.19.0 ([#28533](https://github.com/Koenkk/zigbee2mqtt/issues/28533)) ([5f2630c](https://github.com/Koenkk/zigbee2mqtt/commit/5f2630c93b8541eafbb737c6eb134155ae2fa6f5))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.20.0 ([#28545](https://github.com/Koenkk/zigbee2mqtt/issues/28545)) ([a297b92](https://github.com/Koenkk/zigbee2mqtt/commit/a297b9255b961d19c0164f6dc29fcaf3cc10aab6))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.21.0 ([#28561](https://github.com/Koenkk/zigbee2mqtt/issues/28561)) ([01d5863](https://github.com/Koenkk/zigbee2mqtt/commit/01d5863487322729fed61da167b6754289d26919))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.22.0 ([#28580](https://github.com/Koenkk/zigbee2mqtt/issues/28580)) ([5f6fae0](https://github.com/Koenkk/zigbee2mqtt/commit/5f6fae0df729b8fafa4d8835ba48dc5e25578330))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.23.0 ([#28598](https://github.com/Koenkk/zigbee2mqtt/issues/28598)) ([3f25834](https://github.com/Koenkk/zigbee2mqtt/commit/3f258342d8acd2cd4f69902679735dee2a7e0e01))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.24.0 ([#28608](https://github.com/Koenkk/zigbee2mqtt/issues/28608)) ([2edf85f](https://github.com/Koenkk/zigbee2mqtt/commit/2edf85f6e1c8b0a42eacfd38a4fd4a43875e86d1))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.25.0 ([#28621](https://github.com/Koenkk/zigbee2mqtt/issues/28621)) ([b2f7460](https://github.com/Koenkk/zigbee2mqtt/commit/b2f74607cc32d17df12fc7361b9bab7eafebf5bd))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.26.0 ([#28629](https://github.com/Koenkk/zigbee2mqtt/issues/28629)) ([2cb7dcc](https://github.com/Koenkk/zigbee2mqtt/commit/2cb7dcc12ab00dbc966717ab70b5f8ad8a86012e))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.29.0 ([#28654](https://github.com/Koenkk/zigbee2mqtt/issues/28654)) ([382d37e](https://github.com/Koenkk/zigbee2mqtt/commit/382d37e839bad69c02c6a560b32964b03305ac67))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.30.0 ([#28707](https://github.com/Koenkk/zigbee2mqtt/issues/28707)) ([77926bc](https://github.com/Koenkk/zigbee2mqtt/commit/77926bc1c31a86bf2ded7838216a59380f3bde1e))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.31.0 ([#28726](https://github.com/Koenkk/zigbee2mqtt/issues/28726)) ([a310627](https://github.com/Koenkk/zigbee2mqtt/commit/a310627e19fb0f684be407d7d54bf90ff112041a))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.32.0 ([#28746](https://github.com/Koenkk/zigbee2mqtt/issues/28746)) ([87c474d](https://github.com/Koenkk/zigbee2mqtt/commit/87c474d2f5433f74fda122a42d4ffa16c64b3a00))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.33.0 ([#28758](https://github.com/Koenkk/zigbee2mqtt/issues/28758)) ([26c74b5](https://github.com/Koenkk/zigbee2mqtt/commit/26c74b57786e0feffe5d1bb3ae7406e25449a591))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.34.0 ([#28763](https://github.com/Koenkk/zigbee2mqtt/issues/28763)) ([f6c0ce7](https://github.com/Koenkk/zigbee2mqtt/commit/f6c0ce735ff582e8d07a11f951a1faa9720367c1))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.35.1 ([#28774](https://github.com/Koenkk/zigbee2mqtt/issues/28774)) ([1283859](https://github.com/Koenkk/zigbee2mqtt/commit/1283859a12d09ed1b7ea2605acbf2293adc80df0))
|
||||
* **ignore:** update zigbee2mqtt-frontend to 0.9.21 ([#28745](https://github.com/Koenkk/zigbee2mqtt/issues/28745)) ([2c70deb](https://github.com/Koenkk/zigbee2mqtt/commit/2c70deb411fbf670f14b7c5457e96d21f7203822))
|
||||
* **ignore:** update zigbee2mqtt-windfront to 2.1.0 ([#28471](https://github.com/Koenkk/zigbee2mqtt/issues/28471)) ([e52203a](https://github.com/Koenkk/zigbee2mqtt/commit/e52203a1b8b543820506780981de997e6e7edeff))
|
||||
* Make windfront the default frontend ([#28546](https://github.com/Koenkk/zigbee2mqtt/issues/28546)) ([fefae99](https://github.com/Koenkk/zigbee2mqtt/commit/fefae9957c9d35bc2cfa1264cb23c4731d21a64a))
|
||||
|
||||
## [2.6.1](https://github.com/Koenkk/zigbee2mqtt/compare/2.6.0...2.6.1) (2025-09-01)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Always unlink `node_modules` symlinks on stop ([#28202](https://github.com/Koenkk/zigbee2mqtt/issues/28202)) ([63a4207](https://github.com/Koenkk/zigbee2mqtt/commit/63a4207061039e4dab50f5f999febe4d87397856))
|
||||
* Home Assistant: set icon and state class for orientation sensors ([#28192](https://github.com/Koenkk/zigbee2mqtt/issues/28192)) ([b7cbd9b](https://github.com/Koenkk/zigbee2mqtt/commit/b7cbd9b5d830fc1b936208076c440bc561552220))
|
||||
* Home Assistant: use "occupancy" device_class for human presence sensors ([#28329](https://github.com/Koenkk/zigbee2mqtt/issues/28329)) ([ccfab84](https://github.com/Koenkk/zigbee2mqtt/commit/ccfab84e7f93be151e841834943d8a65500fe5d9))
|
||||
* **ignore:** bump the minor-patch group with 2 updates ([#28383](https://github.com/Koenkk/zigbee2mqtt/issues/28383)) ([a8fd23b](https://github.com/Koenkk/zigbee2mqtt/commit/a8fd23b6cc97468f345216913ebb6c8f27e83789))
|
||||
* **ignore:** bump the minor-patch group with 4 updates ([#28147](https://github.com/Koenkk/zigbee2mqtt/issues/28147)) ([b72abd6](https://github.com/Koenkk/zigbee2mqtt/commit/b72abd675f409fca324b34936c1bfb6f3d8aefd4))
|
||||
* **ignore:** bump the minor-patch group with 5 updates ([#28237](https://github.com/Koenkk/zigbee2mqtt/issues/28237)) ([1dd6cc3](https://github.com/Koenkk/zigbee2mqtt/commit/1dd6cc3da54527eb5560c7edec7e56324ef38ea1))
|
||||
* **ignore:** update zigbee-herdsman to 6.0.0 ([#28235](https://github.com/Koenkk/zigbee2mqtt/issues/28235)) ([bd1be88](https://github.com/Koenkk/zigbee2mqtt/commit/bd1be886022ac13bb71828fc773df0f8f144ec8a))
|
||||
* **ignore:** update zigbee-herdsman to 6.0.1 ([#28287](https://github.com/Koenkk/zigbee2mqtt/issues/28287)) ([bed8bec](https://github.com/Koenkk/zigbee2mqtt/commit/bed8beccbc54c06430bdd97bcfb8d14158756216))
|
||||
* **ignore:** update zigbee-herdsman to 6.0.2 ([#28406](https://github.com/Koenkk/zigbee2mqtt/issues/28406)) ([264440e](https://github.com/Koenkk/zigbee2mqtt/commit/264440ebcc7c86fb6f2fbacd76a3b1bc451f01ad))
|
||||
* **ignore:** update zigbee-herdsman to 6.0.4 ([#28438](https://github.com/Koenkk/zigbee2mqtt/issues/28438)) ([7788653](https://github.com/Koenkk/zigbee2mqtt/commit/77886530fe8c6599cfa1a1a797743fc07cdee75c))
|
||||
* **ignore:** update zigbee-herdsman-converters to 24.12.0 ([#28170](https://github.com/Koenkk/zigbee2mqtt/issues/28170)) ([9836f0e](https://github.com/Koenkk/zigbee2mqtt/commit/9836f0e27a57863bdbd98f9770ea37036ccf243c))
|
||||
* **ignore:** update zigbee-herdsman-converters to 24.13.0 ([#28175](https://github.com/Koenkk/zigbee2mqtt/issues/28175)) ([2056b89](https://github.com/Koenkk/zigbee2mqtt/commit/2056b89baca9018254e23b02fbf0a5250314159b))
|
||||
* **ignore:** update zigbee-herdsman-converters to 24.14.0 ([#28199](https://github.com/Koenkk/zigbee2mqtt/issues/28199)) ([09f046c](https://github.com/Koenkk/zigbee2mqtt/commit/09f046c72d309ad4270e404376bcf009b3411b00))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.0.0 ([#28236](https://github.com/Koenkk/zigbee2mqtt/issues/28236)) ([3160219](https://github.com/Koenkk/zigbee2mqtt/commit/3160219824bcb12c4cbff232d2b7ec5c5a73317b))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.1.0 ([#28264](https://github.com/Koenkk/zigbee2mqtt/issues/28264)) ([2b17808](https://github.com/Koenkk/zigbee2mqtt/commit/2b1780879a62c8f1a044be7f2a525517f8af4082))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.10.0 ([#28399](https://github.com/Koenkk/zigbee2mqtt/issues/28399)) ([32d8265](https://github.com/Koenkk/zigbee2mqtt/commit/32d82651e233665e1850d86d7f8a30a1cdead507))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.11.0 ([#28407](https://github.com/Koenkk/zigbee2mqtt/issues/28407)) ([c07fce9](https://github.com/Koenkk/zigbee2mqtt/commit/c07fce936f8bbbfe6405938221c426ba8dd5eff2))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.12.0 ([#28417](https://github.com/Koenkk/zigbee2mqtt/issues/28417)) ([bdeab61](https://github.com/Koenkk/zigbee2mqtt/commit/bdeab6100195a129980cf9d0151d6eb1b849a802))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.13.0 ([#28427](https://github.com/Koenkk/zigbee2mqtt/issues/28427)) ([203019a](https://github.com/Koenkk/zigbee2mqtt/commit/203019aa26e3ee028e68d1ef9b4d032624fd7991))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.14.0 ([#28439](https://github.com/Koenkk/zigbee2mqtt/issues/28439)) ([bf22dda](https://github.com/Koenkk/zigbee2mqtt/commit/bf22ddac466db6523b659b422a36c968700c385f))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.2.0 ([#28280](https://github.com/Koenkk/zigbee2mqtt/issues/28280)) ([4c97842](https://github.com/Koenkk/zigbee2mqtt/commit/4c9784255bab79d7d8a394135bfd6f5b9e40ef9b))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.3.0 ([#28301](https://github.com/Koenkk/zigbee2mqtt/issues/28301)) ([5f7c005](https://github.com/Koenkk/zigbee2mqtt/commit/5f7c00515adc8941c51b6ede219529719949a9bf))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.4.0 ([#28313](https://github.com/Koenkk/zigbee2mqtt/issues/28313)) ([384bd30](https://github.com/Koenkk/zigbee2mqtt/commit/384bd309a6d980ba1555a7dcfe13539df67699a1))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.5.0 ([#28328](https://github.com/Koenkk/zigbee2mqtt/issues/28328)) ([23f831a](https://github.com/Koenkk/zigbee2mqtt/commit/23f831a1feae67aacd5b76ac81bf3c857065f5d3))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.6.0 ([#28344](https://github.com/Koenkk/zigbee2mqtt/issues/28344)) ([4bd0c04](https://github.com/Koenkk/zigbee2mqtt/commit/4bd0c04bdcdf22e08e152d52f3f5d9a565d8f5f7))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.7.0 ([#28361](https://github.com/Koenkk/zigbee2mqtt/issues/28361)) ([7bd7bce](https://github.com/Koenkk/zigbee2mqtt/commit/7bd7bce69c4065d94a809baef80966ee07691efc))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.8.0 ([#28373](https://github.com/Koenkk/zigbee2mqtt/issues/28373)) ([8e6ba79](https://github.com/Koenkk/zigbee2mqtt/commit/8e6ba7975b292b4ba0817de8b7877fb7b9892aed))
|
||||
* **ignore:** update zigbee-herdsman-converters to 25.9.0 ([#28380](https://github.com/Koenkk/zigbee2mqtt/issues/28380)) ([0147441](https://github.com/Koenkk/zigbee2mqtt/commit/0147441c935a4a77f4fccdb59499672de64fabd5))
|
||||
* **ignore:** update zigbee2mqtt-frontend to 0.9.20 ([#28250](https://github.com/Koenkk/zigbee2mqtt/issues/28250)) ([800b85c](https://github.com/Koenkk/zigbee2mqtt/commit/800b85c812e57e982a689554b64cbe73aee4f192))
|
||||
* **ignore:** update zigbee2mqtt-windfront to 1.6.0 ([#28207](https://github.com/Koenkk/zigbee2mqtt/issues/28207)) ([092c95b](https://github.com/Koenkk/zigbee2mqtt/commit/092c95b7169d7e23c30db154988fb50d4099d750))
|
||||
* **ignore:** update zigbee2mqtt-windfront to 1.8.0 ([#28266](https://github.com/Koenkk/zigbee2mqtt/issues/28266)) ([f4cfcba](https://github.com/Koenkk/zigbee2mqtt/commit/f4cfcbacde8cab83e0a7ea742f39f87c2bceb1e1))
|
||||
* **ignore:** update zigbee2mqtt-windfront to 1.8.1 ([#28272](https://github.com/Koenkk/zigbee2mqtt/issues/28272)) ([d04ab53](https://github.com/Koenkk/zigbee2mqtt/commit/d04ab53f1d584aed400ab8fd0bcd985f78611cb5))
|
||||
* **ignore:** update zigbee2mqtt-windfront to 2.0.1 ([#28420](https://github.com/Koenkk/zigbee2mqtt/issues/28420)) ([08903f6](https://github.com/Koenkk/zigbee2mqtt/commit/08903f68d9a9e20994a1da2eb4835ad28ca68877))
|
||||
* Remove 60 MB (28%) of dev dependencies from Docker image ([#28160](https://github.com/Koenkk/zigbee2mqtt/issues/28160)) ([050ebfc](https://github.com/Koenkk/zigbee2mqtt/commit/050ebfc9f5dd5a2de07f5402d3c99ac8ab3b12b4))
|
||||
* Set minimum for some settings ([#28209](https://github.com/Koenkk/zigbee2mqtt/issues/28209)) ([a102fac](https://github.com/Koenkk/zigbee2mqtt/commit/a102fac2c8ab09a126fddfb0cc7170d57bf114c0))
|
||||
* Support for new ZH typing ([#28257](https://github.com/Koenkk/zigbee2mqtt/issues/28257)) ([b21f926](https://github.com/Koenkk/zigbee2mqtt/commit/b21f926b3e152176d09dc7f95fbc02b2b5ec13da))
|
||||
* Update to refactored zhc api and fix `onEvent(stop)` not being called when device is force removed ([#27984](https://github.com/Koenkk/zigbee2mqtt/issues/27984)) ([5286570](https://github.com/Koenkk/zigbee2mqtt/commit/5286570bd625a714fad432dd693308caf59344de))
|
||||
* update zigbee2mqtt-windfront to 2.0.0 ([#28389](https://github.com/Koenkk/zigbee2mqtt/issues/28389)) ([2df363f](https://github.com/Koenkk/zigbee2mqtt/commit/2df363f3af8f13c5fde91bab7ac276de3be7ee44))
|
||||
|
||||
## [2.6.0](https://github.com/Koenkk/zigbee2mqtt/compare/2.5.1...2.6.0) (2025-08-01)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* Allow to disable internal frontend UI serving for standalone serving ([#27851](https://github.com/Koenkk/zigbee2mqtt/issues/27851)) ([0215e76](https://github.com/Koenkk/zigbee2mqtt/commit/0215e76118c8dcbe77c1ed4890846aaf7da85bae))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* erroneous Health OS memory percent calculation ([#27892](https://github.com/Koenkk/zigbee2mqtt/issues/27892)) ([190cfe9](https://github.com/Koenkk/zigbee2mqtt/commit/190cfe99ac62b9dc6db4dc59a4389afda85e8177))
|
||||
* Exit with code 2 when adapters disconnects ([#28013](https://github.com/Koenkk/zigbee2mqtt/issues/28013)) ([0e0a561](https://github.com/Koenkk/zigbee2mqtt/commit/0e0a5618af9a1b5707ddccbca2cde983cafb40b5))
|
||||
* Fix settings schema defaults ([#27961](https://github.com/Koenkk/zigbee2mqtt/issues/27961)) ([ecadda4](https://github.com/Koenkk/zigbee2mqtt/commit/ecadda45e7c5665f9e242c956f5f140b7caa6eed))
|
||||
* Ignore symbolic links in `data` during backup ([#28132](https://github.com/Koenkk/zigbee2mqtt/issues/28132)) ([0182c4b](https://github.com/Koenkk/zigbee2mqtt/commit/0182c4b32efafc85d1f4a38840345944501feaef))
|
||||
* **ignore:** add test to specifically check HA envs ([#27969](https://github.com/Koenkk/zigbee2mqtt/issues/27969)) ([833605b](https://github.com/Koenkk/zigbee2mqtt/commit/833605b71f110b4e7aeb6632694820cdd1110e25))
|
||||
* **ignore:** bump the minor-patch group with 2 updates ([#27924](https://github.com/Koenkk/zigbee2mqtt/issues/27924)) ([8ceb087](https://github.com/Koenkk/zigbee2mqtt/commit/8ceb08704f7e5d637b661c745c804beebf38eed9))
|
||||
* **ignore:** bump the minor-patch group with 4 updates ([#28046](https://github.com/Koenkk/zigbee2mqtt/issues/28046)) ([e505a93](https://github.com/Koenkk/zigbee2mqtt/commit/e505a93a4036affe9e531b24e29ee543ed4cb0f5))
|
||||
* **ignore:** fix 71cf2b41603a9923024c0472ffc1f7bfe3d14fc7 ([6dd812f](https://github.com/Koenkk/zigbee2mqtt/commit/6dd812f71cf9ca6737777c3d4acfab35c52a76b8))
|
||||
* **ignore:** fix breaking changes of https://github.com/Koenkk/zigbee2mqtt/pull/28077 ([713551b](https://github.com/Koenkk/zigbee2mqtt/commit/713551b5257f8624ed03f7901f0addf6864faf1f))
|
||||
* **ignore:** Remove retain/qos from mqtt publish logging https://github.com/Koenkk/zigbee2mqtt/pull/27983 ([e2b7df9](https://github.com/Koenkk/zigbee2mqtt/commit/e2b7df9f84550aa413f3453bb97a13ba2eee4187))
|
||||
* **ignore:** update zigbee-herdsman to 4.3.2 ([#27900](https://github.com/Koenkk/zigbee2mqtt/issues/27900)) ([4afdd4e](https://github.com/Koenkk/zigbee2mqtt/commit/4afdd4e89241eddeb27e5f6c1c7b6604ce4a41cb))
|
||||
* **ignore:** update zigbee-herdsman to 4.4.0 ([#27906](https://github.com/Koenkk/zigbee2mqtt/issues/27906)) ([e663e86](https://github.com/Koenkk/zigbee2mqtt/commit/e663e86e09cf86078877407e2233447468d66899))
|
||||
* **ignore:** update zigbee-herdsman to 4.4.1 ([#27918](https://github.com/Koenkk/zigbee2mqtt/issues/27918)) ([eb82973](https://github.com/Koenkk/zigbee2mqtt/commit/eb829730678dad354d3feede2155f142d58a140f))
|
||||
* **ignore:** update zigbee-herdsman to 4.5.0 ([#28044](https://github.com/Koenkk/zigbee2mqtt/issues/28044)) ([cc6f7b0](https://github.com/Koenkk/zigbee2mqtt/commit/cc6f7b02bc2d7548f142ec162696eae06027d6a3))
|
||||
* **ignore:** update zigbee-herdsman to 5.0.0 ([#28077](https://github.com/Koenkk/zigbee2mqtt/issues/28077)) ([9a215ef](https://github.com/Koenkk/zigbee2mqtt/commit/9a215efe26be6fafde0f0a779b651ded860cd90c))
|
||||
* **ignore:** update zigbee-herdsman to 5.0.1 ([#28080](https://github.com/Koenkk/zigbee2mqtt/issues/28080)) ([6432571](https://github.com/Koenkk/zigbee2mqtt/commit/6432571c61b6e2d4bcc17cc952eeacdaf72213f6))
|
||||
* **ignore:** update zigbee-herdsman to 5.0.2 ([#28110](https://github.com/Koenkk/zigbee2mqtt/issues/28110)) ([e9f2a3f](https://github.com/Koenkk/zigbee2mqtt/commit/e9f2a3f5326954f361199bd4d73ed944f72f6ebe))
|
||||
* **ignore:** update zigbee-herdsman to 5.0.3 ([#28121](https://github.com/Koenkk/zigbee2mqtt/issues/28121)) ([e5f677b](https://github.com/Koenkk/zigbee2mqtt/commit/e5f677bdd1cc3df4d05dd1f8164220ae2258f081))
|
||||
* **ignore:** update zigbee-herdsman to 5.0.4 ([#28141](https://github.com/Koenkk/zigbee2mqtt/issues/28141)) ([9fcc41b](https://github.com/Koenkk/zigbee2mqtt/commit/9fcc41b199082e47d96de4cad996c55c39da83a5))
|
||||
* **ignore:** update zigbee-herdsman-converters to 23.70.0 ([#27905](https://github.com/Koenkk/zigbee2mqtt/issues/27905)) ([163a15d](https://github.com/Koenkk/zigbee2mqtt/commit/163a15d664432631f100814927647b918563d85b))
|
||||
* **ignore:** update zigbee-herdsman-converters to 23.70.1 ([#27916](https://github.com/Koenkk/zigbee2mqtt/issues/27916)) ([e047324](https://github.com/Koenkk/zigbee2mqtt/commit/e04732462c218cd42c2b617aefba37a5f61d1ce6))
|
||||
* **ignore:** update zigbee-herdsman-converters to 23.71.0 ([#27931](https://github.com/Koenkk/zigbee2mqtt/issues/27931)) ([93c1824](https://github.com/Koenkk/zigbee2mqtt/commit/93c1824b1d81c997f0e5a445acac421300f55758))
|
||||
* **ignore:** update zigbee-herdsman-converters to 23.72.0 ([#27943](https://github.com/Koenkk/zigbee2mqtt/issues/27943)) ([b4a9424](https://github.com/Koenkk/zigbee2mqtt/commit/b4a9424d604c47609071ef33e88ee55a55a6c8d5))
|
||||
* **ignore:** update zigbee-herdsman-converters to 24.0.0 ([#27946](https://github.com/Koenkk/zigbee2mqtt/issues/27946)) ([c465ef8](https://github.com/Koenkk/zigbee2mqtt/commit/c465ef83526c434cac6555836d82e7707072b754))
|
||||
* **ignore:** update zigbee-herdsman-converters to 24.1.0 ([#27973](https://github.com/Koenkk/zigbee2mqtt/issues/27973)) ([a837702](https://github.com/Koenkk/zigbee2mqtt/commit/a837702b2c1f517dcfa3a0f578d9b5b3700b171d))
|
||||
* **ignore:** update zigbee-herdsman-converters to 24.10.0 ([#28122](https://github.com/Koenkk/zigbee2mqtt/issues/28122)) ([ee1c884](https://github.com/Koenkk/zigbee2mqtt/commit/ee1c884031fdef516393ce68754a9dbcc8ad093d))
|
||||
* **ignore:** update zigbee-herdsman-converters to 24.11.0 ([#28143](https://github.com/Koenkk/zigbee2mqtt/issues/28143)) ([3765549](https://github.com/Koenkk/zigbee2mqtt/commit/376554943d15c45a15d30713002d825286204581))
|
||||
* **ignore:** update zigbee-herdsman-converters to 24.2.0 ([#27986](https://github.com/Koenkk/zigbee2mqtt/issues/27986)) ([6ede403](https://github.com/Koenkk/zigbee2mqtt/commit/6ede4036886066bf91953b13714a16ba96217b6d))
|
||||
* **ignore:** update zigbee-herdsman-converters to 24.3.0 ([#28015](https://github.com/Koenkk/zigbee2mqtt/issues/28015)) ([21fa5cb](https://github.com/Koenkk/zigbee2mqtt/commit/21fa5cbdeddb51d55364c4d28b887791384a951b))
|
||||
* **ignore:** update zigbee-herdsman-converters to 24.4.0 ([#28022](https://github.com/Koenkk/zigbee2mqtt/issues/28022)) ([74e9357](https://github.com/Koenkk/zigbee2mqtt/commit/74e9357a5989c6b1eeb25aa91c0da27b7b54fa67))
|
||||
* **ignore:** update zigbee-herdsman-converters to 24.5.0 ([#28045](https://github.com/Koenkk/zigbee2mqtt/issues/28045)) ([bc74d0b](https://github.com/Koenkk/zigbee2mqtt/commit/bc74d0b11b58bb2cb2bcc07f5ae9c47b1ca7a13e))
|
||||
* **ignore:** update zigbee-herdsman-converters to 24.6.0 ([#28051](https://github.com/Koenkk/zigbee2mqtt/issues/28051)) ([4bc6a59](https://github.com/Koenkk/zigbee2mqtt/commit/4bc6a59ff38f9a102259afbff2606a75409042a3))
|
||||
* **ignore:** update zigbee-herdsman-converters to 24.7.0 ([#28070](https://github.com/Koenkk/zigbee2mqtt/issues/28070)) ([81bafa5](https://github.com/Koenkk/zigbee2mqtt/commit/81bafa55201d6d7a34b364a85c19423a56eceeee))
|
||||
* **ignore:** update zigbee-herdsman-converters to 24.8.0 ([#28081](https://github.com/Koenkk/zigbee2mqtt/issues/28081)) ([caf91cd](https://github.com/Koenkk/zigbee2mqtt/commit/caf91cd7ffb8ae4961c3f43875f051b182f1a379))
|
||||
* **ignore:** update zigbee-herdsman-converters to 24.9.0 ([71cf2b4](https://github.com/Koenkk/zigbee2mqtt/commit/71cf2b41603a9923024c0472ffc1f7bfe3d14fc7))
|
||||
* **ignore:** update zigbee2mqtt-frontend to 0.9.17 ([#27917](https://github.com/Koenkk/zigbee2mqtt/issues/27917)) ([a3e7f69](https://github.com/Koenkk/zigbee2mqtt/commit/a3e7f69b3ff6173a59b4d5e2ad1f09c2c414b416))
|
||||
* **ignore:** update zigbee2mqtt-frontend to 0.9.19 ([#28021](https://github.com/Koenkk/zigbee2mqtt/issues/28021)) ([8b87682](https://github.com/Koenkk/zigbee2mqtt/commit/8b876823da7fbde4f980fefa54cec7c3fa52c423))
|
||||
* **ignore:** update zigbee2mqtt-windfront to 1.3.0 ([#27953](https://github.com/Koenkk/zigbee2mqtt/issues/27953)) ([1b37bae](https://github.com/Koenkk/zigbee2mqtt/commit/1b37baefd3e6817fc9dbf36c9ec9e8aec4481643))
|
||||
* **ignore:** update zigbee2mqtt-windfront to 1.3.1 ([#27999](https://github.com/Koenkk/zigbee2mqtt/issues/27999)) ([a51216e](https://github.com/Koenkk/zigbee2mqtt/commit/a51216e3c76335b66a9383b1734a213ad948d70a))
|
||||
* **ignore:** update zigbee2mqtt-windfront to 1.4.1 ([#28062](https://github.com/Koenkk/zigbee2mqtt/issues/28062)) ([d322dc2](https://github.com/Koenkk/zigbee2mqtt/commit/d322dc20479faffa8f923e2190c1a5f82d17d5e4))
|
||||
* **ignore:** update zigbee2mqtt-windfront to 1.5.0 ([#28082](https://github.com/Koenkk/zigbee2mqtt/issues/28082)) ([29e56ad](https://github.com/Koenkk/zigbee2mqtt/commit/29e56adc159268038727d955135d3edbedbaae8b))
|
||||
* **ignore:** update zigbee2mqtt-windfront to 1.5.1 ([#28123](https://github.com/Koenkk/zigbee2mqtt/issues/28123)) ([31d3e19](https://github.com/Koenkk/zigbee2mqtt/commit/31d3e19f3862b067555bcbc9bbcd3a5ded6df211))
|
||||
* **ignore:** update zigbee2mqtt-windfront to 1.5.2 ([#28140](https://github.com/Koenkk/zigbee2mqtt/issues/28140)) ([fe5639c](https://github.com/Koenkk/zigbee2mqtt/commit/fe5639ce40cf0a4035cd996a558c952dc065fcd0))
|
||||
* Improve startup settings validation ([#27988](https://github.com/Koenkk/zigbee2mqtt/issues/27988)) ([435a6cc](https://github.com/Koenkk/zigbee2mqtt/commit/435a6cceb9aea1ac6941c99603d7785ef91e274a))
|
||||
* log error message when external JS fails to load ([#27837](https://github.com/Koenkk/zigbee2mqtt/issues/27837)) ([f4d821d](https://github.com/Koenkk/zigbee2mqtt/commit/f4d821deca71540f830f38f631d1a3759c1d0f40))
|
||||
* Publish definition source in `bridge/devices` ([#28076](https://github.com/Koenkk/zigbee2mqtt/issues/28076)) ([65eef1b](https://github.com/Koenkk/zigbee2mqtt/commit/65eef1b6900afdf831c809047ab68e93df59b4b0))
|
||||
* Publish endpoint names in `bridge/devices` ([#28057](https://github.com/Koenkk/zigbee2mqtt/issues/28057)) ([5f9019a](https://github.com/Koenkk/zigbee2mqtt/commit/5f9019a95fb460f1dc4a31d09e2424ff56049c14))
|
||||
* Set MQTT retain and qos=1 on (re)connect ([#27983](https://github.com/Koenkk/zigbee2mqtt/issues/27983)) ([ef07505](https://github.com/Koenkk/zigbee2mqtt/commit/ef07505b31782936a3ae517688c7e1eb9e541daf))
|
||||
* Various fixes to align behaviors (+add benchmarks for dev) ([#28011](https://github.com/Koenkk/zigbee2mqtt/issues/28011)) ([db20369](https://github.com/Koenkk/zigbee2mqtt/commit/db203694477ff718386a3d97ca260dccd0dc0597))
|
||||
|
||||
## [2.5.1](https://github.com/Koenkk/zigbee2mqtt/compare/2.5.0...2.5.1) (2025-07-02)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **ignore:** update zigbee-herdsman to 4.3.1 ([#27878](https://github.com/Koenkk/zigbee2mqtt/issues/27878)) ([917d852](https://github.com/Koenkk/zigbee2mqtt/commit/917d8527a5efcf349153ed71e8a44b6d6c87b398))
|
||||
* Various Windfront frontend improvements [@nerivec](https://github.com/nerivec) ([#27880](https://github.com/Koenkk/zigbee2mqtt/issues/27880)) ([4dd7dab](https://github.com/Koenkk/zigbee2mqtt/commit/4dd7dabf0803e3cad6e9b6aa1683a2ea8984fb0e))
|
||||
|
||||
## [2.5.0](https://github.com/Koenkk/zigbee2mqtt/compare/2.4.0...2.5.0) (2025-07-01)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* New health extension & extras in `bridge/info` ([#27164](https://github.com/Koenkk/zigbee2mqtt/issues/27164)) ([cd9b752](https://github.com/Koenkk/zigbee2mqtt/commit/cd9b752ede91db1d02c567dded92c4e52c05b88d))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Bump Alpine to 3.22 ([#27690](https://github.com/Koenkk/zigbee2mqtt/issues/27690)) ([f6c3887](https://github.com/Koenkk/zigbee2mqtt/commit/f6c3887c812ea6e15e950e6d55e0274356f2eea5))
|
||||
* Fix devices not immediately marked as offline when timeout expires ([#27691](https://github.com/Koenkk/zigbee2mqtt/issues/27691)) ([e4b253e](https://github.com/Koenkk/zigbee2mqtt/commit/e4b253e08beb147367872aa4517df93a03ef1a4f))
|
||||
* Generate group ID if empty string given ([#27702](https://github.com/Koenkk/zigbee2mqtt/issues/27702)) ([0e66b29](https://github.com/Koenkk/zigbee2mqtt/commit/0e66b29983ae691a2dab44f6649e20a9e00a43cd))
|
||||
* **ignore:** API correctness ([#27637](https://github.com/Koenkk/zigbee2mqtt/issues/27637)) ([018fad2](https://github.com/Koenkk/zigbee2mqtt/commit/018fad27afb5861b1d9c7adff3161c926ccbbaa4))
|
||||
* **ignore:** bump @types/node from 22.15.30 to 24.0.3 ([#27745](https://github.com/Koenkk/zigbee2mqtt/issues/27745)) ([de80045](https://github.com/Koenkk/zigbee2mqtt/commit/de800450ad31e5d8ad5c342b061dc3c59f0d565e))
|
||||
* **ignore:** bump the minor-patch group across 1 directory with 4 updates ([#27858](https://github.com/Koenkk/zigbee2mqtt/issues/27858)) ([c8dc26b](https://github.com/Koenkk/zigbee2mqtt/commit/c8dc26b241ae6562271d56fe59a13f05927b2bb4))
|
||||
* **ignore:** bump the minor-patch group with 2 updates ([#27797](https://github.com/Koenkk/zigbee2mqtt/issues/27797)) ([50b0ffd](https://github.com/Koenkk/zigbee2mqtt/commit/50b0ffd7e7ef343fec983a62d2268feda28b01ba))
|
||||
* **ignore:** bump the minor-patch group with 3 updates ([#27598](https://github.com/Koenkk/zigbee2mqtt/issues/27598)) ([7e82a3d](https://github.com/Koenkk/zigbee2mqtt/commit/7e82a3d1e960d4fa2d89558b6d6a20534e7d6ecf))
|
||||
* **ignore:** bump the minor-patch group with 4 updates ([#27610](https://github.com/Koenkk/zigbee2mqtt/issues/27610)) ([ac80bb6](https://github.com/Koenkk/zigbee2mqtt/commit/ac80bb6430007e494c544089af323c3fb99c3541))
|
||||
* **ignore:** bump the minor-patch group with 6 updates ([#27678](https://github.com/Koenkk/zigbee2mqtt/issues/27678)) ([587a02f](https://github.com/Koenkk/zigbee2mqtt/commit/587a02f66319688cb93df82fde02539bce0263ea))
|
||||
* **ignore:** bump zigbee2mqtt-windfront from 1.0.5 to 1.0.6 in the minor-patch group ([#27744](https://github.com/Koenkk/zigbee2mqtt/issues/27744)) ([9776729](https://github.com/Koenkk/zigbee2mqtt/commit/977672976f06f644ed6e02e4a17c07b63873c8da))
|
||||
* **ignore:** Migrate to Biome 2 ([#27785](https://github.com/Koenkk/zigbee2mqtt/issues/27785)) ([c87d452](https://github.com/Koenkk/zigbee2mqtt/commit/c87d4524d599302a0728b85799c9bf7c0784a8f4))
|
||||
* **ignore:** update zigbee-herdsman to 4.1.1 ([#27640](https://github.com/Koenkk/zigbee2mqtt/issues/27640)) ([4b95b54](https://github.com/Koenkk/zigbee2mqtt/commit/4b95b54be7abc53a7f7a83814994f9cdde90134e))
|
||||
* **ignore:** update zigbee-herdsman to 4.1.2 ([#27729](https://github.com/Koenkk/zigbee2mqtt/issues/27729)) ([242815e](https://github.com/Koenkk/zigbee2mqtt/commit/242815e1390e9e3a5ded929e8bfc4a9a4329a526))
|
||||
* **ignore:** update zigbee-herdsman to 4.2.0 ([#27786](https://github.com/Koenkk/zigbee2mqtt/issues/27786)) ([15f3eaf](https://github.com/Koenkk/zigbee2mqtt/commit/15f3eaf96629caa5fbd7e02ae002883becc1b49f))
|
||||
* **ignore:** update zigbee-herdsman to 4.2.1 ([#27835](https://github.com/Koenkk/zigbee2mqtt/issues/27835)) ([16faef1](https://github.com/Koenkk/zigbee2mqtt/commit/16faef1511e9bfb1cf76c5faaa1008e195ef67fc))
|
||||
* **ignore:** update zigbee-herdsman to 4.3.0 ([#27853](https://github.com/Koenkk/zigbee2mqtt/issues/27853)) ([50c7d2d](https://github.com/Koenkk/zigbee2mqtt/commit/50c7d2d6adb9c9366d5c7f829003c84a140f7a19))
|
||||
* **ignore:** update zigbee-herdsman-converters to 23.54.0 ([#27600](https://github.com/Koenkk/zigbee2mqtt/issues/27600)) ([1765fe8](https://github.com/Koenkk/zigbee2mqtt/commit/1765fe8925e359b917c1e2e08d3691d4c8bdcf3f))
|
||||
* **ignore:** update zigbee-herdsman-converters to 23.55.0 ([#27618](https://github.com/Koenkk/zigbee2mqtt/issues/27618)) ([4594142](https://github.com/Koenkk/zigbee2mqtt/commit/4594142c09ee8d19af2d32238ffa58512694d2ed))
|
||||
* **ignore:** update zigbee-herdsman-converters to 23.56.0 ([#27639](https://github.com/Koenkk/zigbee2mqtt/issues/27639)) ([f637e7d](https://github.com/Koenkk/zigbee2mqtt/commit/f637e7d59cc71f32b8d04e8f4bfc414027e7d23a))
|
||||
* **ignore:** update zigbee-herdsman-converters to 23.57.0 ([#27646](https://github.com/Koenkk/zigbee2mqtt/issues/27646)) ([252bfba](https://github.com/Koenkk/zigbee2mqtt/commit/252bfbaa20beccd315592dac811cb23309cdee01))
|
||||
* **ignore:** update zigbee-herdsman-converters to 23.57.1 ([#27689](https://github.com/Koenkk/zigbee2mqtt/issues/27689)) ([56d3a8f](https://github.com/Koenkk/zigbee2mqtt/commit/56d3a8f9d8bc01e30a6e469b517545d3406941e2))
|
||||
* **ignore:** update zigbee-herdsman-converters to 23.58.0 ([#27695](https://github.com/Koenkk/zigbee2mqtt/issues/27695)) ([6a8d208](https://github.com/Koenkk/zigbee2mqtt/commit/6a8d20858ede85de72c34ce58e9df41fa2e91d0d))
|
||||
* **ignore:** update zigbee-herdsman-converters to 23.59.0 ([#27712](https://github.com/Koenkk/zigbee2mqtt/issues/27712)) ([87ff0f3](https://github.com/Koenkk/zigbee2mqtt/commit/87ff0f3711e043eb47319e9fb8abcdfa878d9868))
|
||||
* **ignore:** update zigbee-herdsman-converters to 23.60.0 ([#27752](https://github.com/Koenkk/zigbee2mqtt/issues/27752)) ([f33d360](https://github.com/Koenkk/zigbee2mqtt/commit/f33d3606be9e916989d08c7d418c4505dcbfe4ea))
|
||||
* **ignore:** update zigbee-herdsman-converters to 23.61.0 ([#27759](https://github.com/Koenkk/zigbee2mqtt/issues/27759)) ([b537f9a](https://github.com/Koenkk/zigbee2mqtt/commit/b537f9a93a61095b6b0b82d04d85f7e264aec27c))
|
||||
* **ignore:** update zigbee-herdsman-converters to 23.62.0 ([#27767](https://github.com/Koenkk/zigbee2mqtt/issues/27767)) ([281e10c](https://github.com/Koenkk/zigbee2mqtt/commit/281e10c15fa09358e999f1f6b506fe9b08295608))
|
||||
* **ignore:** update zigbee-herdsman-converters to 23.63.0 ([#27784](https://github.com/Koenkk/zigbee2mqtt/issues/27784)) ([0d5de75](https://github.com/Koenkk/zigbee2mqtt/commit/0d5de750ffed0674c5a23c2c4d8d1e954c602197))
|
||||
* **ignore:** update zigbee-herdsman-converters to 23.64.0 ([#27799](https://github.com/Koenkk/zigbee2mqtt/issues/27799)) ([b7d9c78](https://github.com/Koenkk/zigbee2mqtt/commit/b7d9c78309a8c3e3cf551948b6542d2b71b70697))
|
||||
* **ignore:** update zigbee-herdsman-converters to 23.65.0 ([#27804](https://github.com/Koenkk/zigbee2mqtt/issues/27804)) ([4190ba4](https://github.com/Koenkk/zigbee2mqtt/commit/4190ba43b43e1f688e246f9236bfe7c60230a927))
|
||||
* **ignore:** update zigbee-herdsman-converters to 23.66.0 ([#27831](https://github.com/Koenkk/zigbee2mqtt/issues/27831)) ([33234d9](https://github.com/Koenkk/zigbee2mqtt/commit/33234d9ce45323a2a10b7839c5f7aebc84a9cc32))
|
||||
* **ignore:** update zigbee-herdsman-converters to 23.67.0 ([#27842](https://github.com/Koenkk/zigbee2mqtt/issues/27842)) ([6930fa6](https://github.com/Koenkk/zigbee2mqtt/commit/6930fa6f3fce8f415302c8db32294b1a9d0ea333))
|
||||
* **ignore:** update zigbee-herdsman-converters to 23.68.0 ([#27852](https://github.com/Koenkk/zigbee2mqtt/issues/27852)) ([3ccbaf2](https://github.com/Koenkk/zigbee2mqtt/commit/3ccbaf21d227b7c4ad7952522a980a9083f06463))
|
||||
* **ignore:** update zigbee-herdsman-converters to 23.69.0 ([#27860](https://github.com/Koenkk/zigbee2mqtt/issues/27860)) ([5285b7b](https://github.com/Koenkk/zigbee2mqtt/commit/5285b7b95e3c977cca14d28444b9f4f2a9d8996c))
|
||||
* **ignore:** update zigbee2mqtt-frontend to 0.9.14 ([#27645](https://github.com/Koenkk/zigbee2mqtt/issues/27645)) ([66e1318](https://github.com/Koenkk/zigbee2mqtt/commit/66e1318a79502cb723cf88d888c9ac23daeb7fd8))
|
||||
* **ignore:** update zigbee2mqtt-frontend to 0.9.15 ([#27711](https://github.com/Koenkk/zigbee2mqtt/issues/27711)) ([8ecb9be](https://github.com/Koenkk/zigbee2mqtt/commit/8ecb9be98efb44db23f386e05509389c7d681025))
|
||||
* **ignore:** update zigbee2mqtt-frontend to 0.9.16 ([#27783](https://github.com/Koenkk/zigbee2mqtt/issues/27783)) ([7109900](https://github.com/Koenkk/zigbee2mqtt/commit/7109900bcfeff48fdea48456455cd1c6cebf380a))
|
||||
* **ignore:** update zigbee2mqtt-windfront to 1.0.5 ([#27656](https://github.com/Koenkk/zigbee2mqtt/issues/27656)) ([eaa3e45](https://github.com/Koenkk/zigbee2mqtt/commit/eaa3e458b5a8a9c5ebf31e12ae7e68fcf60f762f))
|
||||
* **ignore:** update zigbee2mqtt-windfront to 1.1.0 ([#27763](https://github.com/Koenkk/zigbee2mqtt/issues/27763)) ([cdad6cc](https://github.com/Koenkk/zigbee2mqtt/commit/cdad6ccd75200061ded795af032f0fed0bb21484))
|
||||
* Rename fix typo in backoff settings https://github.com/Koenkk/zigbee2mqtt/issues/27642 ([0181263](https://github.com/Koenkk/zigbee2mqtt/commit/0181263d32dd1099676ed92226a3fc2ee6ac701e))
|
||||
* update zigbee2mqtt-windfront to 1.0.4 ([#27641](https://github.com/Koenkk/zigbee2mqtt/issues/27641)) ([9a4ce6f](https://github.com/Koenkk/zigbee2mqtt/commit/9a4ce6fcd0fce6fea9c195ff48a41096b738dccb))
|
||||
|
||||
## [2.4.0](https://github.com/Koenkk/zigbee2mqtt/compare/2.3.0...2.4.0) (2025-06-01)
|
||||
|
||||
|
||||
@@ -123,7 +445,7 @@
|
||||
|
||||
* Frontend: support filtering notifications ([#26805](https://github.com/Koenkk/zigbee2mqtt/issues/26805)) ([f872a51](https://github.com/Koenkk/zigbee2mqtt/commit/f872a5180c5618b7d3e7c0d11f1283a454dcbc6b))
|
||||
* Onboarding ([#26608](https://github.com/Koenkk/zigbee2mqtt/issues/26608)) ([05d6f08](https://github.com/Koenkk/zigbee2mqtt/commit/05d6f08a0dd6a5097b7d19b8de3b39e37e9a8533))
|
||||
* Support ZigBee on Host adapter ([#26742](https://github.com/Koenkk/zigbee2mqtt/issues/26742)) ([92955c0](https://github.com/Koenkk/zigbee2mqtt/commit/92955c02a4de09cbed79249db8bf0e6529423b93))
|
||||
* Support Zigbee on Host adapter ([#26742](https://github.com/Koenkk/zigbee2mqtt/issues/26742)) ([92955c0](https://github.com/Koenkk/zigbee2mqtt/commit/92955c02a4de09cbed79249db8bf0e6529423b93))
|
||||
* Use dynamic import for external JS ([#26522](https://github.com/Koenkk/zigbee2mqtt/issues/26522)) ([badf107](https://github.com/Koenkk/zigbee2mqtt/commit/badf1079919baa06f160a42c34e9f742a9b584c9))
|
||||
|
||||
|
||||
|
||||
+1
-1
@@ -4,5 +4,5 @@ Everybody is invited and welcome to contribute to Zigbee2MQTT. Zigbee2MQTT is wr
|
||||
|
||||
- Pull requests are always created against the [**dev**](https://github.com/Koenkk/zigbee2mqtt/tree/dev) branch.
|
||||
- Easiest way to start developing Zigbee2MQTT is by setting up a development environment (aka bare-metal installation). You can follow this [guide](https://www.zigbee2mqtt.io/guide/installation/01_linux.html) to do this.
|
||||
- You can run the tests locally by executing `pnpm test`. Zigbee2MQTT enforces 100% code coverage, in case you add new code check if your code is covered by running `pnpm run test-with-coverage`. The coverage report can be found under `coverage/lcov-report/index.html`. Linting is also enforced and can be run with `pnpm run eslint`.
|
||||
- You can run the tests locally by executing `pnpm test`. Zigbee2MQTT enforces 100% code coverage, in case you add new code check if your code is covered by running `pnpm run test:coverage`. The coverage report can be found under `coverage/lcov-report/index.html`. Linting is also enforced and can be run with `pnpm run eslint`.
|
||||
- When you want to add support for a new device no changes to Zigbee2MQTT have to be made, only to zigbee-herdsman-converters. You can find a guide for it [here](https://www.zigbee2mqtt.io/advanced/support-new-devices/01_support_new_devices.html).
|
||||
|
||||
@@ -5,33 +5,27 @@
|
||||
<br>
|
||||
<br>
|
||||
<div style="display: flex;">
|
||||
<a href="https://github.com/Koenkk/zigbee2mqtt/actions?query=workflow%3Aci">
|
||||
<img src="https://github.com/koenkk/zigbee2mqtt/workflows/ci/badge.svg">
|
||||
</a>
|
||||
<a href="https://github.com/Koenkk/zigbee2mqtt/releases">
|
||||
<img src="https://img.shields.io/github/release/koenkk/zigbee2mqtt.svg">
|
||||
</a>
|
||||
<a href="https://www.npmjs.com/package/zigbee2mqtt">
|
||||
<img src="https://img.shields.io/npm/v/zigbee2mqtt">
|
||||
</a>
|
||||
<a href="https://github.com/Koenkk/zigbee2mqtt/actions/workflows/ci.yml">
|
||||
<img src="https://github.com/Koenkk/zigbee2mqtt/actions/workflows/ci.yml/badge.svg">
|
||||
</a>
|
||||
<a href="https://github.com/Koenkk/zigbee2mqtt/actions/workflows/github-code-scanning/codeql">
|
||||
<img src="https://github.com/Koenkk/zigbee2mqtt/actions/workflows/github-code-scanning/codeql/badge.svg">
|
||||
</a>
|
||||
<a href="https://discord.gg/dadfWYE">
|
||||
<img src="https://img.shields.io/discord/556563650429583360.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&utm_medium=referral&utm_content=Koenkk/zigbee2mqtt&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>
|
||||
@@ -52,59 +46,67 @@ If you aren't familiar with **Zigbee** terminology make sure you [read this](htt
|
||||
|
||||
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/)
|
||||
|
||||
- [Home Assistant OS](https://www.home-assistant.io/installation/): Using [the official addon](https://github.com/zigbee2mqtt/hassio-zigbee2mqtt)
|
||||
- Other installation: using instructions [here](https://www.zigbee2mqtt.io/guide/usage/integrations/home_assistant.html)
|
||||
<img align="left" height="75px" width="75px" src="https://user-images.githubusercontent.com/7738048/40914297-49e6e560-6800-11e8-8904-36cce896e5a8.png">
|
||||
|
||||
<br>
|
||||
<br clear="right">
|
||||
|
||||
<img align="left" height="100px" width="100px" src="https://etc.athom.com/logo/white/256.png">
|
||||
[Home Assistant OS](https://www.home-assistant.io/installation/) using [the official addon](https://github.com/zigbee2mqtt/hassio-zigbee2mqtt) ([other installations](https://www.zigbee2mqtt.io/guide/usage/integrations/home_assistant.html))
|
||||
|
||||
<br clear="both">
|
||||
|
||||
### [Homey](https://homey.app/)
|
||||
|
||||
- Integration implemented in the [Homey App](https://homey.app/nl-nl/app/com.gruijter.zigbee2mqtt/)
|
||||
- Documentation and support in the [Homey Forum](https://community.homey.app/t/83214)
|
||||
<img align="left" height="75px" width="75px" src="https://etc.athom.com/logo/white/256.png">
|
||||
|
||||
<br>
|
||||
<br clear="right">
|
||||
|
||||
<img align="left" height="100px" width="100px" src="https://user-images.githubusercontent.com/2734836/47615848-b8dd8700-dabd-11e8-9d77-175002dd8987.png">
|
||||
Integration implemented in the [Homey App](https://homey.app/nl-nl/app/com.gruijter.zigbee2mqtt/) ([documentation & support](https://community.homey.app/t/83214))
|
||||
|
||||
<br clear="both">
|
||||
|
||||
### [Domoticz](https://www.domoticz.com/)
|
||||
|
||||
- Integration implemented in Domoticz ([documentation](https://www.domoticz.com/wiki/Zigbee2MQTT)).
|
||||
<img align="left" height="75px" width="75px" src="https://user-images.githubusercontent.com/2734836/47615848-b8dd8700-dabd-11e8-9d77-175002dd8987.png">
|
||||
|
||||
<br>
|
||||
<br clear="right">
|
||||
|
||||
<img align="left" height="100px" width="100px" src="./images/gladys-assistant-logo.jpg">
|
||||
Integration implemented in Domoticz ([documentation](https://www.domoticz.com/wiki/Zigbee2MQTT)).
|
||||
|
||||
<br clear="both">
|
||||
|
||||
### [Gladys Assistant](https://gladysassistant.com/)
|
||||
|
||||
- Integration implemented natively in Gladys Assistant ([documentation](https://gladysassistant.com/docs/integrations/zigbee2mqtt/)).
|
||||
<img align="left" height="75px" width="75px" src="./images/gladys-assistant-logo.jpg">
|
||||
|
||||
<br>
|
||||
<br clear="right">
|
||||
|
||||
<img align="left" height="100px" width="100px" src="https://forum.iobroker.net/assets/uploads/system/site-logo.png">
|
||||
Integration implemented natively in Gladys Assistant ([documentation](https://gladysassistant.com/docs/integrations/zigbee2mqtt/)).
|
||||
|
||||
<br clear="both">
|
||||
|
||||
### [IoBroker](https://www.iobroker.net/)
|
||||
|
||||
- Integration implemented in IoBroker ([documentation](https://github.com/o0shojo0o/ioBroker.zigbee2mqtt)).
|
||||
<img align="left" height="75px" width="75px" src="https://forum.iobroker.net/assets/uploads/system/site-logo.png">
|
||||
|
||||
<br>
|
||||
<br clear="right">
|
||||
|
||||
Integration implemented in IoBroker ([documentation](https://github.com/o0shojo0o/ioBroker.zigbee2mqtt)).
|
||||
|
||||
<br clear="both">
|
||||
|
||||
## Architecture
|
||||
|
||||

|
||||

|
||||
|
||||
### 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 and 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/blob/master/docs/07-5123-08-Zigbee-Cluster-Library.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. Zigbee2MQTT provides a [web-based interface](https://github.com/nurikk/zigbee2mqtt-frontend) that allows monitoring and configuration.
|
||||
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 adapter to handle Zigbee communication and 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/wiki/References#texas-instruments-zstack) to communicate with the adapter. 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/wiki/References#csa-zigbee-alliance-spec) 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. Zigbee2MQTT provides several web-based interfaces ([zigbee2mqtt-frontend](https://github.com/nurikk/zigbee2mqtt-frontend), [zigbee2mqtt-windfront](https://github.com/Nerivec/zigbee2mqtt-windfront)) that allows monitoring and configuration.
|
||||
|
||||
### Developing
|
||||
|
||||
Zigbee2MQTT uses TypeScript (partially for now). Therefore after making changes to files in the `lib/` directory you need to recompile Zigbee2MQTT. This can be done by executing `pnpm run build`. For faster development instead of running `pnpm run build` you can run `pnpm run build-watch` in another terminal session, this will recompile as you change files.
|
||||
Zigbee2MQTT uses TypeScript. Therefore after making changes to files in the `lib/` directory you need to recompile Zigbee2MQTT. This can be done by executing `pnpm run build`. For faster development instead of running `pnpm run build` you can run `pnpm run build:watch` in another terminal session, this will recompile as you change files.
|
||||
|
||||
Before running any of the commands, you'll first need to run `pnpm install --include=dev`.
|
||||
Before submitting changes run `pnpm run check:w` then `pnpm run test:coverage`.
|
||||
|
||||
+14
-5
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"$schema": "https://biomejs.dev/schemas/1.9.4/schema.json",
|
||||
"$schema": "https://biomejs.dev/schemas/2.3.8/schema.json",
|
||||
"vcs": {
|
||||
"enabled": true,
|
||||
"clientKind": "git",
|
||||
@@ -12,10 +12,10 @@
|
||||
"bracketSpacing": false
|
||||
},
|
||||
"files": {
|
||||
"ignore": ["package.json"]
|
||||
"includes": ["**", "!package.json"]
|
||||
},
|
||||
"linter": {
|
||||
"ignore": [],
|
||||
"includes": ["**"],
|
||||
"rules": {
|
||||
"correctness": {
|
||||
"noUnusedImports": "error"
|
||||
@@ -55,7 +55,16 @@
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"useAsConstAssertion": "error",
|
||||
"useDefaultParameterLast": "error",
|
||||
"useEnumInitializers": "error",
|
||||
"useSelfClosingElements": "error",
|
||||
"useSingleVarDeclarator": "error",
|
||||
"noUnusedTemplateLiteral": "error",
|
||||
"useNumberNamespace": "error",
|
||||
"noInferrableTypes": "error",
|
||||
"noUselessElse": "error"
|
||||
},
|
||||
"performance": {
|
||||
"noDelete": "off"
|
||||
@@ -68,7 +77,7 @@
|
||||
},
|
||||
"overrides": [
|
||||
{
|
||||
"include": ["test/**"],
|
||||
"includes": ["test/**"],
|
||||
"linter": {
|
||||
"rules": {
|
||||
"style": {
|
||||
|
||||
+16
-6
@@ -1,6 +1,6 @@
|
||||
ARG TARGETPLATFORM
|
||||
|
||||
FROM alpine:3.21 AS base
|
||||
FROM alpine:3.22 AS base
|
||||
|
||||
ENV NODE_ENV=production
|
||||
WORKDIR /app
|
||||
@@ -10,12 +10,19 @@ RUN apk add --no-cache tzdata eudev tini nodejs
|
||||
FROM base AS deps
|
||||
|
||||
COPY package.json pnpm-lock.yaml ./
|
||||
|
||||
# Make and such are needed to compile serialport for riscv64
|
||||
RUN apk add make gcc g++ python3 linux-headers npm && \
|
||||
npm install -g pnpm@10.4.1 && \
|
||||
pnpm install --frozen-lockfile --no-optional && \
|
||||
# serialport has outdated prebuilds that appear to fail on some archs, force build on target platform
|
||||
rm -rf `find ./node_modules/.pnpm/ -wholename "*/@serialport/bindings-cpp/prebuilds" -type d` && \
|
||||
# Install pnpm, configure a tmp-based store, then use it under a cache mount so each arch gets its own store
|
||||
# NOTE: We do not install devDependencies here (the --prod argument in pnpm install) as we use an already
|
||||
# built artifact (./dist directory) from previous GitHub runner stages. Omitting devDependencies here
|
||||
# saves storage as this node_modules/ is being copied straight to the release stage later.
|
||||
RUN --mount=type=cache,id=pnpm-store,target=/tmp/pnpm-store \
|
||||
apk add --no-cache make gcc g++ python3 linux-headers npm jq && \
|
||||
npm install -g $(jq -r '.packageManager' package.json) && \
|
||||
pnpm config set store-dir /tmp/pnpm-store && \
|
||||
pnpm install --frozen-lockfile --prod --no-optional && \
|
||||
# force serialport to rebuild on current platform instead of using prebuilds
|
||||
rm -rf $(find ./node_modules/.pnpm/ -wholename "*/@serialport/bindings-cpp/prebuilds" -type d) && \
|
||||
pnpm rebuild @serialport/bindings-cpp
|
||||
|
||||
# Release
|
||||
@@ -45,5 +52,8 @@ RUN mkdir /app/data
|
||||
ARG COMMIT
|
||||
RUN echo "$COMMIT" > dist/.hash
|
||||
|
||||
# Expose the default frontend port (see lib/util/settings.ts defaults.frontend.port)
|
||||
EXPOSE 8080
|
||||
|
||||
ENTRYPOINT ["docker-entrypoint.sh"]
|
||||
CMD [ "/sbin/tini", "--", "node", "index.js"]
|
||||
|
||||
File diff suppressed because one or more lines are too long
Binary file not shown.
|
After Width: | Height: | Size: 200 KiB |
+14
-16
@@ -1,21 +1,18 @@
|
||||
import type Extension from "./extension/extension";
|
||||
import type {Zigbee2MQTTAPI} from "./types/api";
|
||||
|
||||
import bind from "bind-decorator";
|
||||
import stringify from "json-stable-stringify-without-jsonify";
|
||||
|
||||
import {setLogger as zhSetLogger} from "zigbee-herdsman";
|
||||
import {setLogger as zhcSetLogger} from "zigbee-herdsman-converters";
|
||||
|
||||
import EventBus from "./eventBus";
|
||||
// Extensions
|
||||
import ExtensionAvailability from "./extension/availability";
|
||||
import ExtensionBind from "./extension/bind";
|
||||
import ExtensionBridge from "./extension/bridge";
|
||||
import ExtensionConfigure from "./extension/configure";
|
||||
import type Extension from "./extension/extension";
|
||||
import ExtensionExternalConverters from "./extension/externalConverters";
|
||||
import ExtensionExternalExtensions from "./extension/externalExtensions";
|
||||
import ExtensionGroups from "./extension/groups";
|
||||
import ExtensionHealth from "./extension/health";
|
||||
import ExtensionNetworkMap from "./extension/networkMap";
|
||||
import ExtensionOnEvent from "./extension/onEvent";
|
||||
import ExtensionOTAUpdate from "./extension/otaUpdate";
|
||||
@@ -23,6 +20,7 @@ import ExtensionPublish from "./extension/publish";
|
||||
import ExtensionReceive from "./extension/receive";
|
||||
import Mqtt, {type MqttPublishOptions} from "./mqtt";
|
||||
import State from "./state";
|
||||
import type {Zigbee2MQTTAPI} from "./types/api";
|
||||
import logger from "./util/logger";
|
||||
import {initSdNotify} from "./util/sd-notify";
|
||||
import * as settings from "./util/settings";
|
||||
@@ -30,10 +28,10 @@ import utils from "./util/utils";
|
||||
import Zigbee from "./zigbee";
|
||||
|
||||
export class Controller {
|
||||
private eventBus: EventBus;
|
||||
private zigbee: Zigbee;
|
||||
private state: State;
|
||||
private mqtt: Mqtt;
|
||||
public readonly eventBus: EventBus;
|
||||
public readonly zigbee: Zigbee;
|
||||
public readonly state: State;
|
||||
public readonly mqtt: Mqtt;
|
||||
private restartCallback: () => Promise<void>;
|
||||
private exitCallback: (code: number, restart: boolean) => Promise<void>;
|
||||
public readonly extensions: Set<Extension>;
|
||||
@@ -76,6 +74,7 @@ export class Controller {
|
||||
new ExtensionOTAUpdate(...this.extensionArgs),
|
||||
new ExtensionExternalExtensions(...this.extensionArgs),
|
||||
new ExtensionAvailability(...this.extensionArgs),
|
||||
new ExtensionHealth(...this.extensionArgs),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -282,17 +281,16 @@ export class Controller {
|
||||
}
|
||||
}
|
||||
|
||||
async stop(restart = false): Promise<void> {
|
||||
async stop(restart = false, code = 0): Promise<void> {
|
||||
this.sdNotify?.notifyStopping();
|
||||
|
||||
let code = 0;
|
||||
|
||||
let localCode = 0;
|
||||
for (const extension of this.extensions) {
|
||||
try {
|
||||
await extension.stop();
|
||||
} catch (error) {
|
||||
logger.error(`Failed to stop '${extension.constructor.name}' (${(error as Error).stack})`);
|
||||
code = 1;
|
||||
localCode = 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -307,11 +305,11 @@ export class Controller {
|
||||
logger.info("Stopped Zigbee2MQTT");
|
||||
} catch (error) {
|
||||
logger.error(`Failed to stop Zigbee2MQTT (${(error as Error).stack})`);
|
||||
code = 1;
|
||||
localCode = 1;
|
||||
}
|
||||
|
||||
this.sdNotify?.stop();
|
||||
return await this.exit(code, restart);
|
||||
return await this.exit(code !== 0 ? code : localCode, restart);
|
||||
}
|
||||
|
||||
async exit(code: number, restart = false): Promise<void> {
|
||||
@@ -321,7 +319,7 @@ export class Controller {
|
||||
|
||||
@bind async onZigbeeAdapterDisconnected(): Promise<void> {
|
||||
logger.error("Adapter disconnected, stopping");
|
||||
await this.stop();
|
||||
await this.stop(false, 2);
|
||||
}
|
||||
|
||||
@bind async publishEntityState(entity: Group | Device, payload: KeyValue, stateChangeReason?: StateChangeReason): Promise<void> {
|
||||
|
||||
+54
-6
@@ -8,8 +8,8 @@ interface EventBusMap {
|
||||
adapterDisconnected: [];
|
||||
permitJoinChanged: [data: eventdata.PermitJoinChanged];
|
||||
publishAvailability: [];
|
||||
deviceRenamed: [data: eventdata.EntityRenamed];
|
||||
deviceRemoved: [data: eventdata.EntityRemoved];
|
||||
entityRenamed: [data: eventdata.EntityRenamed];
|
||||
entityRemoved: [data: eventdata.EntityRemoved];
|
||||
lastSeenChanged: [data: eventdata.LastSeenChanged];
|
||||
deviceNetworkAddressChanged: [data: eventdata.DeviceNetworkAddressChanged];
|
||||
deviceAnnounce: [data: eventdata.DeviceAnnounce];
|
||||
@@ -34,9 +34,25 @@ type EventBusListener<K> = K extends keyof EventBusMap
|
||||
: never
|
||||
: never;
|
||||
|
||||
type Stats = {
|
||||
devices: Map<
|
||||
string, // IEEE address
|
||||
{
|
||||
lastSeenChanges?: {messages: number; first: number};
|
||||
leaveCounts: number;
|
||||
networkAddressChanges: number;
|
||||
}
|
||||
>;
|
||||
mqtt: {
|
||||
published: number;
|
||||
received: number;
|
||||
};
|
||||
};
|
||||
|
||||
export default class EventBus {
|
||||
private callbacksByExtension = new Map<string, {event: keyof EventBusMap; callback: EventBusListener<keyof EventBusMap>}[]>();
|
||||
private emitter = new events.EventEmitter<EventBusMap>();
|
||||
readonly stats: Stats = {devices: new Map(), mqtt: {published: 0, received: 0}};
|
||||
|
||||
constructor() {
|
||||
this.emitter.setMaxListeners(100);
|
||||
@@ -57,21 +73,33 @@ export default class EventBus {
|
||||
}
|
||||
|
||||
public emitEntityRenamed(data: eventdata.EntityRenamed): void {
|
||||
this.emitter.emit("deviceRenamed", data);
|
||||
this.emitter.emit("entityRenamed", data);
|
||||
}
|
||||
public onEntityRenamed(key: ListenerKey, callback: (data: eventdata.EntityRenamed) => void): void {
|
||||
this.on("deviceRenamed", callback, key);
|
||||
this.on("entityRenamed", callback, key);
|
||||
}
|
||||
|
||||
public emitEntityRemoved(data: eventdata.EntityRemoved): void {
|
||||
this.emitter.emit("deviceRemoved", data);
|
||||
this.emitter.emit("entityRemoved", data);
|
||||
}
|
||||
public onEntityRemoved(key: ListenerKey, callback: (data: eventdata.EntityRemoved) => void): void {
|
||||
this.on("deviceRemoved", callback, key);
|
||||
this.on("entityRemoved", callback, key);
|
||||
}
|
||||
|
||||
public emitLastSeenChanged(data: eventdata.LastSeenChanged): void {
|
||||
this.emitter.emit("lastSeenChanged", data);
|
||||
|
||||
const device = this.stats.devices.get(data.device.ieeeAddr);
|
||||
|
||||
if (device?.lastSeenChanges) {
|
||||
device.lastSeenChanges.messages += 1;
|
||||
} else {
|
||||
this.stats.devices.set(data.device.ieeeAddr, {
|
||||
lastSeenChanges: {messages: 1, first: Date.now()},
|
||||
leaveCounts: 0,
|
||||
networkAddressChanges: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
public onLastSeenChanged(key: ListenerKey, callback: (data: eventdata.LastSeenChanged) => void): void {
|
||||
this.on("lastSeenChanged", callback, key);
|
||||
@@ -79,6 +107,14 @@ export default class EventBus {
|
||||
|
||||
public emitDeviceNetworkAddressChanged(data: eventdata.DeviceNetworkAddressChanged): void {
|
||||
this.emitter.emit("deviceNetworkAddressChanged", data);
|
||||
|
||||
const device = this.stats.devices.get(data.device.ieeeAddr);
|
||||
|
||||
if (device) {
|
||||
device.networkAddressChanges += 1;
|
||||
} else {
|
||||
this.stats.devices.set(data.device.ieeeAddr, {leaveCounts: 0, networkAddressChanges: 1});
|
||||
}
|
||||
}
|
||||
public onDeviceNetworkAddressChanged(key: ListenerKey, callback: (data: eventdata.DeviceNetworkAddressChanged) => void): void {
|
||||
this.on("deviceNetworkAddressChanged", callback, key);
|
||||
@@ -121,6 +157,14 @@ export default class EventBus {
|
||||
|
||||
public emitDeviceLeave(data: eventdata.DeviceLeave): void {
|
||||
this.emitter.emit("deviceLeave", data);
|
||||
|
||||
const device = this.stats.devices.get(data.ieeeAddr);
|
||||
|
||||
if (device) {
|
||||
device.leaveCounts += 1;
|
||||
} else {
|
||||
this.stats.devices.set(data.ieeeAddr, {leaveCounts: 1, networkAddressChanges: 0});
|
||||
}
|
||||
}
|
||||
public onDeviceLeave(key: ListenerKey, callback: (data: eventdata.DeviceLeave) => void): void {
|
||||
this.on("deviceLeave", callback, key);
|
||||
@@ -135,6 +179,8 @@ export default class EventBus {
|
||||
|
||||
public emitMQTTMessage(data: eventdata.MQTTMessage): void {
|
||||
this.emitter.emit("mqttMessage", data);
|
||||
|
||||
this.stats.mqtt.received += 1;
|
||||
}
|
||||
public onMQTTMessage(key: ListenerKey, callback: (data: eventdata.MQTTMessage) => void): void {
|
||||
this.on("mqttMessage", callback, key);
|
||||
@@ -142,6 +188,8 @@ export default class EventBus {
|
||||
|
||||
public emitMQTTMessagePublished(data: eventdata.MQTTMessagePublished): void {
|
||||
this.emitter.emit("mqttMessagePublished", data);
|
||||
|
||||
this.stats.mqtt.published += 1;
|
||||
}
|
||||
public onMQTTMessagePublished(key: ListenerKey, callback: (data: eventdata.MQTTMessagePublished) => void): void {
|
||||
this.on("mqttMessagePublished", callback, key);
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
import type * as zhc from "zigbee-herdsman-converters";
|
||||
|
||||
import type {Zigbee2MQTTAPI} from "../types/api";
|
||||
|
||||
import assert from "node:assert";
|
||||
|
||||
import bind from "bind-decorator";
|
||||
import debounce from "debounce";
|
||||
import type * as zhc from "zigbee-herdsman-converters";
|
||||
import type {Zigbee2MQTTAPI} from "../types/api";
|
||||
|
||||
import logger from "../util/logger";
|
||||
import * as settings from "../util/settings";
|
||||
@@ -76,7 +73,7 @@ export default class Availability extends Extension {
|
||||
if (entity.isDevice()) {
|
||||
const lastSeen = entity.zh.lastSeen ?? /* v8 ignore next */ 0;
|
||||
|
||||
return Date.now() - lastSeen < this.getTimeout(entity) + this.getMaxJitter(entity);
|
||||
return Date.now() - lastSeen < this.getTimeout(entity);
|
||||
}
|
||||
|
||||
for (const memberDevice of entity.membersDevices()) {
|
||||
@@ -210,7 +207,7 @@ export default class Availability extends Extension {
|
||||
await this.publishAvailability(data.entity, false, true);
|
||||
}
|
||||
});
|
||||
this.eventBus.onEntityRemoved(this, (data) => data.type === "device" && this.clearTimer(data.id));
|
||||
this.eventBus.onEntityRemoved(this, (data) => data.entity.isDevice() && this.clearTimer(data.entity.ID));
|
||||
this.eventBus.onDeviceLeave(this, (data) => this.clearTimer(data.ieeeAddr));
|
||||
this.eventBus.onDeviceAnnounce(this, (data) => this.retrieveState(data.device));
|
||||
this.eventBus.onLastSeenChanged(this, this.onLastSeenChanged);
|
||||
|
||||
+68
-66
@@ -1,23 +1,18 @@
|
||||
import type {ClusterName} from "zigbee-herdsman/dist/zspec/zcl/definition/tstype";
|
||||
|
||||
import type {Zigbee2MQTTAPI, Zigbee2MQTTResponseEndpoints} from "../types/api";
|
||||
|
||||
import assert from "node:assert";
|
||||
|
||||
import bind from "bind-decorator";
|
||||
import debounce from "debounce";
|
||||
import stringify from "json-stable-stringify-without-jsonify";
|
||||
|
||||
import {Zcl} from "zigbee-herdsman";
|
||||
|
||||
import type {TClusterAttributeKeys} from "zigbee-herdsman/dist/zspec/zcl/definition/clusters-types";
|
||||
import type {ClusterName} from "zigbee-herdsman/dist/zspec/zcl/definition/tstype";
|
||||
import Device from "../model/device";
|
||||
import Group from "../model/group";
|
||||
import type {Zigbee2MQTTAPI, Zigbee2MQTTResponseEndpoints} from "../types/api";
|
||||
import logger from "../util/logger";
|
||||
import * as settings from "../util/settings";
|
||||
import utils from "../util/utils";
|
||||
import utils, {DEFAULT_BIND_GROUP_ID} from "../util/utils";
|
||||
import Extension from "./extension";
|
||||
|
||||
const TOPIC_REGEX = new RegExp(`^${settings.get().mqtt.base_topic}/bridge/request/device/(bind|unbind)`);
|
||||
const ALL_CLUSTER_CANDIDATES: readonly ClusterName[] = [
|
||||
"genScenes",
|
||||
"genOnOff",
|
||||
@@ -33,7 +28,7 @@ const ALL_CLUSTER_CANDIDATES: readonly ClusterName[] = [
|
||||
];
|
||||
|
||||
// See zigbee-herdsman-converters
|
||||
const DEFAULT_BIND_GROUP = {type: "group_number", ID: 901, name: "default_bind_group"};
|
||||
const DEFAULT_BIND_GROUP = {type: "group_number", ID: DEFAULT_BIND_GROUP_ID, name: "default_bind_group"};
|
||||
const DEFAULT_REPORT_CONFIG = {minimumReportInterval: 5, maximumReportInterval: 3600, reportableChange: 1};
|
||||
|
||||
const getColorCapabilities = async (endpoint: zh.Endpoint): Promise<{colorTemperature: boolean; colorXY: boolean}> => {
|
||||
@@ -49,53 +44,33 @@ const getColorCapabilities = async (endpoint: zh.Endpoint): Promise<{colorTemper
|
||||
};
|
||||
};
|
||||
|
||||
const REPORT_CLUSTERS: Readonly<
|
||||
Partial<
|
||||
Record<
|
||||
ClusterName,
|
||||
Readonly<{
|
||||
attribute: string;
|
||||
minimumReportInterval: number;
|
||||
maximumReportInterval: number;
|
||||
reportableChange: number;
|
||||
condition?: (endpoint: zh.Endpoint) => Promise<boolean>;
|
||||
}>[]
|
||||
>
|
||||
>
|
||||
> = {
|
||||
genOnOff: [{attribute: "onOff", ...DEFAULT_REPORT_CONFIG, minimumReportInterval: 0, reportableChange: 0}],
|
||||
genLevelCtrl: [{attribute: "currentLevel", ...DEFAULT_REPORT_CONFIG}],
|
||||
const REPORT_CLUSTERS = {
|
||||
genOnOff: [{attribute: "onOff" as const, ...DEFAULT_REPORT_CONFIG, minimumReportInterval: 0, reportableChange: 0}],
|
||||
genLevelCtrl: [{attribute: "currentLevel" as const, ...DEFAULT_REPORT_CONFIG}],
|
||||
lightingColorCtrl: [
|
||||
{
|
||||
attribute: "colorTemperature",
|
||||
attribute: "colorTemperature" as const,
|
||||
...DEFAULT_REPORT_CONFIG,
|
||||
condition: async (endpoint): Promise<boolean> => (await getColorCapabilities(endpoint)).colorTemperature,
|
||||
condition: async (endpoint: zh.Endpoint): Promise<boolean> => (await getColorCapabilities(endpoint)).colorTemperature,
|
||||
},
|
||||
{
|
||||
attribute: "currentX",
|
||||
attribute: "currentX" as const,
|
||||
...DEFAULT_REPORT_CONFIG,
|
||||
condition: async (endpoint): Promise<boolean> => (await getColorCapabilities(endpoint)).colorXY,
|
||||
condition: async (endpoint: zh.Endpoint): Promise<boolean> => (await getColorCapabilities(endpoint)).colorXY,
|
||||
},
|
||||
{
|
||||
attribute: "currentY",
|
||||
attribute: "currentY" as const,
|
||||
...DEFAULT_REPORT_CONFIG,
|
||||
condition: async (endpoint): Promise<boolean> => (await getColorCapabilities(endpoint)).colorXY,
|
||||
condition: async (endpoint: zh.Endpoint): Promise<boolean> => (await getColorCapabilities(endpoint)).colorXY,
|
||||
},
|
||||
],
|
||||
closuresWindowCovering: [
|
||||
{attribute: "currentPositionLiftPercentage", ...DEFAULT_REPORT_CONFIG},
|
||||
{attribute: "currentPositionTiltPercentage", ...DEFAULT_REPORT_CONFIG},
|
||||
{attribute: "currentPositionLiftPercentage" as const, ...DEFAULT_REPORT_CONFIG},
|
||||
{attribute: "currentPositionTiltPercentage" as const, ...DEFAULT_REPORT_CONFIG},
|
||||
],
|
||||
};
|
||||
|
||||
type PollOnMessage = {
|
||||
cluster: Readonly<Partial<Record<ClusterName, {type: string; data: KeyValue}[]>>>;
|
||||
read: Readonly<{cluster: string; attributes: string[]; attributesForEndpoint?: (endpoint: zh.Endpoint) => Promise<string[]>}>;
|
||||
manufacturerIDs: readonly Zcl.ManufacturerCode[];
|
||||
manufacturerNames: readonly string[];
|
||||
}[];
|
||||
|
||||
const POLL_ON_MESSAGE: Readonly<PollOnMessage> = [
|
||||
const POLL_ON_MESSAGE = [
|
||||
{
|
||||
// On messages that have the cluster and type of below
|
||||
cluster: {
|
||||
@@ -115,7 +90,7 @@ const POLL_ON_MESSAGE: Readonly<PollOnMessage> = [
|
||||
genScenes: [{type: "commandRecall", data: {}}],
|
||||
},
|
||||
// Read the following attributes
|
||||
read: {cluster: "genLevelCtrl", attributes: ["currentLevel"]},
|
||||
read: {cluster: "genLevelCtrl" as const, attributes: ["currentLevel"] as TClusterAttributeKeys<"genLevelCtrl">},
|
||||
// When the bound devices/members of group have the following manufacturerIDs
|
||||
manufacturerIDs: [
|
||||
Zcl.ManufacturerCode.SIGNIFY_NETHERLANDS_B_V,
|
||||
@@ -147,7 +122,7 @@ const POLL_ON_MESSAGE: Readonly<PollOnMessage> = [
|
||||
{type: "commandHueNotification", data: {button: 4}},
|
||||
],
|
||||
},
|
||||
read: {cluster: "genOnOff", attributes: ["onOff"]},
|
||||
read: {cluster: "genOnOff" as const, attributes: ["onOff"] as TClusterAttributeKeys<"genOnOff">},
|
||||
manufacturerIDs: [
|
||||
Zcl.ManufacturerCode.SIGNIFY_NETHERLANDS_B_V,
|
||||
Zcl.ManufacturerCode.ATMEL,
|
||||
@@ -163,13 +138,13 @@ const POLL_ON_MESSAGE: Readonly<PollOnMessage> = [
|
||||
genScenes: [{type: "commandRecall", data: {}}],
|
||||
},
|
||||
read: {
|
||||
cluster: "lightingColorCtrl",
|
||||
attributes: [] as string[],
|
||||
cluster: "lightingColorCtrl" as const,
|
||||
attributes: [] as TClusterAttributeKeys<"lightingColorCtrl">,
|
||||
// Since not all devices support the same attributes they need to be calculated dynamically
|
||||
// depending on the capabilities of the endpoint.
|
||||
attributesForEndpoint: async (endpoint): Promise<string[]> => {
|
||||
attributesForEndpoint: async (endpoint: zh.Endpoint): Promise<TClusterAttributeKeys<"lightingColorCtrl">> => {
|
||||
const supportedAttrs = await getColorCapabilities(endpoint);
|
||||
const readAttrs: string[] = [];
|
||||
const readAttrs: TClusterAttributeKeys<"lightingColorCtrl"> = [];
|
||||
|
||||
if (supportedAttrs.colorXY) {
|
||||
readAttrs.push("currentX", "currentY");
|
||||
@@ -209,6 +184,7 @@ interface ParsedMQTTMessage {
|
||||
}
|
||||
|
||||
export default class Bind extends Extension {
|
||||
#topicRegex = new RegExp(`^${settings.get().mqtt.base_topic}/bridge/request/device/(bind|unbind|binds/clear)`);
|
||||
private pollDebouncers: {[s: string]: () => void} = {};
|
||||
|
||||
// biome-ignore lint/suspicious/useAwait: API
|
||||
@@ -221,7 +197,7 @@ export default class Bind extends Extension {
|
||||
private parseMQTTMessage(
|
||||
data: eventdata.MQTTMessage,
|
||||
): [raw: KeyValue | undefined, parsed: ParsedMQTTMessage | undefined, error: string | undefined] {
|
||||
if (data.topic.match(TOPIC_REGEX)) {
|
||||
if (data.topic.match(this.#topicRegex)) {
|
||||
const type = data.topic.endsWith("unbind") ? "unbind" : "bind";
|
||||
let skipDisableReporting = false;
|
||||
const message = JSON.parse(data.message) as Zigbee2MQTTAPI["bridge/request/device/bind"];
|
||||
@@ -300,6 +276,36 @@ export default class Bind extends Extension {
|
||||
}
|
||||
|
||||
@bind private async onMQTTMessage(data: eventdata.MQTTMessage): Promise<void> {
|
||||
if (data.topic.endsWith("binds/clear")) {
|
||||
const message = JSON.parse(data.message) as Zigbee2MQTTAPI["bridge/request/device/binds/clear"];
|
||||
|
||||
if (typeof message !== "object" || typeof message.target !== "string") {
|
||||
await this.publishResponse("binds/clear", message, {}, "Invalid payload");
|
||||
return;
|
||||
}
|
||||
|
||||
const target = this.zigbee.resolveEntity(message.target);
|
||||
|
||||
if (!(target instanceof Device)) {
|
||||
await this.publishResponse("binds/clear", message, {}, "Invalid target");
|
||||
return;
|
||||
}
|
||||
|
||||
// this list is raw (not resolved) to allow clearing any specific target (not only currently known)
|
||||
const eui64List = message.ieee_list ?? ["0xffffffffffffffff"];
|
||||
|
||||
await target.zh.clearAllBindings(eui64List);
|
||||
|
||||
const responseData: Zigbee2MQTTAPI["bridge/response/device/binds/clear"] = {
|
||||
target: message.target,
|
||||
ieee_list: eui64List,
|
||||
};
|
||||
|
||||
await this.publishResponse("binds/clear", message, responseData);
|
||||
this.eventBus.emitDevicesChanged();
|
||||
return;
|
||||
}
|
||||
|
||||
const [raw, parsed, error] = this.parseMQTTMessage(data);
|
||||
|
||||
if (!raw || !parsed) {
|
||||
@@ -413,7 +419,7 @@ export default class Bind extends Extension {
|
||||
}
|
||||
|
||||
private async publishResponse<T extends Zigbee2MQTTResponseEndpoints>(
|
||||
type: ParsedMQTTMessage["type"],
|
||||
type: ParsedMQTTMessage["type"] | "binds/clear",
|
||||
request: KeyValue,
|
||||
data: Zigbee2MQTTAPI[T],
|
||||
error?: string,
|
||||
@@ -485,16 +491,15 @@ export default class Bind extends Extension {
|
||||
const items = [];
|
||||
|
||||
// biome-ignore lint/style/noNonNullAssertion: valid from outer `if`
|
||||
for (const c of REPORT_CLUSTERS[bind.cluster.name as ClusterName]!) {
|
||||
if (!c.condition || (await c.condition(endpoint))) {
|
||||
const i = {...c};
|
||||
delete i.condition;
|
||||
for (const c of REPORT_CLUSTERS[bind.cluster.name as keyof typeof REPORT_CLUSTERS]!) {
|
||||
if (!("condition" in c) || !c.condition || (await c.condition(endpoint))) {
|
||||
const {attribute, minimumReportInterval, maximumReportInterval, reportableChange} = c;
|
||||
|
||||
items.push(i);
|
||||
items.push({attribute, minimumReportInterval, maximumReportInterval, reportableChange});
|
||||
}
|
||||
}
|
||||
|
||||
await endpoint.configureReporting(bind.cluster.name, items);
|
||||
await endpoint.configureReporting(bind.cluster.name as keyof typeof REPORT_CLUSTERS, items);
|
||||
logger.info(`Successfully setup reporting for '${entity}' cluster '${bind.cluster.name}'`);
|
||||
} catch (error) {
|
||||
logger.warning(`Failed to setup reporting for '${entity}' cluster '${bind.cluster.name}' (${(error as Error).message})`);
|
||||
@@ -513,9 +518,7 @@ export default class Bind extends Extension {
|
||||
|
||||
for (const device of this.zigbee.devicesIterator(utils.deviceNotCoordinator)) {
|
||||
for (const endpoint of device.zh.endpoints) {
|
||||
for (const bind of endpoint.binds) {
|
||||
allBinds.push(bind);
|
||||
}
|
||||
allBinds.push(...endpoint.binds);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -544,16 +547,15 @@ export default class Bind extends Extension {
|
||||
const items = [];
|
||||
|
||||
// biome-ignore lint/style/noNonNullAssertion: valid from loop (pushed to array only if in)
|
||||
for (const item of REPORT_CLUSTERS[cluster as ClusterName]!) {
|
||||
if (!item.condition || (await item.condition(endpoint))) {
|
||||
const i = {...item};
|
||||
delete i.condition;
|
||||
for (const item of REPORT_CLUSTERS[cluster as keyof typeof REPORT_CLUSTERS]!) {
|
||||
if (!("condition" in item) || !item.condition || (await item.condition(endpoint))) {
|
||||
const {attribute, minimumReportInterval, reportableChange} = item;
|
||||
|
||||
items.push({...i, maximumReportInterval: 0xffff});
|
||||
items.push({attribute, minimumReportInterval, maximumReportInterval: 0xffff, reportableChange});
|
||||
}
|
||||
}
|
||||
|
||||
await endpoint.configureReporting(cluster, items);
|
||||
await endpoint.configureReporting(cluster as keyof typeof REPORT_CLUSTERS, items);
|
||||
logger.info(`Successfully disabled reporting for '${entity}' cluster '${cluster}'`);
|
||||
} catch (error) {
|
||||
logger.warning(`Failed to disable reporting for '${entity}' cluster '${cluster}' (${(error as Error).message})`);
|
||||
@@ -574,7 +576,7 @@ export default class Bind extends Extension {
|
||||
* When we receive a message from a Hue dimmer we read the brightness from the bulb (if bound).
|
||||
*/
|
||||
const polls = POLL_ON_MESSAGE.filter((p) =>
|
||||
p.cluster[data.cluster as ClusterName]?.some((c) => c.type === data.type && utils.equalsPartial(data.data, c.data)),
|
||||
p.cluster[data.cluster as keyof (typeof p)["cluster"]]?.some((c) => c.type === data.type && utils.equalsPartial(data.data, c.data)),
|
||||
);
|
||||
|
||||
if (polls.length) {
|
||||
|
||||
+95
-24
@@ -1,30 +1,26 @@
|
||||
import type winston from "winston";
|
||||
|
||||
import type Group from "../model/group";
|
||||
import type {Zigbee2MQTTAPI, Zigbee2MQTTDevice, Zigbee2MQTTResponse, Zigbee2MQTTResponseEndpoints} from "../types/api";
|
||||
|
||||
import fs from "node:fs";
|
||||
|
||||
import bind from "bind-decorator";
|
||||
import stringify from "json-stable-stringify-without-jsonify";
|
||||
import JSZip from "jszip";
|
||||
import objectAssignDeep from "object-assign-deep";
|
||||
import type winston from "winston";
|
||||
import Transport from "winston-transport";
|
||||
|
||||
import {Zcl} from "zigbee-herdsman";
|
||||
import * as zhc from "zigbee-herdsman-converters";
|
||||
import {InterviewState} from "zigbee-herdsman/dist/controller/model/device";
|
||||
|
||||
import * as zhc from "zigbee-herdsman-converters";
|
||||
import Device from "../model/device";
|
||||
import type Group from "../model/group";
|
||||
import type {Zigbee2MQTTAPI, Zigbee2MQTTDevice, Zigbee2MQTTResponse, Zigbee2MQTTResponseEndpoints} from "../types/api";
|
||||
import data from "../util/data";
|
||||
import logger from "../util/logger";
|
||||
import * as settings from "../util/settings";
|
||||
import utils, {assertString} from "../util/utils";
|
||||
import utils, {assertString, DEFAULT_BIND_GROUP_ID} from "../util/utils";
|
||||
import Extension from "./extension";
|
||||
|
||||
const REQUEST_REGEX = new RegExp(`${settings.get().mqtt.base_topic}/bridge/request/(.*)`);
|
||||
|
||||
export default class Bridge extends Extension {
|
||||
#requestRegex = new RegExp(`${settings.get().mqtt.base_topic}/bridge/request/(.*)`);
|
||||
// set on `start`
|
||||
#osInfo!: Zigbee2MQTTAPI["bridge/info"]["os"];
|
||||
private zigbee2mqttVersion!: {commitHash?: string; version: string};
|
||||
private zigbeeHerdsmanVersion!: {version: string};
|
||||
private zigbeeHerdsmanConvertersVersion!: {version: string};
|
||||
@@ -35,7 +31,10 @@ export default class Bridge extends Extension {
|
||||
private logTransport!: winston.transport;
|
||||
private requestLookup: {[key: string]: (message: KeyValue | string) => Promise<Zigbee2MQTTResponse<Zigbee2MQTTResponseEndpoints>>} = {
|
||||
"device/options": this.deviceOptions,
|
||||
"device/configure_reporting": this.deviceConfigureReporting,
|
||||
/** @deprecated 3.0 */
|
||||
"device/configure_reporting": this.deviceReportingConfigure,
|
||||
"device/reporting/configure": this.deviceReportingConfigure,
|
||||
"device/reporting/read": this.deviceReportingRead,
|
||||
"device/remove": this.deviceRemove,
|
||||
"device/interview": this.deviceInterview,
|
||||
"device/generate_external_definition": this.deviceGenerateExternalDefinition,
|
||||
@@ -54,6 +53,7 @@ export default class Bridge extends Extension {
|
||||
health_check: this.healthCheck,
|
||||
coordinator_check: this.coordinatorCheck,
|
||||
options: this.bridgeOptions,
|
||||
action: this.action,
|
||||
};
|
||||
|
||||
override async start(): Promise<void> {
|
||||
@@ -92,6 +92,15 @@ export default class Bridge extends Extension {
|
||||
|
||||
logger.addTransport(this.logTransport);
|
||||
|
||||
const os = await import("node:os");
|
||||
const process = await import("node:process");
|
||||
const logicalCpuCores = os.cpus();
|
||||
this.#osInfo = {
|
||||
version: `${os.version()} - ${os.release()} - ${os.arch()}`,
|
||||
node_version: process.version,
|
||||
cpus: `${[...new Set(logicalCpuCores.map((cpu) => cpu.model))].join(" | ")} (x${logicalCpuCores.length})`,
|
||||
memory_mb: Math.round(os.totalmem() / 1024 / 1024),
|
||||
};
|
||||
this.zigbee2mqttVersion = await utils.getZigbee2MQTTVersion();
|
||||
this.zigbeeHerdsmanVersion = await utils.getDependencyVersion("zigbee-herdsman");
|
||||
this.zigbeeHerdsmanConvertersVersion = await utils.getDependencyVersion("zigbee-herdsman-converters");
|
||||
@@ -191,7 +200,7 @@ export default class Bridge extends Extension {
|
||||
}
|
||||
|
||||
@bind async onMQTTMessage(data: eventdata.MQTTMessage): Promise<void> {
|
||||
const match = data.topic.match(REQUEST_REGEX);
|
||||
const match = data.topic.match(this.#requestRegex);
|
||||
|
||||
if (!match) {
|
||||
return;
|
||||
@@ -461,16 +470,16 @@ export default class Bridge extends Extension {
|
||||
return utils.getResponse(message, {from: oldOptions, to: newOptions, id: ID, restart_required: this.restartRequired});
|
||||
}
|
||||
|
||||
@bind async deviceConfigureReporting(message: string | KeyValue): Promise<Zigbee2MQTTResponse<"bridge/response/device/configure_reporting">> {
|
||||
@bind async deviceReportingConfigure(message: string | KeyValue): Promise<Zigbee2MQTTResponse<"bridge/response/device/reporting/configure">> {
|
||||
if (
|
||||
typeof message !== "object" ||
|
||||
message.id === undefined ||
|
||||
message.endpoint === undefined ||
|
||||
message.cluster === undefined ||
|
||||
message.maximum_report_interval === undefined ||
|
||||
message.minimum_report_interval === undefined ||
|
||||
message.reportable_change === undefined ||
|
||||
message.attribute === undefined
|
||||
message.attribute === undefined ||
|
||||
typeof message.maximum_report_interval !== "number" ||
|
||||
typeof message.minimum_report_interval !== "number" ||
|
||||
(message.reportable_change !== undefined && typeof message.reportable_change !== "number")
|
||||
) {
|
||||
throw new Error("Invalid payload");
|
||||
}
|
||||
@@ -513,6 +522,46 @@ export default class Bridge extends Extension {
|
||||
});
|
||||
}
|
||||
|
||||
@bind async deviceReportingRead(message: string | KeyValue): Promise<Zigbee2MQTTResponse<"bridge/response/device/reporting/read">> {
|
||||
if (
|
||||
typeof message !== "object" ||
|
||||
message.id === undefined ||
|
||||
message.endpoint === undefined ||
|
||||
message.cluster === undefined ||
|
||||
message.configs === undefined
|
||||
) {
|
||||
throw new Error("Invalid payload");
|
||||
}
|
||||
|
||||
const device = this.getEntity("device", message.id);
|
||||
const endpoint = device.endpoint(message.endpoint);
|
||||
|
||||
if (!endpoint) {
|
||||
throw new Error(`Device '${device.ID}' does not have endpoint '${message.endpoint}'`);
|
||||
}
|
||||
|
||||
const response = await endpoint.readReportingConfig(
|
||||
message.cluster,
|
||||
message.configs,
|
||||
message.manufacturer_code ? {manufacturerCode: message.manufacturer_code} : {},
|
||||
);
|
||||
|
||||
await this.publishDevices();
|
||||
|
||||
const responseData: Zigbee2MQTTAPI["bridge/response/device/reporting/read"] = {
|
||||
id: message.id,
|
||||
endpoint: message.endpoint,
|
||||
cluster: message.cluster,
|
||||
configs: response,
|
||||
};
|
||||
|
||||
if (message.manufacturer_code) {
|
||||
responseData.manufacturer_code = message.manufacturer_code;
|
||||
}
|
||||
|
||||
return utils.getResponse(message, responseData);
|
||||
}
|
||||
|
||||
@bind async deviceInterview(message: string | KeyValue): Promise<Zigbee2MQTTResponse<"bridge/response/device/interview">> {
|
||||
if (typeof message !== "object" || message.id === undefined) {
|
||||
throw new Error("Invalid payload");
|
||||
@@ -549,6 +598,22 @@ export default class Bridge extends Extension {
|
||||
return utils.getResponse(message, {id: message.id, source});
|
||||
}
|
||||
|
||||
@bind async action(message: string | KeyValue): Promise<Zigbee2MQTTResponse<"bridge/response/action">> {
|
||||
if (typeof message !== "object" || !message.action) {
|
||||
throw new Error("Invalid payload");
|
||||
}
|
||||
|
||||
const action = zhc.ACTIONS[message.action];
|
||||
|
||||
if (action === undefined) {
|
||||
throw new Error("Invalid action");
|
||||
}
|
||||
|
||||
const response = await action(this.zigbee.zhController, message.params ?? {});
|
||||
|
||||
return utils.getResponse(message, response);
|
||||
}
|
||||
|
||||
async renameEntity<T extends "device" | "group">(
|
||||
entityType: T,
|
||||
message: string | KeyValue,
|
||||
@@ -625,7 +690,6 @@ export default class Bridge extends Extension {
|
||||
await entity.zh.removeFromNetwork();
|
||||
}
|
||||
|
||||
this.eventBus.emitEntityRemoved({id: entity.ID, name: friendlyName, type: "device"});
|
||||
settings.removeDevice(entity.ID as string);
|
||||
} else {
|
||||
if (force) {
|
||||
@@ -634,10 +698,12 @@ export default class Bridge extends Extension {
|
||||
await entity.zh.removeFromNetwork();
|
||||
}
|
||||
|
||||
this.eventBus.emitEntityRemoved({id: entity.ID, name: friendlyName, type: "group"});
|
||||
this.zigbee.removeGroupFromLookup(entity.ID);
|
||||
settings.removeGroup(entity.ID);
|
||||
}
|
||||
|
||||
this.eventBus.emitEntityRemoved({entity, name: friendlyName});
|
||||
|
||||
// Remove from state
|
||||
this.state.remove(entity.ID);
|
||||
|
||||
@@ -691,6 +757,8 @@ export default class Bridge extends Extension {
|
||||
|
||||
const networkParams = await this.zigbee.getNetworkParameters();
|
||||
const payload: Zigbee2MQTTAPI["bridge/info"] = {
|
||||
os: this.#osInfo,
|
||||
mqtt: this.mqtt.info,
|
||||
version: this.zigbee2mqttVersion.version,
|
||||
commit: this.zigbee2mqttVersion.commitHash,
|
||||
zigbee_herdsman_converters: this.zigbeeHerdsmanConvertersVersion,
|
||||
@@ -723,6 +791,7 @@ export default class Bridge extends Extension {
|
||||
|
||||
for (const endpoint of device.zh.endpoints) {
|
||||
const data: (typeof endpoints)[keyof typeof endpoints] = {
|
||||
name: device.endpointName(endpoint),
|
||||
scenes: utils.getScenes(endpoint),
|
||||
bindings: [],
|
||||
configured_reportings: [],
|
||||
@@ -789,7 +858,7 @@ export default class Bridge extends Extension {
|
||||
|
||||
groups.push({
|
||||
id: group.ID,
|
||||
friendly_name: group.ID === 901 ? "default_bind_group" : group.name,
|
||||
friendly_name: group.ID === DEFAULT_BIND_GROUP_ID ? "default_bind_group" : group.name,
|
||||
description: group.options.description,
|
||||
scenes: utils.getScenes(group.zh),
|
||||
members,
|
||||
@@ -803,6 +872,7 @@ export default class Bridge extends Extension {
|
||||
const data: Zigbee2MQTTAPI["bridge/definitions"] = {
|
||||
clusters: Zcl.Clusters,
|
||||
custom_clusters: {},
|
||||
actions: Object.keys(zhc.ACTIONS),
|
||||
};
|
||||
|
||||
for (const device of this.zigbee.devicesIterator((d) => !utils.objectIsEmpty(d.customClusters))) {
|
||||
@@ -824,11 +894,12 @@ export default class Bridge extends Extension {
|
||||
|
||||
if (icon) {
|
||||
/* v8 ignore next */
|
||||
icon = icon.replace("${zigbeeModel}", utils.sanitizeImageParameter(device.zh.modelID ?? ""));
|
||||
icon = icon.replace("${model}", utils.sanitizeImageParameter(device.definition.model));
|
||||
icon = icon.replace("$zigbeeModel", utils.sanitizeImageParameter(device.zh.modelID ?? ""));
|
||||
icon = icon.replace("$model", utils.sanitizeImageParameter(device.definition.model));
|
||||
}
|
||||
|
||||
const payload: Zigbee2MQTTDevice["definition"] = {
|
||||
source: device.definition.externalConverterName ? "external" : device.definition.generated ? "generated" : "native",
|
||||
model: device.definition.model,
|
||||
vendor: device.definition.vendor,
|
||||
description: device.definition.description,
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
import type {Zigbee2MQTTAPI} from "../types/api";
|
||||
|
||||
import bind from "bind-decorator";
|
||||
import stringify from "json-stable-stringify-without-jsonify";
|
||||
|
||||
import * as zhc from "zigbee-herdsman-converters";
|
||||
|
||||
import Device from "../model/device";
|
||||
import type {Zigbee2MQTTAPI} from "../types/api";
|
||||
import logger from "../util/logger";
|
||||
import * as settings from "../util/settings";
|
||||
import utils from "../util/utils";
|
||||
@@ -59,7 +56,7 @@ export default class Configure extends Extension {
|
||||
}
|
||||
}
|
||||
|
||||
override async start(): Promise<void> {
|
||||
override start(): Promise<void> {
|
||||
setImmediate(async () => {
|
||||
// Only configure routers on startup, end devices are likely sleeping and
|
||||
// will reconfigure once they send a message
|
||||
@@ -82,6 +79,8 @@ export default class Configure extends Extension {
|
||||
this.eventBus.onLastSeenChanged(this, (data) => this.configure(data.device, "zigbee_event"));
|
||||
this.eventBus.onMQTTMessage(this, this.onMQTTMessage);
|
||||
this.eventBus.onReconfigure(this, this.onReconfigure);
|
||||
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
private async configure(
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import type Extension from "./extension";
|
||||
|
||||
import logger from "../util/logger";
|
||||
import * as settings from "../util/settings";
|
||||
import type Extension from "./extension";
|
||||
import ExternalJSExtension from "./externalJS";
|
||||
|
||||
type TModule = new (...args: ConstructorParameters<typeof Extension>) => Extension;
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import type {Zigbee2MQTTAPI, Zigbee2MQTTResponse} from "../types/api";
|
||||
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import bind from "bind-decorator";
|
||||
import stringify from "json-stable-stringify-without-jsonify";
|
||||
import type {Zigbee2MQTTAPI, Zigbee2MQTTResponse} from "../types/api";
|
||||
|
||||
import data from "../util/data";
|
||||
import logger from "../util/logger";
|
||||
@@ -59,13 +57,15 @@ export default abstract class ExternalJSExtension<M> extends Extension {
|
||||
if (!basePathInZ2mDir) {
|
||||
logger.debug(`External JS folder '${this.folderName}' is outside the Z2M install dir, creating a symlink to 'node_modules'`);
|
||||
const nodeModulesSymlink = path.join(this.basePath, "node_modules");
|
||||
/* v8 ignore start */
|
||||
if (fs.existsSync(nodeModulesSymlink)) {
|
||||
fs.unlinkSync(nodeModulesSymlink);
|
||||
}
|
||||
/* v8 ignore stop */
|
||||
|
||||
// Type `junction` is required on Windows.
|
||||
// https://github.com/nodejs/node/issues/18518#issuecomment-513866491
|
||||
/* v8 ignore next */
|
||||
fs.symlinkSync(nodeModulesPath, nodeModulesSymlink, os.platform() === "win32" ? "junction" : "dir");
|
||||
fs.symlinkSync(nodeModulesPath, nodeModulesSymlink, /* v8 ignore next */ os.platform() === "win32" ? "junction" : "dir");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -77,6 +77,17 @@ export default abstract class ExternalJSExtension<M> extends Extension {
|
||||
await this.publishExternalJS();
|
||||
}
|
||||
|
||||
override async stop(): Promise<void> {
|
||||
await super.stop();
|
||||
|
||||
// ensure "node_modules" is never followed & included in 3rd-party backup systems
|
||||
const nodeModulesSymlink = path.join(this.basePath, "node_modules");
|
||||
|
||||
if (fs.existsSync(nodeModulesSymlink)) {
|
||||
fs.unlinkSync(nodeModulesSymlink);
|
||||
}
|
||||
}
|
||||
|
||||
private getFilePath(name: string, mkBasePath = false): string {
|
||||
if (mkBasePath && !fs.existsSync(this.basePath)) {
|
||||
fs.mkdirSync(this.basePath, {recursive: true});
|
||||
@@ -195,7 +206,7 @@ export default abstract class ExternalJSExtension<M> extends Extension {
|
||||
fs.renameSync(filePath, `${filePath}.invalid`);
|
||||
|
||||
logger.error(
|
||||
`Invalid external ${this.mqttTopic} '${extension.name}' was ignored and renamed to prevent interference with Zigbee2MQTT.`,
|
||||
`Invalid external ${this.mqttTopic} '${extension.name}' was ignored and renamed to prevent interference with Zigbee2MQTT. (${(error as Error).message})`,
|
||||
);
|
||||
// biome-ignore lint/style/noNonNullAssertion: always Error
|
||||
logger.debug((error as Error).stack!);
|
||||
|
||||
+88
-84
@@ -1,15 +1,11 @@
|
||||
import type {IncomingMessage, Server, ServerResponse} from "node:http";
|
||||
import type {Socket} from "node:net";
|
||||
|
||||
import type {RequestHandler} from "express-static-gzip";
|
||||
|
||||
import assert from "node:assert";
|
||||
import {existsSync, readFileSync} from "node:fs";
|
||||
import type {IncomingMessage, Server, ServerResponse} from "node:http";
|
||||
import {createServer} from "node:http";
|
||||
import {createServer as createSecureServer} from "node:https";
|
||||
import type {Socket} from "node:net";
|
||||
import {posix} from "node:path";
|
||||
import {parse} from "node:url";
|
||||
|
||||
import bind from "bind-decorator";
|
||||
import expressStaticGzip from "express-static-gzip";
|
||||
import finalhandler from "finalhandler";
|
||||
@@ -27,9 +23,7 @@ import Extension from "./extension";
|
||||
*/
|
||||
export class Frontend extends Extension {
|
||||
private mqttBaseTopic: string;
|
||||
private server!: Server;
|
||||
private fileServer!: RequestHandler;
|
||||
private deviceIconsFileServer!: RequestHandler;
|
||||
private server: Server | undefined;
|
||||
private wss!: WebSocket.Server;
|
||||
private baseUrl: string;
|
||||
|
||||
@@ -52,60 +46,97 @@ export class Frontend extends Extension {
|
||||
}
|
||||
|
||||
override async start(): Promise<void> {
|
||||
const hasSSL = (val: string | undefined, key: string): val is string => {
|
||||
if (val) {
|
||||
if (!existsSync(val)) {
|
||||
logger.error(`Defined ${key} '${val}' file path does not exists, server won't be secured.`);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
const {host, port, ssl_key: sslKey, ssl_cert: sslCert} = settings.get().frontend;
|
||||
const options = {
|
||||
enableBrotli: true,
|
||||
// TODO: https://github.com/Koenkk/zigbee2mqtt/issues/24654 - enable compressed index serving when express-static-gzip is fixed.
|
||||
index: false,
|
||||
serveStatic: {
|
||||
index: "index.html",
|
||||
/* v8 ignore start */
|
||||
setHeaders: (res: ServerResponse, path: string): void => {
|
||||
if (path.endsWith("index.html")) {
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
if (settings.get().frontend.disable_ui_serving) {
|
||||
const {host, port} = settings.get().frontend;
|
||||
this.wss = new WebSocket.Server({port, host, path: posix.join(this.baseUrl, "api")});
|
||||
|
||||
logger.info(
|
||||
/* v8 ignore next */
|
||||
`Frontend UI serving is disabled. WebSocket at: ${this.wss.options.host ?? "0.0.0.0"}:${this.wss.options.port}${this.wss.options.path}`,
|
||||
);
|
||||
} else {
|
||||
const {host, port, ssl_key: sslKey, ssl_cert: sslCert} = settings.get().frontend;
|
||||
const hasSSL = (val: string | undefined, key: string): val is string => {
|
||||
if (val) {
|
||||
if (existsSync(val)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
logger.error(`Defined ${key} '${val}' file path does not exists, server won't be secured.`);
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
const options: expressStaticGzip.ExpressStaticGzipOptions = {
|
||||
enableBrotli: true,
|
||||
serveStatic: {
|
||||
/* v8 ignore start */
|
||||
setHeaders: (res: ServerResponse, path: string): void => {
|
||||
if (path.endsWith("index.html")) {
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
}
|
||||
},
|
||||
/* v8 ignore stop */
|
||||
},
|
||||
/* v8 ignore stop */
|
||||
},
|
||||
};
|
||||
const frontend = (await import(settings.get().frontend.package)) as typeof import("zigbee2mqtt-frontend");
|
||||
this.fileServer = expressStaticGzip(frontend.default.getPath(), options);
|
||||
this.deviceIconsFileServer = expressStaticGzip(data.joinPath("device_icons"), options);
|
||||
this.wss = new WebSocket.Server({noServer: true, path: posix.join(this.baseUrl, "api")});
|
||||
};
|
||||
const frontend = (await import(settings.get().frontend.package)) as typeof import("zigbee2mqtt-frontend");
|
||||
const fileServer = expressStaticGzip(frontend.default.getPath(), options);
|
||||
const deviceIconsFileServer = expressStaticGzip(data.joinPath("device_icons"), options);
|
||||
const onRequest = (request: IncomingMessage, response: ServerResponse): void => {
|
||||
const next = finalhandler(request, response);
|
||||
// biome-ignore lint/style/noNonNullAssertion: `Only valid for request obtained from Server`
|
||||
const newUrl = posix.relative(this.baseUrl, request.url!);
|
||||
|
||||
// The request url is not within the frontend base url, so the relative path starts with '..'
|
||||
if (newUrl.startsWith(".")) {
|
||||
next();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Attach originalUrl so that static-server can perform a redirect to '/' when serving the root directory.
|
||||
// This is necessary for the browser to resolve relative assets paths correctly.
|
||||
request.originalUrl = request.url;
|
||||
request.url = `/${newUrl}`;
|
||||
request.path = request.url;
|
||||
|
||||
if (newUrl.startsWith("device_icons/")) {
|
||||
request.path = request.path.replace("device_icons/", "");
|
||||
request.url = request.url.replace("/device_icons", "");
|
||||
|
||||
deviceIconsFileServer(request, response, next);
|
||||
} else {
|
||||
fileServer(request, response, next);
|
||||
}
|
||||
};
|
||||
|
||||
if (hasSSL(sslKey, "ssl_key") && hasSSL(sslCert, "ssl_cert")) {
|
||||
const serverOptions = {key: readFileSync(sslKey), cert: readFileSync(sslCert)};
|
||||
this.server = createSecureServer(serverOptions, onRequest);
|
||||
} else {
|
||||
this.server = createServer(onRequest);
|
||||
}
|
||||
|
||||
this.server.on("upgrade", this.onUpgrade);
|
||||
|
||||
if (!host) {
|
||||
this.server.listen(port);
|
||||
logger.info(`Started frontend on port ${port}`);
|
||||
} else if (host.startsWith("/")) {
|
||||
this.server.listen(host);
|
||||
logger.info(`Started frontend on socket ${host}`);
|
||||
} else {
|
||||
this.server.listen(port, host);
|
||||
logger.info(`Started frontend on port ${host}:${port}`);
|
||||
}
|
||||
|
||||
this.wss = new WebSocket.Server({noServer: true, path: posix.join(this.baseUrl, "api")});
|
||||
}
|
||||
|
||||
this.wss.on("connection", this.onWebSocketConnection);
|
||||
|
||||
if (hasSSL(sslKey, "ssl_key") && hasSSL(sslCert, "ssl_cert")) {
|
||||
const serverOptions = {key: readFileSync(sslKey), cert: readFileSync(sslCert)};
|
||||
this.server = createSecureServer(serverOptions, this.onRequest);
|
||||
} else {
|
||||
this.server = createServer(this.onRequest);
|
||||
}
|
||||
|
||||
this.server.on("upgrade", this.onUpgrade);
|
||||
this.eventBus.onMQTTMessagePublished(this, this.onMQTTPublishMessageOrEntityState);
|
||||
this.eventBus.onPublishEntityState(this, this.onMQTTPublishMessageOrEntityState);
|
||||
|
||||
if (!host) {
|
||||
this.server.listen(port);
|
||||
logger.info(`Started frontend on port ${port}`);
|
||||
} else if (host.startsWith("/")) {
|
||||
this.server.listen(host);
|
||||
logger.info(`Started frontend on socket ${host}`);
|
||||
} else {
|
||||
this.server.listen(port, host);
|
||||
logger.info(`Started frontend on port ${host}:${port}`);
|
||||
}
|
||||
}
|
||||
|
||||
override async stop(): Promise<void> {
|
||||
@@ -120,34 +151,7 @@ export class Frontend extends Extension {
|
||||
this.wss.close();
|
||||
}
|
||||
|
||||
await new Promise((resolve) => this.server?.close(resolve));
|
||||
}
|
||||
|
||||
@bind private onRequest(request: IncomingMessage, response: ServerResponse): void {
|
||||
const fin = finalhandler(request, response);
|
||||
// biome-ignore lint/style/noNonNullAssertion: `Only valid for request obtained from Server`
|
||||
const newUrl = posix.relative(this.baseUrl, request.url!);
|
||||
|
||||
// The request url is not within the frontend base url, so the relative path starts with '..'
|
||||
if (newUrl.startsWith(".")) {
|
||||
fin();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Attach originalUrl so that static-server can perform a redirect to '/' when serving the root directory.
|
||||
// This is necessary for the browser to resolve relative assets paths correctly.
|
||||
request.originalUrl = request.url;
|
||||
request.url = `/${newUrl}`;
|
||||
request.path = request.url;
|
||||
|
||||
if (newUrl.startsWith("device_icons/")) {
|
||||
request.path = request.path.replace("device_icons/", "");
|
||||
request.url = request.url.replace("/device_icons", "");
|
||||
this.deviceIconsFileServer(request, response, fin);
|
||||
} else {
|
||||
this.fileServer(request, response, fin);
|
||||
}
|
||||
await new Promise((resolve) => (this.server ? this.server.close(resolve) : resolve(undefined)));
|
||||
}
|
||||
|
||||
@bind private onUpgrade(request: IncomingMessage, socket: Socket, head: Buffer): void {
|
||||
|
||||
+8
-13
@@ -1,22 +1,16 @@
|
||||
import type * as zhc from "zigbee-herdsman-converters";
|
||||
|
||||
import type {Zigbee2MQTTAPI, Zigbee2MQTTResponseEndpoints} from "../types/api";
|
||||
|
||||
import assert from "node:assert";
|
||||
|
||||
import bind from "bind-decorator";
|
||||
import equals from "fast-deep-equal/es6";
|
||||
import stringify from "json-stable-stringify-without-jsonify";
|
||||
|
||||
import type * as zhc from "zigbee-herdsman-converters";
|
||||
import Device from "../model/device";
|
||||
import Group from "../model/group";
|
||||
import type {Zigbee2MQTTAPI, Zigbee2MQTTResponseEndpoints} from "../types/api";
|
||||
import logger from "../util/logger";
|
||||
import * as settings from "../util/settings";
|
||||
import utils, {isLightExpose} from "../util/utils";
|
||||
import Extension from "./extension";
|
||||
|
||||
const TOPIC_REGEX = new RegExp(`^${settings.get().mqtt.base_topic}/bridge/request/group/members/(remove|add|remove_all)$`);
|
||||
|
||||
const STATE_PROPERTIES: Readonly<Record<string, (value: string, exposes: zhc.Expose[]) => boolean>> = {
|
||||
state: () => true,
|
||||
brightness: (_value, exposes) => exposes.some((e) => isLightExpose(e) && e.features.some((f) => f.name === "brightness")),
|
||||
@@ -42,6 +36,7 @@ interface ParsedMQTTMessage {
|
||||
}
|
||||
|
||||
export default class Groups extends Extension {
|
||||
#topicRegex = new RegExp(`^${settings.get().mqtt.base_topic}/bridge/request/group/members/(remove|add|remove_all)$`);
|
||||
private lastOptimisticState: {[s: string]: KeyValue} = {};
|
||||
|
||||
// biome-ignore lint/suspicious/useAwait: API
|
||||
@@ -189,7 +184,7 @@ export default class Groups extends Extension {
|
||||
private parseMQTTMessage(
|
||||
data: eventdata.MQTTMessage,
|
||||
): [raw: KeyValue | undefined, parsed: ParsedMQTTMessage | undefined, error: string | undefined] {
|
||||
const topicRegexMatch = data.topic.match(TOPIC_REGEX);
|
||||
const topicRegexMatch = data.topic.match(this.#topicRegex);
|
||||
|
||||
if (topicRegexMatch) {
|
||||
const type = topicRegexMatch[1] as "remove" | "add" | "remove_all";
|
||||
@@ -277,7 +272,7 @@ export default class Groups extends Extension {
|
||||
try {
|
||||
if (type === "add") {
|
||||
assert(resolvedGroup, "`resolvedGroup` is missing");
|
||||
logger.info(`Adding '${resolvedDevice.name}' to '${resolvedGroup.name}'`);
|
||||
logger.info(`Adding endpoint '${resolvedEndpoint.ID}' of device '${resolvedDevice.name}' to group '${resolvedGroup.name}'`);
|
||||
await resolvedEndpoint.addToGroup(resolvedGroup.zh);
|
||||
changedGroups.push(resolvedGroup);
|
||||
// biome-ignore lint/style/noNonNullAssertion: valid from resolved asserts
|
||||
@@ -285,7 +280,7 @@ export default class Groups extends Extension {
|
||||
await this.publishResponse<"bridge/response/group/members/add">(parsed.type, raw, respPayload);
|
||||
} else if (type === "remove") {
|
||||
assert(resolvedGroup, "`resolvedGroup` is missing");
|
||||
logger.info(`Removing '${resolvedDevice.name}' from '${resolvedGroup.name}'`);
|
||||
logger.info(`Removing endpoint '${resolvedEndpoint.ID}' of device '${resolvedDevice.name}' from group '${resolvedGroup.name}'`);
|
||||
await resolvedEndpoint.removeFromGroup(resolvedGroup.zh);
|
||||
changedGroups.push(resolvedGroup);
|
||||
// biome-ignore lint/style/noNonNullAssertion: valid from resolved asserts
|
||||
@@ -293,7 +288,7 @@ export default class Groups extends Extension {
|
||||
await this.publishResponse<"bridge/response/group/members/remove">(parsed.type, raw, respPayload);
|
||||
} else {
|
||||
// remove_all
|
||||
logger.info(`Removing '${resolvedDevice.name}' from all groups`);
|
||||
logger.info(`Removing endpoint '${resolvedEndpoint.ID}' of device '${resolvedDevice.name}' from all groups`);
|
||||
|
||||
for (const group of this.zigbee.groupsIterator((g) => g.members.includes(resolvedEndpoint))) {
|
||||
changedGroups.push(group);
|
||||
@@ -305,7 +300,7 @@ export default class Groups extends Extension {
|
||||
await this.publishResponse<"bridge/response/group/members/remove_all">(parsed.type, raw, respPayload);
|
||||
}
|
||||
} catch (e) {
|
||||
const errorMsg = `Failed to ${type} from group (${(e as Error).message})`;
|
||||
const errorMsg = `Failed to ${type} ${type === "add" ? "to" : "from"} group (${(e as Error).message})`;
|
||||
await this.publishResponse(parsed.type, raw, {}, errorMsg);
|
||||
// biome-ignore lint/style/noNonNullAssertion: always Error
|
||||
logger.debug((e as Error).stack!);
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import * as os from "node:os";
|
||||
import * as process from "node:process";
|
||||
import type {Zigbee2MQTTAPI} from "../types/api";
|
||||
import * as settings from "../util/settings";
|
||||
import utils from "../util/utils";
|
||||
import Extension from "./extension";
|
||||
|
||||
/** Round with 2 decimals */
|
||||
const round2 = (n: number): number => Math.round(n * 100.0) / 100.0;
|
||||
/** Round with 4 decimals */
|
||||
const round4 = (n: number): number => Math.round(n * 10000.0) / 10000.0;
|
||||
|
||||
export default class Health extends Extension {
|
||||
#checkTimer: NodeJS.Timeout | undefined;
|
||||
|
||||
override async start(): Promise<void> {
|
||||
await super.start();
|
||||
|
||||
this.#checkTimer = setInterval(this.#checkHealth.bind(this), utils.minutes(settings.get().health.interval));
|
||||
}
|
||||
|
||||
override async stop(): Promise<void> {
|
||||
clearInterval(this.#checkTimer);
|
||||
await super.stop();
|
||||
}
|
||||
|
||||
clearStats(): void {
|
||||
this.eventBus.stats.devices.clear();
|
||||
this.eventBus.stats.mqtt.published = 0;
|
||||
this.eventBus.stats.mqtt.received = 0;
|
||||
}
|
||||
|
||||
async #checkHealth(): Promise<void> {
|
||||
const sysMemTotalKb = os.totalmem() / 1024;
|
||||
const sysMemFreeKb = os.freemem() / 1024;
|
||||
const sysMemUsedKb = sysMemTotalKb - sysMemFreeKb;
|
||||
const procMemUsedKb = process.memoryUsage().rss / 1024;
|
||||
const healthcheck: Zigbee2MQTTAPI["bridge/health"] = {
|
||||
response_time: Date.now(),
|
||||
os: {
|
||||
load_average: os.loadavg(), // will be [0,0,0] on Windows (not supported)
|
||||
memory_used_mb: round2(sysMemUsedKb / 1024),
|
||||
memory_percent: round4((sysMemUsedKb / sysMemTotalKb) * 100.0),
|
||||
},
|
||||
process: {
|
||||
uptime_sec: Math.floor(process.uptime()),
|
||||
memory_used_mb: round2(procMemUsedKb / 1024),
|
||||
memory_percent: round4((procMemUsedKb / sysMemTotalKb) * 100.0),
|
||||
},
|
||||
mqtt: {...this.mqtt.stats, ...this.eventBus.stats.mqtt},
|
||||
devices: {},
|
||||
};
|
||||
|
||||
for (const [ieeeAddr, device] of this.eventBus.stats.devices) {
|
||||
let messages = 0;
|
||||
let mps = 0;
|
||||
|
||||
if (device.lastSeenChanges) {
|
||||
const timeDiff = Date.now() - device.lastSeenChanges.first;
|
||||
messages = device.lastSeenChanges.messages;
|
||||
mps = timeDiff > 0 ? round4(messages / (timeDiff / 1000.0)) : 0;
|
||||
}
|
||||
|
||||
healthcheck.devices[ieeeAddr] = {
|
||||
messages,
|
||||
messages_per_sec: mps,
|
||||
leave_count: device.leaveCounts,
|
||||
network_address_changes: device.networkAddressChanges,
|
||||
};
|
||||
}
|
||||
|
||||
if (settings.get().health.reset_on_check) {
|
||||
this.clearStats();
|
||||
}
|
||||
|
||||
await this.mqtt.publish("bridge/health", JSON.stringify(healthcheck), {clientOptions: {retain: true, qos: 1}});
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,7 @@
|
||||
import type * as zhc from "zigbee-herdsman-converters";
|
||||
|
||||
import assert from "node:assert";
|
||||
|
||||
import bind from "bind-decorator";
|
||||
import stringify from "json-stable-stringify-without-jsonify";
|
||||
import type * as zhc from "zigbee-herdsman-converters";
|
||||
|
||||
import logger from "../util/logger";
|
||||
import * as settings from "../util/settings";
|
||||
@@ -83,7 +81,7 @@ const BINARY_DISCOVERY_LOOKUP: {[s: string]: KeyValue} = {
|
||||
noise_detected: {device_class: "sound"},
|
||||
occupancy: {device_class: "occupancy"},
|
||||
power_outage_memory: {entity_category: "config", icon: "mdi:memory"},
|
||||
presence: {device_class: "presence"},
|
||||
presence: {device_class: "occupancy"},
|
||||
setup: {device_class: "running"},
|
||||
smoke: {device_class: "smoke"},
|
||||
sos: {device_class: "safety"},
|
||||
@@ -238,9 +236,12 @@ const NUMERIC_DISCOVERY_LOOKUP: {[s: string]: KeyValue} = {
|
||||
device_class: "water",
|
||||
state_class: "total_increasing",
|
||||
},
|
||||
x_axis: {icon: "mdi:axis-x-arrow"},
|
||||
y_axis: {icon: "mdi:axis-y-arrow"},
|
||||
z_axis: {icon: "mdi:axis-z-arrow"},
|
||||
x: {icon: "mdi:axis-x-arrow", state_class: "measurement"},
|
||||
x_axis: {icon: "mdi:axis-x-arrow", state_class: "measurement"},
|
||||
y: {icon: "mdi:axis-y-arrow", state_class: "measurement"},
|
||||
y_axis: {icon: "mdi:axis-y-arrow", state_class: "measurement"},
|
||||
z: {icon: "mdi:axis-z-arrow", state_class: "measurement"},
|
||||
z_axis: {icon: "mdi:axis-z-arrow", state_class: "measurement"},
|
||||
} as const;
|
||||
const ENUM_DISCOVERY_LOOKUP: {[s: string]: KeyValue} = {
|
||||
action: {icon: "mdi:gesture-double-tap"},
|
||||
@@ -705,22 +706,58 @@ export class HomeAssistant extends Extension {
|
||||
|
||||
const piHeatingDemand = (firstExpose as zhc.Climate).features.filter(isNumericExpose).find((f) => f.name === "pi_heating_demand");
|
||||
if (piHeatingDemand) {
|
||||
const discoveryEntry: DiscoveryEntry = {
|
||||
type: "sensor",
|
||||
object_id: endpoint ? /* v8 ignore next */ `${piHeatingDemand.name}_${endpoint}` : `${piHeatingDemand.name}`,
|
||||
const discoveryEntry: Partial<DiscoveryEntry> = {
|
||||
object_id: endpoint ? `${piHeatingDemand.name}_${endpoint}` : `${piHeatingDemand.name}`,
|
||||
mockProperties: [{property: piHeatingDemand.property, value: null}],
|
||||
discovery_payload: {
|
||||
name: endpoint ? /* v8 ignore next */ `${piHeatingDemand.label} ${endpoint}` : piHeatingDemand.label,
|
||||
name: endpoint ? `${piHeatingDemand.label} ${endpoint}` : piHeatingDemand.label,
|
||||
value_template: `{{ value_json.${piHeatingDemand.property} }}`,
|
||||
...(piHeatingDemand.unit && {unit_of_measurement: piHeatingDemand.unit}),
|
||||
entity_category: "diagnostic",
|
||||
icon: "mdi:radiator",
|
||||
},
|
||||
};
|
||||
|
||||
assert(discoveryEntry.discovery_payload);
|
||||
|
||||
if (piHeatingDemand.access & ACCESS_SET) {
|
||||
discoveryEntry.type = "number";
|
||||
discoveryEntry.discovery_payload.command_topic = true;
|
||||
discoveryEntry.discovery_payload.command_topic_prefix = endpoint;
|
||||
discoveryEntry.discovery_payload.command_topic_postfix = piHeatingDemand.property;
|
||||
discoveryEntry.discovery_payload.min = piHeatingDemand.value_min;
|
||||
discoveryEntry.discovery_payload.max = piHeatingDemand.value_max;
|
||||
} else {
|
||||
discoveryEntry.type = "sensor";
|
||||
discoveryEntry.discovery_payload.entity_category = "diagnostic";
|
||||
}
|
||||
|
||||
discoveryEntries.push(<DiscoveryEntry>discoveryEntry);
|
||||
}
|
||||
|
||||
const piCoolingDemand = (firstExpose as zhc.Climate).features.filter(isNumericExpose).find((f) => f.name === "pi_cooling_demand");
|
||||
if (piCoolingDemand) {
|
||||
const discoveryEntry: DiscoveryEntry = {
|
||||
type: "sensor",
|
||||
object_id: endpoint ? /* v8 ignore next */ `${piCoolingDemand.name}_${endpoint}` : `${piCoolingDemand.name}`,
|
||||
mockProperties: [{property: piCoolingDemand.property, value: null}],
|
||||
discovery_payload: {
|
||||
name: endpoint ? /* v8 ignore next */ `${piCoolingDemand.label} ${endpoint}` : piCoolingDemand.label,
|
||||
value_template: `{{ value_json.${piCoolingDemand.property} }}`,
|
||||
...(piCoolingDemand.unit && {unit_of_measurement: piCoolingDemand.unit}),
|
||||
entity_category: "diagnostic",
|
||||
icon: "mdi:air-conditioner",
|
||||
},
|
||||
};
|
||||
|
||||
discoveryEntries.push(discoveryEntry);
|
||||
}
|
||||
|
||||
const currentHumidity = allExposes?.filter(isNumericExpose).find((e) => e.name === "humidity" && e.access & ACCESS_STATE);
|
||||
if (currentHumidity) {
|
||||
discoveryEntry.discovery_payload.current_humidity_template = `{{ value_json.${currentHumidity.property} }}`;
|
||||
discoveryEntry.discovery_payload.current_humidity_topic = true;
|
||||
}
|
||||
|
||||
discoveryEntries.push(discoveryEntry);
|
||||
break;
|
||||
}
|
||||
@@ -1220,13 +1257,13 @@ export class HomeAssistant extends Extension {
|
||||
|
||||
@bind async onEntityRemoved(data: eventdata.EntityRemoved): Promise<void> {
|
||||
logger.debug(`Clearing Home Assistant discovery for '${data.name}'`);
|
||||
const discovered = this.getDiscovered(data.id);
|
||||
const discovered = this.getDiscovered(data.entity.ID);
|
||||
|
||||
for (const topic of Object.keys(discovered.messages)) {
|
||||
await this.mqtt.publish(topic, "", {clientOptions: {retain: true, qos: 1}, baseTopic: this.discoveryTopic, skipReceive: false});
|
||||
}
|
||||
|
||||
delete this.discovered[data.id];
|
||||
delete this.discovered[data.entity.ID];
|
||||
}
|
||||
|
||||
@bind async onGroupMembersChanged(data: eventdata.GroupMembersChanged): Promise<void> {
|
||||
@@ -1514,6 +1551,11 @@ export class HomeAssistant extends Extension {
|
||||
payload.object_id = `${payload.object_id}${payload.object_id_postfix ?? ""}`;
|
||||
delete payload.object_id_postfix;
|
||||
|
||||
// Set `default_entity_id`, as of HA 2025.10 this replaces the `object_id`.
|
||||
// For migration purposes we set both for now.
|
||||
// https://github.com/home-assistant/core/pull/151775
|
||||
payload.default_entity_id = `${config.type}.${payload.object_id}`;
|
||||
|
||||
// Set unique_id
|
||||
payload.unique_id = `${entity.options.ID}_${config.object_id}_${settings.get().mqtt.base_topic}`;
|
||||
|
||||
@@ -1639,6 +1681,10 @@ export class HomeAssistant extends Extension {
|
||||
payload.action_topic = stateTopic;
|
||||
}
|
||||
|
||||
if (payload.current_humidity_topic) {
|
||||
payload.current_humidity_topic = stateTopic;
|
||||
}
|
||||
|
||||
// Override configuration with user settings.
|
||||
if (entity.options.homeassistant != null) {
|
||||
const add = (obj: KeyValue, ignoreName: boolean): void => {
|
||||
@@ -1821,6 +1867,10 @@ export class HomeAssistant extends Extension {
|
||||
};
|
||||
|
||||
const url = settings.get().frontend?.url ?? "";
|
||||
// Since zigbee2mqtt-windfront support multiple instances the configuration URL contains the
|
||||
// instance ID. Since we don't know which instance it is we always point to 0.
|
||||
// https://github.com/Koenkk/zigbee2mqtt/issues/28936
|
||||
const urlEntityPostfix = settings.get().frontend.package === "zigbee2mqtt-windfront" ? "0/" : "";
|
||||
if (entity.isDevice()) {
|
||||
assert(entity.definition, `Cannot 'getDevicePayload' for unsupported device`);
|
||||
payload.model = entity.definition.description;
|
||||
@@ -1828,11 +1878,11 @@ export class HomeAssistant extends Extension {
|
||||
payload.manufacturer = entity.definition.vendor;
|
||||
payload.sw_version = entity.zh.softwareBuildID;
|
||||
payload.hw_version = entity.zh.hardwareVersion;
|
||||
payload.configuration_url = `${url}/#/device/${entity.ieeeAddr}/info`;
|
||||
payload.configuration_url = `${url}/#/device/${urlEntityPostfix}${entity.ieeeAddr}/info`;
|
||||
} else if (entity.isGroup()) {
|
||||
payload.model = "Group";
|
||||
payload.manufacturer = "Zigbee2MQTT";
|
||||
payload.configuration_url = `${url}/#/group/${entity.ID}`;
|
||||
payload.configuration_url = `${url}/#/group/${urlEntityPostfix}${entity.ID}`;
|
||||
} else {
|
||||
payload.model = "Bridge";
|
||||
payload.manufacturer = "Zigbee2MQTT";
|
||||
|
||||
+30
-25
@@ -1,8 +1,8 @@
|
||||
import type {Zigbee2MQTTAPI, Zigbee2MQTTNetworkMap} from "../types/api";
|
||||
|
||||
import bind from "bind-decorator";
|
||||
import stringify from "json-stable-stringify-without-jsonify";
|
||||
|
||||
import type {Eui64} from "zigbee-herdsman/dist/zspec/tstypes";
|
||||
import type {LQITableEntry, RoutingTableEntry} from "zigbee-herdsman/dist/zspec/zdo/definition/tstypes";
|
||||
import type {Zigbee2MQTTAPI, Zigbee2MQTTNetworkMap} from "../types/api";
|
||||
import logger from "../util/logger";
|
||||
import * as settings from "../util/settings";
|
||||
import utils from "../util/utils";
|
||||
@@ -14,7 +14,7 @@ const SUPPORTED_FORMATS = ["raw", "graphviz", "plantuml"];
|
||||
* This extension creates a network map
|
||||
*/
|
||||
export default class NetworkMap extends Extension {
|
||||
private topic = `${settings.get().mqtt.base_topic}/bridge/request/networkmap`;
|
||||
#topic = `${settings.get().mqtt.base_topic}/bridge/request/networkmap`;
|
||||
|
||||
// biome-ignore lint/suspicious/useAwait: API
|
||||
override async start(): Promise<void> {
|
||||
@@ -22,7 +22,7 @@ export default class NetworkMap extends Extension {
|
||||
}
|
||||
|
||||
@bind async onMQTTMessage(data: eventdata.MQTTMessage): Promise<void> {
|
||||
if (data.topic === this.topic) {
|
||||
if (data.topic === this.#topic) {
|
||||
const message = utils.parseJSON(data.message, data.message) as Zigbee2MQTTAPI["bridge/request/networkmap"];
|
||||
|
||||
try {
|
||||
@@ -186,8 +186,8 @@ export default class NetworkMap extends Extension {
|
||||
|
||||
async networkScan(includeRoutes: boolean): Promise<Zigbee2MQTTNetworkMap> {
|
||||
logger.info(`Starting network scan (includeRoutes '${includeRoutes}')`);
|
||||
const lqis = new Map<Device, zh.LQI>();
|
||||
const routingTables = new Map<Device, zh.RoutingTable>();
|
||||
const lqis = new Map<Device, LQITableEntry[]>();
|
||||
const routingTables = new Map<Device, RoutingTableEntry[]>();
|
||||
const failed = new Map<Device, string[]>();
|
||||
const requestWithRetry = async <T>(request: () => Promise<T>): Promise<T> => {
|
||||
try {
|
||||
@@ -211,7 +211,7 @@ export default class NetworkMap extends Extension {
|
||||
await utils.sleep(1); // sleep 1 second between each scan to reduce stress on network.
|
||||
|
||||
try {
|
||||
const result = await requestWithRetry<zh.LQI>(async () => await device.zh.lqi());
|
||||
const result = await requestWithRetry<LQITableEntry[]>(async () => await device.zh.lqi());
|
||||
lqis.set(device, result);
|
||||
logger.debug(`LQI succeeded for '${device.name}'`);
|
||||
} catch (error) {
|
||||
@@ -223,7 +223,7 @@ export default class NetworkMap extends Extension {
|
||||
|
||||
if (includeRoutes) {
|
||||
try {
|
||||
const result = await requestWithRetry<zh.RoutingTable>(async () => await device.zh.routingTable());
|
||||
const result = await requestWithRetry<RoutingTableEntry[]>(async () => await device.zh.routingTable());
|
||||
routingTables.set(device, result);
|
||||
logger.debug(`Routing table succeeded for '${device.name}'`);
|
||||
} catch (error) {
|
||||
@@ -275,42 +275,47 @@ export default class NetworkMap extends Extension {
|
||||
}
|
||||
|
||||
// Add links
|
||||
for (const [device, lqi] of lqis) {
|
||||
for (const neighbor of lqi.neighbors) {
|
||||
for (const [device, table] of lqis) {
|
||||
for (const neighbor of table) {
|
||||
if (neighbor.relationship > 3) {
|
||||
// Relationship is not active, skip it
|
||||
continue;
|
||||
}
|
||||
|
||||
let neighborEui64 = neighbor.eui64;
|
||||
|
||||
// Some Xiaomi devices return 0x00 as the neighbor ieeeAddr (obviously not correct).
|
||||
// Determine the correct ieeeAddr based on the networkAddress.
|
||||
if (neighbor.ieeeAddr === "0x0000000000000000") {
|
||||
const neighborDevice = this.zigbee.deviceByNetworkAddress(neighbor.networkAddress);
|
||||
if (neighborEui64 === "0x0000000000000000") {
|
||||
const neighborDevice = this.zigbee.deviceByNetworkAddress(neighbor.nwkAddress);
|
||||
|
||||
if (neighborDevice) {
|
||||
neighbor.ieeeAddr = neighborDevice.ieeeAddr;
|
||||
neighborEui64 = neighborDevice.ieeeAddr as Eui64;
|
||||
}
|
||||
}
|
||||
|
||||
const link: Zigbee2MQTTNetworkMap["links"][number] = {
|
||||
source: {ieeeAddr: neighbor.ieeeAddr, networkAddress: neighbor.networkAddress},
|
||||
source: {ieeeAddr: neighborEui64, networkAddress: neighbor.nwkAddress},
|
||||
target: {ieeeAddr: device.ieeeAddr, networkAddress: device.zh.networkAddress},
|
||||
linkquality: neighbor.linkquality,
|
||||
depth: neighbor.depth,
|
||||
routes: [],
|
||||
// DEPRECATED:
|
||||
sourceIeeeAddr: neighbor.ieeeAddr,
|
||||
targetIeeeAddr: device.ieeeAddr,
|
||||
sourceNwkAddr: neighbor.networkAddress,
|
||||
lqi: neighbor.linkquality,
|
||||
deviceType: neighbor.deviceType,
|
||||
rxOnWhenIdle: neighbor.rxOnWhenIdle,
|
||||
relationship: neighbor.relationship,
|
||||
permitJoining: neighbor.permitJoining,
|
||||
depth: neighbor.depth,
|
||||
lqi: neighbor.lqi,
|
||||
routes: [],
|
||||
// below are @deprecated
|
||||
sourceIeeeAddr: neighborEui64,
|
||||
targetIeeeAddr: device.ieeeAddr,
|
||||
sourceNwkAddr: neighbor.nwkAddress,
|
||||
linkquality: neighbor.lqi,
|
||||
};
|
||||
|
||||
const routingTable = routingTables.get(device);
|
||||
|
||||
if (routingTable) {
|
||||
for (const entry of routingTable.table) {
|
||||
if (entry.status === "ACTIVE" && entry.nextHop === neighbor.networkAddress) {
|
||||
for (const entry of routingTable) {
|
||||
if (entry.nextHopAddress === neighbor.nwkAddress) {
|
||||
link.routes.push(entry);
|
||||
}
|
||||
}
|
||||
|
||||
+37
-25
@@ -1,4 +1,4 @@
|
||||
import {onEvent} from "zigbee-herdsman-converters";
|
||||
import {onEvent, type OnEvent as ZhcOnEvent} from "zigbee-herdsman-converters";
|
||||
|
||||
import utils from "../util/utils";
|
||||
import Extension from "./extension";
|
||||
@@ -7,42 +7,50 @@ import Extension from "./extension";
|
||||
* This extension calls the zigbee-herdsman-converters onEvent.
|
||||
*/
|
||||
export default class OnEvent extends Extension {
|
||||
readonly #startCalled: Set<string> = new Set();
|
||||
|
||||
#getOnEventBaseData(device: Device): ZhcOnEvent.BaseData {
|
||||
const deviceExposesChanged = (): void => this.eventBus.emitExposesAndDevicesChanged(device);
|
||||
const state = this.state.get(device);
|
||||
const options = device.options as KeyValue;
|
||||
return {deviceExposesChanged, device: device.zh, state, options};
|
||||
}
|
||||
|
||||
// biome-ignore lint/suspicious/useAwait: API
|
||||
override async start(): Promise<void> {
|
||||
for (const device of this.zigbee.devicesIterator(utils.deviceNotCoordinator)) {
|
||||
// don't await, in case of repeated failures this would hold startup
|
||||
this.callOnEvent(device, "start", {}).catch(utils.noop);
|
||||
this.callOnEvent(device, {type: "start", data: this.#getOnEventBaseData(device)}).catch(utils.noop);
|
||||
}
|
||||
|
||||
this.eventBus.onDeviceMessage(this, async (data) => {
|
||||
await this.callOnEvent(data.device, "message", {
|
||||
endpoint: data.endpoint,
|
||||
meta: data.meta,
|
||||
cluster: typeof data.cluster === "string" ? data.cluster : /* v8 ignore next */ undefined, // XXX: ZH typing is wrong?
|
||||
type: data.type,
|
||||
data: data.data, // XXX: typing is a bit convoluted: ZHC has `KeyValueAny` here while Z2M has `KeyValue | Array<string | number>`
|
||||
});
|
||||
});
|
||||
this.eventBus.onDeviceJoined(this, async (data) => {
|
||||
await this.callOnEvent(data.device, "deviceJoined", {});
|
||||
await this.callOnEvent(data.device, {type: "deviceJoined", data: this.#getOnEventBaseData(data.device)});
|
||||
});
|
||||
this.eventBus.onDeviceLeave(this, async (data) => {
|
||||
if (data.device) {
|
||||
await this.callOnEvent(data.device, "stop", {});
|
||||
await this.callOnEvent(data.device, {type: "stop", data: {ieeeAddr: data.device.ieeeAddr}});
|
||||
}
|
||||
});
|
||||
this.eventBus.onEntityRemoved(this, async (data) => {
|
||||
if (data.entity.isDevice()) {
|
||||
await this.callOnEvent(data.entity, {type: "stop", data: {ieeeAddr: data.entity.ieeeAddr}});
|
||||
}
|
||||
});
|
||||
this.eventBus.onDeviceInterview(this, async (data) => {
|
||||
await this.callOnEvent(data.device, "deviceInterview", {});
|
||||
await this.callOnEvent(data.device, {type: "deviceInterview", data: {...this.#getOnEventBaseData(data.device), status: data.status}});
|
||||
});
|
||||
this.eventBus.onDeviceAnnounce(this, async (data) => {
|
||||
await this.callOnEvent(data.device, "deviceAnnounce", {});
|
||||
await this.callOnEvent(data.device, {type: "deviceAnnounce", data: this.#getOnEventBaseData(data.device)});
|
||||
});
|
||||
this.eventBus.onDeviceNetworkAddressChanged(this, async (data) => {
|
||||
await this.callOnEvent(data.device, "deviceNetworkAddressChanged", {});
|
||||
await this.callOnEvent(data.device, {type: "deviceNetworkAddressChanged", data: this.#getOnEventBaseData(data.device)});
|
||||
});
|
||||
this.eventBus.onEntityOptionsChanged(this, async (data) => {
|
||||
if (data.entity.isDevice()) {
|
||||
await this.callOnEvent(data.entity, "deviceOptionsChanged", {});
|
||||
await this.callOnEvent(data.entity, {
|
||||
type: "deviceOptionsChanged",
|
||||
data: {...this.#getOnEventBaseData(data.entity), from: data.from, to: data.to},
|
||||
});
|
||||
this.eventBus.emitDevicesChanged();
|
||||
}
|
||||
});
|
||||
@@ -52,23 +60,27 @@ export default class OnEvent extends Extension {
|
||||
await super.stop();
|
||||
|
||||
for (const device of this.zigbee.devicesIterator(utils.deviceNotCoordinator)) {
|
||||
await this.callOnEvent(device, "stop", {});
|
||||
await this.callOnEvent(device, {type: "stop", data: {ieeeAddr: device.ieeeAddr}});
|
||||
}
|
||||
}
|
||||
|
||||
private async callOnEvent(device: Device, type: Parameters<typeof onEvent>[0], data: Parameters<typeof onEvent>[1]): Promise<void> {
|
||||
private async callOnEvent(device: Device, event: ZhcOnEvent.Event): Promise<void> {
|
||||
if (device.options.disabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
const state = this.state.get(device);
|
||||
const deviceExposesChanged = (): void => this.eventBus.emitExposesAndDevicesChanged(device);
|
||||
if (event.type === "start") {
|
||||
this.#startCalled.add(device.ieeeAddr);
|
||||
} else if (event.type !== "stop" && !this.#startCalled.has(device.ieeeAddr) && device.definition?.onEvent) {
|
||||
this.#startCalled.add(device.ieeeAddr);
|
||||
await device.definition.onEvent({type: "start", data: this.#getOnEventBaseData(device)});
|
||||
}
|
||||
|
||||
await onEvent(type, data, device.zh, {deviceExposesChanged});
|
||||
await onEvent(event);
|
||||
await device.definition?.onEvent?.(event);
|
||||
|
||||
if (device.definition?.onEvent) {
|
||||
const options: KeyValue = device.options;
|
||||
await device.definition.onEvent(type, data, device.zh, options, state, {deviceExposesChanged});
|
||||
if (event.type === "stop") {
|
||||
this.#startCalled.delete(device.ieeeAddr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +1,12 @@
|
||||
import type {Ota} from "zigbee-herdsman-converters";
|
||||
|
||||
import type {Zigbee2MQTTAPI} from "../types/api";
|
||||
|
||||
import assert from "node:assert";
|
||||
import path from "node:path";
|
||||
|
||||
import bind from "bind-decorator";
|
||||
import stringify from "json-stable-stringify-without-jsonify";
|
||||
|
||||
import {Zcl} from "zigbee-herdsman";
|
||||
import type {Ota} from "zigbee-herdsman-converters";
|
||||
import {ota} from "zigbee-herdsman-converters";
|
||||
|
||||
import Device from "../model/device";
|
||||
import type {Zigbee2MQTTAPI} from "../types/api";
|
||||
import dataDir from "../util/data";
|
||||
import logger from "../util/logger";
|
||||
import * as settings from "../util/settings";
|
||||
@@ -30,12 +25,11 @@ export interface UpdatePayload {
|
||||
};
|
||||
}
|
||||
|
||||
const topicRegex = new RegExp(
|
||||
`^${settings.get().mqtt.base_topic}/bridge/request/device/ota_update/(update|check|schedule|unschedule)/?(downgrade)?`,
|
||||
"i",
|
||||
);
|
||||
|
||||
export default class OTAUpdate extends Extension {
|
||||
#topicRegex = new RegExp(
|
||||
`^${settings.get().mqtt.base_topic}/bridge/request/device/ota_update/(update|check|schedule|unschedule)/?(downgrade)?`,
|
||||
"i",
|
||||
);
|
||||
private inProgress = new Set<string>();
|
||||
private lastChecked = new Map<string, number>();
|
||||
private scheduledUpgrades = new Set<string>();
|
||||
@@ -257,7 +251,7 @@ export default class OTAUpdate extends Extension {
|
||||
}
|
||||
|
||||
@bind async onMQTTMessage(data: eventdata.MQTTMessage): Promise<void> {
|
||||
const topicMatch = data.topic.match(topicRegex);
|
||||
const topicMatch = data.topic.match(this.#topicRegex);
|
||||
|
||||
if (!topicMatch) {
|
||||
return;
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import type * as zhc from "zigbee-herdsman-converters";
|
||||
|
||||
import bind from "bind-decorator";
|
||||
import stringify from "json-stable-stringify-without-jsonify";
|
||||
import type * as zhc from "zigbee-herdsman-converters";
|
||||
|
||||
import Device from "../model/device";
|
||||
import Group from "../model/group";
|
||||
@@ -10,12 +9,12 @@ import * as settings from "../util/settings";
|
||||
import utils from "../util/utils";
|
||||
import Extension from "./extension";
|
||||
|
||||
// TODO: get rid of this, use class member
|
||||
let topicGetSetRegex: RegExp;
|
||||
// Used by `publish.test.js` to reload regex when changing `mqtt.base_topic`.
|
||||
// Used by `publish.test.ts` to reload regex when changing `mqtt.base_topic`.
|
||||
export const loadTopicGetSetRegex = (): void => {
|
||||
topicGetSetRegex = new RegExp(`^${settings.get().mqtt.base_topic}/(?!bridge)(.+?)/(get|set)(?:/(.+))?$`);
|
||||
};
|
||||
loadTopicGetSetRegex();
|
||||
|
||||
const STATE_VALUES: ReadonlyArray<string> = ["on", "off", "toggle", "open", "close", "stop", "lock", "unlock"];
|
||||
const SCENE_CONVERTER_KEYS: ReadonlyArray<string> = ["scene_store", "scene_add", "scene_remove", "scene_remove_all", "scene_rename"];
|
||||
@@ -30,6 +29,7 @@ interface ParsedTopic {
|
||||
export default class Publish extends Extension {
|
||||
// biome-ignore lint/suspicious/useAwait: API
|
||||
override async start(): Promise<void> {
|
||||
loadTopicGetSetRegex();
|
||||
this.eventBus.onMQTTMessage(this, this.onMQTTMessage);
|
||||
}
|
||||
|
||||
|
||||
@@ -136,7 +136,7 @@ export default class Receive extends Extension {
|
||||
const publish = async (payload: KeyValue): Promise<void> => {
|
||||
assert(data.device.definition);
|
||||
const options: KeyValue = data.device.options;
|
||||
zhc.postProcessConvertedFromZigbeeMessage(data.device.definition, payload, options);
|
||||
zhc.postProcessConvertedFromZigbeeMessage(data.device.definition, payload, options, data.device.zh);
|
||||
|
||||
if (settings.get().advanced.elapsed) {
|
||||
const now = Date.now();
|
||||
|
||||
+20
-30
@@ -1,10 +1,8 @@
|
||||
import type {CustomClusters} from "zigbee-herdsman/dist/zspec/zcl/definition/tstype";
|
||||
|
||||
import assert from "node:assert";
|
||||
|
||||
import * as zhc from "zigbee-herdsman-converters";
|
||||
import {Numeric, access} from "zigbee-herdsman-converters";
|
||||
import {InterviewState} from "zigbee-herdsman/dist/controller/model/device";
|
||||
import type {CustomClusters} from "zigbee-herdsman/dist/zspec/zcl/definition/tstype";
|
||||
import * as zhc from "zigbee-herdsman-converters";
|
||||
import {access, Numeric} from "zigbee-herdsman-converters";
|
||||
|
||||
import * as settings from "../util/settings";
|
||||
|
||||
@@ -78,43 +76,33 @@ export default class Device {
|
||||
}
|
||||
|
||||
endpoint(key?: string | number): zh.Endpoint | undefined {
|
||||
let endpoint: zh.Endpoint | undefined;
|
||||
|
||||
if (!key) {
|
||||
key = "default";
|
||||
} else if (!Number.isNaN(Number(key))) {
|
||||
return this.zh.getEndpoint(Number(key));
|
||||
}
|
||||
|
||||
if (!Number.isNaN(Number(key))) {
|
||||
endpoint = this.zh.getEndpoint(Number(key));
|
||||
} else if (this.definition?.endpoint) {
|
||||
const ID = this.definition?.endpoint?.(this.zh)[key];
|
||||
if (this.definition?.endpoint) {
|
||||
const ID = this.definition.endpoint(this.zh)[key];
|
||||
|
||||
if (ID) {
|
||||
endpoint = this.zh.getEndpoint(ID);
|
||||
} else if (key === "default") {
|
||||
endpoint = this.zh.endpoints[0];
|
||||
} else {
|
||||
return undefined;
|
||||
return this.zh.getEndpoint(ID);
|
||||
}
|
||||
} else {
|
||||
if (key !== "default") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
endpoint = this.zh.endpoints[0];
|
||||
}
|
||||
|
||||
return endpoint;
|
||||
return key === "default" ? this.zh.endpoints[0] : undefined;
|
||||
}
|
||||
|
||||
endpointName(endpoint: zh.Endpoint): string | undefined {
|
||||
let epName = undefined;
|
||||
let epName: string | undefined;
|
||||
|
||||
if (this.definition?.endpoint) {
|
||||
const mapping = this.definition?.endpoint(this.zh);
|
||||
for (const [name, id] of Object.entries(mapping)) {
|
||||
if (id === endpoint.ID) {
|
||||
const mapping = this.definition.endpoint(this.zh);
|
||||
|
||||
for (const name in mapping) {
|
||||
if (mapping[name] === endpoint.ID) {
|
||||
epName = name;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -126,9 +114,11 @@ export default class Device {
|
||||
getEndpointNames(): string[] {
|
||||
const names: string[] = [];
|
||||
|
||||
for (const name in this.definition?.endpoint?.(this.zh) ?? {}) {
|
||||
if (name !== "default") {
|
||||
names.push(name);
|
||||
if (this.definition?.endpoint) {
|
||||
for (const name in this.definition.endpoint(this.zh)) {
|
||||
if (name !== "default") {
|
||||
names.push(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+7
-1
@@ -1,6 +1,6 @@
|
||||
import type * as zhc from "zigbee-herdsman-converters";
|
||||
|
||||
import * as settings from "../util/settings";
|
||||
import {DEFAULT_BIND_GROUP_ID} from "../util/utils";
|
||||
|
||||
export default class Group {
|
||||
public zh: zh.Group;
|
||||
@@ -23,6 +23,12 @@ export default class Group {
|
||||
this.resolveDevice = resolveDevice;
|
||||
}
|
||||
|
||||
ensureInSettings(): void {
|
||||
if (this.ID !== DEFAULT_BIND_GROUP_ID && !settings.getGroup(this.ID)) {
|
||||
settings.addGroup(this.name, this.ID.toString());
|
||||
}
|
||||
}
|
||||
|
||||
hasMember(device: Device): boolean {
|
||||
return !!device.zh.endpoints.find((e) => this.zh.members.includes(e));
|
||||
}
|
||||
|
||||
+21
-11
@@ -1,11 +1,8 @@
|
||||
import type {IClientOptions, IClientPublishOptions, MqttClient} from "mqtt";
|
||||
|
||||
import type {Zigbee2MQTTAPI} from "./types/api";
|
||||
|
||||
import fs from "node:fs";
|
||||
|
||||
import bind from "bind-decorator";
|
||||
import type {IClientOptions, IClientPublishOptions, MqttClient} from "mqtt";
|
||||
import {connectAsync} from "mqtt";
|
||||
import type {Zigbee2MQTTAPI} from "./types/api";
|
||||
|
||||
import logger from "./util/logger";
|
||||
import * as settings from "./util/settings";
|
||||
@@ -30,6 +27,20 @@ export default class Mqtt {
|
||||
private defaultPublishOptions: MqttPublishOptions;
|
||||
public retainedMessages: {[s: string]: {topic: string; payload: string; options: MqttPublishOptions}} = {};
|
||||
|
||||
get info() {
|
||||
return {
|
||||
version: this.client.options.protocolVersion,
|
||||
server: `${this.client.options.protocol}://${this.client.options.host}:${this.client.options.port}`,
|
||||
};
|
||||
}
|
||||
|
||||
get stats() {
|
||||
return {
|
||||
connected: this.isConnected(),
|
||||
queued: this.client.queue.length,
|
||||
};
|
||||
}
|
||||
|
||||
constructor(eventBus: EventBus) {
|
||||
this.eventBus = eventBus;
|
||||
this.defaultPublishOptions = {
|
||||
@@ -160,7 +171,7 @@ export default class Mqtt {
|
||||
|
||||
const stateData: Zigbee2MQTTAPI["bridge/state"] = {state: "online"};
|
||||
|
||||
await this.publish("bridge/state", JSON.stringify(stateData), {clientOptions: {retain: true}});
|
||||
await this.publish("bridge/state", JSON.stringify(stateData), {clientOptions: {retain: true, qos: 1}});
|
||||
await this.subscribe(`${settings.get().mqtt.base_topic}/#`);
|
||||
}
|
||||
|
||||
@@ -211,19 +222,18 @@ export default class Mqtt {
|
||||
logger.error("Not connected to MQTT server!");
|
||||
logger.error(`Cannot send message: topic: '${topic}', payload: '${payload}`);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (!finalOptions.skipLog) {
|
||||
logger.info(() => `MQTT publish: topic '${topic}', payload '${payload}'`, NS);
|
||||
}
|
||||
|
||||
let clientOptions: IClientPublishOptions = finalOptions.clientOptions;
|
||||
if (settings.get().mqtt.force_disable_retain) {
|
||||
clientOptions = {...finalOptions.clientOptions, retain: false};
|
||||
}
|
||||
|
||||
if (!finalOptions.skipLog) {
|
||||
logger.info(() => `MQTT publish: topic '${topic}', payload '${payload}'`, NS);
|
||||
}
|
||||
|
||||
try {
|
||||
await this.client.publishAsync(topic, payload, clientOptions);
|
||||
} catch (error) {
|
||||
|
||||
+117
-26
@@ -1,7 +1,10 @@
|
||||
import type * as zigbeeHerdsman from "zigbee-herdsman/dist";
|
||||
import type {ZclPayload} from "zigbee-herdsman/dist/adapter/events";
|
||||
import type {Eui64} from "zigbee-herdsman/dist/zspec/tstypes";
|
||||
import type {ClusterDefinition, ClusterName, CustomClusters} from "zigbee-herdsman/dist/zspec/zcl/definition/tstype";
|
||||
import type {GenericZdoResponse, RoutingTableEntry} from "zigbee-herdsman/dist/zspec/zdo/definition/tstypes";
|
||||
import type * as zigbeeHerdsmanConverter from "zigbee-herdsman-converters";
|
||||
import type {Base} from "zigbee-herdsman-converters/lib/exposes";
|
||||
import type * as zigbeeHerdsman from "zigbee-herdsman/dist";
|
||||
import type {ClusterDefinition, ClusterName, CustomClusters} from "zigbee-herdsman/dist/zspec/zcl/definition/tstype";
|
||||
|
||||
export type * as ZSpec from "zigbee-herdsman/dist/zspec";
|
||||
export type * as Zcl from "zigbee-herdsman/dist/zspec/zcl";
|
||||
@@ -151,6 +154,7 @@ export interface Zigbee2MQTTSettings {
|
||||
ssl_cert?: string;
|
||||
ssl_key?: string;
|
||||
notification_filter?: string[];
|
||||
disable_ui_serving?: boolean;
|
||||
};
|
||||
devices: {[s: string]: Zigbee2MQTTDeviceOptions};
|
||||
groups: {[s: string]: Omit<Zigbee2MQTTGroupOptions, "ID">};
|
||||
@@ -183,6 +187,11 @@ export interface Zigbee2MQTTSettings {
|
||||
output: "json" | "attribute" | "attribute_and_json";
|
||||
transmit_power?: number;
|
||||
};
|
||||
health: {
|
||||
/** in minutes */
|
||||
interval: number;
|
||||
reset_on_check: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
export interface Zigbee2MQTTScene {
|
||||
@@ -191,6 +200,7 @@ export interface Zigbee2MQTTScene {
|
||||
}
|
||||
|
||||
export interface Zigbee2MQTTDeviceEndpoint {
|
||||
name?: string;
|
||||
bindings: Zigbee2MQTTDeviceEndpointBinding[];
|
||||
configured_reportings: Zigbee2MQTTDeviceEndpointConfiguredReporting[];
|
||||
clusters: {input: string[]; output: string[]};
|
||||
@@ -213,6 +223,7 @@ export interface Zigbee2MQTTDeviceEndpointConfiguredReporting {
|
||||
}
|
||||
|
||||
export interface Zigbee2MQTTDeviceDefinition {
|
||||
source: "native" | "generated" | "external";
|
||||
model: string;
|
||||
vendor: string;
|
||||
description: string;
|
||||
@@ -229,8 +240,8 @@ export interface Zigbee2MQTTDevice {
|
||||
supported: boolean;
|
||||
friendly_name: string;
|
||||
disabled: boolean;
|
||||
description: string | undefined;
|
||||
definition: Zigbee2MQTTDeviceDefinition | undefined;
|
||||
description?: string;
|
||||
definition?: Zigbee2MQTTDeviceDefinition;
|
||||
power_source: zigbeeHerdsman.Models.Device["powerSource"];
|
||||
software_build_id: zigbeeHerdsman.Models.Device["softwareBuildID"];
|
||||
date_code: zigbeeHerdsman.Models.Device["dateCode"];
|
||||
@@ -250,7 +261,7 @@ export interface Zigbee2MQTTGroupMember {
|
||||
export interface Zigbee2MQTTGroup {
|
||||
id: number;
|
||||
friendly_name: "default_bind_group" | string;
|
||||
description: string | undefined;
|
||||
description?: string;
|
||||
scenes: Zigbee2MQTTScene[];
|
||||
members: Zigbee2MQTTGroupMember[];
|
||||
}
|
||||
@@ -261,27 +272,30 @@ export interface Zigbee2MQTTNetworkMap {
|
||||
friendlyName: string;
|
||||
type: string;
|
||||
networkAddress: number;
|
||||
manufacturerName: string | undefined;
|
||||
modelID: string | undefined;
|
||||
manufacturerName?: string;
|
||||
modelID?: string;
|
||||
failed?: string[];
|
||||
lastSeen: number | undefined;
|
||||
lastSeen?: number;
|
||||
definition?: {model: string; vendor: string; supports: string; description: string};
|
||||
}[];
|
||||
links: {
|
||||
source: {ieeeAddr: string; networkAddress: number};
|
||||
target: {ieeeAddr: string; networkAddress: number};
|
||||
linkquality: number;
|
||||
depth: number;
|
||||
routes: {
|
||||
destinationAddress: number;
|
||||
status: string;
|
||||
nextHop: number;
|
||||
}[];
|
||||
sourceIeeeAddr: string;
|
||||
targetIeeeAddr: string;
|
||||
sourceNwkAddr: number;
|
||||
lqi: number;
|
||||
deviceType: number;
|
||||
rxOnWhenIdle: number;
|
||||
relationship: number;
|
||||
permitJoining: number;
|
||||
depth: number;
|
||||
lqi: number;
|
||||
routes: RoutingTableEntry[];
|
||||
/** @deprecated 3.0 */
|
||||
linkquality: number;
|
||||
/** @deprecated 3.0 */
|
||||
sourceIeeeAddr: string;
|
||||
/** @deprecated 3.0 */
|
||||
targetIeeeAddr: string;
|
||||
/** @deprecated 3.0 */
|
||||
sourceNwkAddr: number;
|
||||
}[];
|
||||
}
|
||||
|
||||
@@ -302,6 +316,7 @@ export interface Zigbee2MQTTAPI {
|
||||
"bridge/definitions": {
|
||||
clusters: Readonly<Record<ClusterName, Readonly<ClusterDefinition>>>;
|
||||
custom_clusters: Record<string, CustomClusters>;
|
||||
actions: string[];
|
||||
};
|
||||
|
||||
"bridge/event":
|
||||
@@ -330,6 +345,16 @@ export interface Zigbee2MQTTAPI {
|
||||
};
|
||||
|
||||
"bridge/info": {
|
||||
os: {
|
||||
version: string;
|
||||
node_version: string;
|
||||
cpus: string;
|
||||
memory_mb: number;
|
||||
};
|
||||
mqtt: {
|
||||
version: number | undefined;
|
||||
server: string;
|
||||
};
|
||||
version: string;
|
||||
commit: string | undefined;
|
||||
zigbee_herdsman_converters: {version: string};
|
||||
@@ -355,6 +380,36 @@ export interface Zigbee2MQTTAPI {
|
||||
config_schema: typeof schemaJson;
|
||||
};
|
||||
|
||||
"bridge/health": {
|
||||
/** time of message, msec from epoch, UTC */
|
||||
response_time: number;
|
||||
os: {
|
||||
load_average: number[];
|
||||
memory_used_mb: number;
|
||||
memory_percent: number;
|
||||
};
|
||||
process: {
|
||||
uptime_sec: number;
|
||||
memory_used_mb: number;
|
||||
memory_percent: number;
|
||||
};
|
||||
mqtt: {
|
||||
connected: boolean;
|
||||
queued: number;
|
||||
received: number;
|
||||
published: number;
|
||||
};
|
||||
devices: Record<
|
||||
string /* ieee */,
|
||||
{
|
||||
messages: number;
|
||||
messages_per_sec: number;
|
||||
leave_count: number;
|
||||
network_address_changes: number;
|
||||
}
|
||||
>;
|
||||
};
|
||||
|
||||
"bridge/devices": Zigbee2MQTTDevice[];
|
||||
|
||||
"bridge/groups": Zigbee2MQTTGroup[];
|
||||
@@ -510,6 +565,16 @@ export interface Zigbee2MQTTAPI {
|
||||
failed: string[];
|
||||
};
|
||||
|
||||
"bridge/request/device/binds/clear": {
|
||||
target: string;
|
||||
ieee_list?: Eui64[];
|
||||
};
|
||||
|
||||
"bridge/response/device/binds/clear": {
|
||||
target: string;
|
||||
ieee_list?: Eui64[];
|
||||
};
|
||||
|
||||
"bridge/request/device/configure":
|
||||
| {
|
||||
id: string | number;
|
||||
@@ -638,25 +703,41 @@ export interface Zigbee2MQTTAPI {
|
||||
homeassistant_rename: boolean;
|
||||
};
|
||||
|
||||
"bridge/request/device/configure_reporting": {
|
||||
"bridge/request/device/reporting/configure": {
|
||||
id: string;
|
||||
endpoint: string | number;
|
||||
cluster: string | number;
|
||||
attribute: string | number | {ID: number; type: number};
|
||||
minimum_report_interval: number;
|
||||
maximum_report_interval: number;
|
||||
reportable_change: number;
|
||||
reportable_change?: number;
|
||||
option: Record<string, unknown>;
|
||||
};
|
||||
|
||||
"bridge/response/device/configure_reporting": {
|
||||
"bridge/response/device/reporting/configure": {
|
||||
id: string;
|
||||
endpoint: string | number;
|
||||
cluster: string | number;
|
||||
attribute: string | number | {ID: number; type: number};
|
||||
minimum_report_interval: number;
|
||||
maximum_report_interval: number;
|
||||
reportable_change: number;
|
||||
reportable_change?: number;
|
||||
};
|
||||
|
||||
"bridge/request/device/reporting/read": {
|
||||
id: string;
|
||||
endpoint: string | number;
|
||||
cluster: string | number;
|
||||
configs: {direction?: number; attribute: string | number | {ID: number; type: number}}[];
|
||||
manufacturer_code?: number;
|
||||
};
|
||||
|
||||
"bridge/response/device/reporting/read": {
|
||||
id: string;
|
||||
endpoint: string | number;
|
||||
cluster: string | number;
|
||||
configs: zigbeeHerdsman.Zcl.ClustersTypes.TFoundation["readReportConfigRsp"];
|
||||
manufacturer_code?: number;
|
||||
};
|
||||
|
||||
"bridge/request/group/remove": {
|
||||
@@ -773,6 +854,10 @@ export interface Zigbee2MQTTAPI {
|
||||
channel: number;
|
||||
};
|
||||
|
||||
"bridge/request/action": {action: string; params?: Record<string, unknown>};
|
||||
|
||||
"bridge/response/action": GenericZdoResponse | ZclPayload | undefined;
|
||||
|
||||
/**
|
||||
* entity state response
|
||||
*/
|
||||
@@ -835,6 +920,7 @@ export type Zigbee2MQTTRequestEndpoints =
|
||||
| "bridge/request/options"
|
||||
| "bridge/request/device/bind"
|
||||
| "bridge/request/device/unbind"
|
||||
| "bridge/request/device/binds/clear"
|
||||
| "bridge/request/device/configure"
|
||||
| "bridge/request/device/remove"
|
||||
| "bridge/request/device/ota_update/check"
|
||||
@@ -848,7 +934,8 @@ export type Zigbee2MQTTRequestEndpoints =
|
||||
| "bridge/request/device/generate_external_definition"
|
||||
| "bridge/request/device/options"
|
||||
| "bridge/request/device/rename"
|
||||
| "bridge/request/device/configure_reporting"
|
||||
| "bridge/request/device/reporting/configure"
|
||||
| "bridge/request/device/reporting/read"
|
||||
| "bridge/request/group/remove"
|
||||
| "bridge/request/group/add"
|
||||
| "bridge/request/group/rename"
|
||||
@@ -859,6 +946,7 @@ export type Zigbee2MQTTRequestEndpoints =
|
||||
| "bridge/request/touchlink/factory_reset"
|
||||
| "bridge/request/touchlink/scan"
|
||||
| "bridge/request/touchlink/identify"
|
||||
| "bridge/request/action"
|
||||
| "{friendlyNameOrId}/set"
|
||||
| "{friendlyNameOrId}/set/{attribute}"
|
||||
| "{friendlyNameOrId}/{endpoint}/set"
|
||||
@@ -883,6 +971,7 @@ export type Zigbee2MQTTResponseEndpoints =
|
||||
| "bridge/response/options"
|
||||
| "bridge/response/device/bind"
|
||||
| "bridge/response/device/unbind"
|
||||
| "bridge/response/device/binds/clear"
|
||||
| "bridge/response/device/configure"
|
||||
| "bridge/response/device/remove"
|
||||
| "bridge/response/device/ota_update/check"
|
||||
@@ -893,7 +982,8 @@ export type Zigbee2MQTTResponseEndpoints =
|
||||
| "bridge/response/device/generate_external_definition"
|
||||
| "bridge/response/device/options"
|
||||
| "bridge/response/device/rename"
|
||||
| "bridge/response/device/configure_reporting"
|
||||
| "bridge/response/device/reporting/configure"
|
||||
| "bridge/response/device/reporting/read"
|
||||
| "bridge/response/group/remove"
|
||||
| "bridge/response/group/add"
|
||||
| "bridge/response/group/rename"
|
||||
@@ -903,7 +993,8 @@ export type Zigbee2MQTTResponseEndpoints =
|
||||
| "bridge/response/group/members/remove_all"
|
||||
| "bridge/response/touchlink/factory_reset"
|
||||
| "bridge/response/touchlink/scan"
|
||||
| "bridge/response/touchlink/identify";
|
||||
| "bridge/response/touchlink/identify"
|
||||
| "bridge/response/action";
|
||||
|
||||
export type Zigbee2MQTTRequest<T extends Zigbee2MQTTRequestEndpoints> = {
|
||||
transaction?: string;
|
||||
|
||||
Vendored
+18
@@ -0,0 +1,18 @@
|
||||
// minimal required because of sub-deps in mqtt >= 5.14.0 to avoid requiring `dom` type
|
||||
declare global {
|
||||
// map to node, doesn't really matter, just needs to be there, and the right "type vs value" to avoid lib check problems
|
||||
/** @deprecated DOM SHIM, DO NOT USE */
|
||||
type MessagePort = import("node:worker_threads").MessagePort;
|
||||
/** @deprecated DOM SHIM, DO NOT USE */
|
||||
type Worker = import("node:worker_threads").Worker;
|
||||
/** @deprecated DOM SHIM, DO NOT USE */
|
||||
type Transferable = import("node:worker_threads").Transferable;
|
||||
/** @deprecated DOM SHIM, DO NOT USE */
|
||||
const addEventListener: import("node:events").EventEmitter["addListener"];
|
||||
/** @deprecated DOM SHIM, DO NOT USE */
|
||||
const removeEventListener: import("node:events").EventEmitter["removeListener"];
|
||||
/** @deprecated DOM SHIM, DO NOT USE */
|
||||
const postMessage: import("node:worker_threads").MessagePort["postMessage"];
|
||||
}
|
||||
|
||||
export {};
|
||||
Vendored
+2
-5
@@ -36,9 +36,6 @@ declare global {
|
||||
type Endpoint = ZHModels.Endpoint;
|
||||
type Device = ZHModels.Device;
|
||||
type Group = ZHModels.Group;
|
||||
// biome-ignore lint/style/useNamingConvention: API
|
||||
type LQI = ZHAdapterTypes.Lqi;
|
||||
type RoutingTable = ZHAdapterTypes.RoutingTable;
|
||||
type CoordinatorVersion = ZHAdapterTypes.CoordinatorVersion;
|
||||
type NetworkParameters = ZHAdapterTypes.NetworkParameters;
|
||||
interface Bind {
|
||||
@@ -49,7 +46,7 @@ declare global {
|
||||
|
||||
namespace eventdata {
|
||||
type EntityRenamed = {entity: Device | Group; homeAssisantRename: boolean; from: string; to: string};
|
||||
type EntityRemoved = {id: string; name: string; type: "device"} | {id: number; name: string; type: "group"};
|
||||
type EntityRemoved = {entity: Device | Group; name: string};
|
||||
type MQTTMessage = {topic: string; message: string};
|
||||
type MQTTMessagePublished = {topic: string; payload: string; options: MqttPublishOptions};
|
||||
type StateChange = {
|
||||
@@ -82,7 +79,7 @@ declare global {
|
||||
groupID: number; // XXX: should this be `?`
|
||||
cluster: string | number;
|
||||
data: KeyValue | Array<string | number>;
|
||||
meta: {zclTransactionSequenceNumber?: number; manufacturerCode?: number; frameControl?: ZHFrameControl};
|
||||
meta: {zclTransactionSequenceNumber?: number; manufacturerCode?: number; frameControl?: ZHFrameControl; rawData: Buffer};
|
||||
};
|
||||
type ScenesChanged = {entity: Device | Group};
|
||||
}
|
||||
|
||||
Vendored
-7
@@ -12,10 +12,3 @@ declare module "http" {
|
||||
path?: string;
|
||||
}
|
||||
}
|
||||
|
||||
declare module "express-static-gzip" {
|
||||
import type {IncomingMessage, ServerResponse} from "node:http";
|
||||
|
||||
export type RequestHandler = (req: IncomingMessage, res: ServerResponse, finalhandler: (err: unknown) => void) => void;
|
||||
export default function expressStaticGzip(root: string, options?: Record<string, unknown>): RequestHandler;
|
||||
}
|
||||
|
||||
@@ -18,4 +18,5 @@ function _testReload(): void {
|
||||
dataPath = setPath();
|
||||
}
|
||||
|
||||
// biome-ignore lint/style/useNamingConvention: test
|
||||
export default {joinPath, getPath, _testReload};
|
||||
|
||||
+5
-6
@@ -2,10 +2,8 @@ import assert from "node:assert";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import moment from "moment";
|
||||
import {rimrafSync} from "rimraf";
|
||||
import winston from "winston";
|
||||
|
||||
import * as settings from "./settings";
|
||||
|
||||
const NAMESPACE_SEPARATOR = ":";
|
||||
@@ -31,7 +29,7 @@ class Logger {
|
||||
// What transports to enable
|
||||
this.output = settings.get().advanced.log_output;
|
||||
// Directory to log to
|
||||
const timestamp = moment(Date.now()).format("YYYY-MM-DD.HH-mm-ss");
|
||||
const timestamp = new Date().toISOString().slice(0, 19).replace("T", ".").replace(/:/g, "-");
|
||||
this.directory = settings.get().advanced.log_directory.replace("%TIMESTAMP%", timestamp);
|
||||
const logFilename = settings.get().advanced.log_file.replace("%TIMESTAMP%", timestamp);
|
||||
this.level = settings.get().advanced.log_level;
|
||||
@@ -40,11 +38,12 @@ class Logger {
|
||||
|
||||
assert(settings.LOG_LEVELS.includes(this.level), `'${this.level}' is not valid log_level, use one of '${settings.LOG_LEVELS.join(", ")}'`);
|
||||
|
||||
const timestampFormat = (): string => moment().format(settings.get().advanced.timestamp_format);
|
||||
|
||||
this.logger = winston.createLogger({
|
||||
level: "debug",
|
||||
format: winston.format.combine(winston.format.errors({stack: true}), winston.format.timestamp({format: timestampFormat})),
|
||||
format: winston.format.combine(
|
||||
winston.format.errors({stack: true}),
|
||||
winston.format.timestamp({format: settings.get().advanced.timestamp_format}),
|
||||
),
|
||||
levels: winston.config.syslog.levels,
|
||||
});
|
||||
|
||||
|
||||
+60
-28
@@ -1,11 +1,10 @@
|
||||
import {existsSync, mkdirSync} from "node:fs";
|
||||
import {createServer} from "node:http";
|
||||
import {parse} from "node:querystring";
|
||||
|
||||
import {findAllDevices} from "zigbee-herdsman/dist/adapter/adapterDiscovery";
|
||||
|
||||
import data from "./data";
|
||||
import * as settings from "./settings";
|
||||
import {YAMLFileException} from "./yaml";
|
||||
|
||||
type OnboardSettings = {
|
||||
mqtt_base_topic?: string;
|
||||
@@ -147,6 +146,7 @@ function generateHtmlForm(currentSettings: RecursivePartial<Settings>, devices:
|
||||
id="serial_rtscts"
|
||||
name="serial_rtscts"
|
||||
${currentSettings.serial?.rtscts ? "checked" : ""}
|
||||
${process.env.ZIGBEE2MQTT_CONFIG_SERIAL_RTSCTS ? "disabled" : ""}>
|
||||
style="margin-bottom: 1rem;">
|
||||
<small>Can be ignored for networked coordinators (TCP).</small>
|
||||
</fieldset>
|
||||
@@ -273,8 +273,13 @@ function generateHtmlForm(currentSettings: RecursivePartial<Settings>, devices:
|
||||
<a href="https://www.zigbee2mqtt.io/guide/configuration/frontend.html" target="_blank">https://www.zigbee2mqtt.io/guide/configuration/frontend.html</a>
|
||||
</small>
|
||||
<fieldset ${process.env.ZIGBEE2MQTT_CONFIG_HOMEASSISTANT ? "disabled" : ""}>
|
||||
<label for="homeassistant_enabled" ${process.env.ZIGBEE2MQTT_CONFIG_HOMEASSISTANT_ENABLED ? "disabled" : ""}>
|
||||
<input type="checkbox" id="homeassistant_enabled" name="homeassistant_enabled" ${currentSettings.homeassistant?.enabled ? "checked" : ""}>
|
||||
<label for="homeassistant_enabled">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="homeassistant_enabled"
|
||||
name="homeassistant_enabled"
|
||||
${currentSettings.homeassistant?.enabled ? "checked" : ""}
|
||||
${process.env.ZIGBEE2MQTT_CONFIG_HOMEASSISTANT_ENABLED ? "disabled" : ""}>
|
||||
Home Assistant enabled?
|
||||
</label>
|
||||
</fieldset>
|
||||
@@ -483,7 +488,7 @@ async function startOnboardingServer(): Promise<boolean> {
|
||||
}
|
||||
});
|
||||
|
||||
server.listen(Number.parseInt(serverUrl.port), serverUrl.hostname, () => {
|
||||
server.listen(Number.parseInt(serverUrl.port, 10), serverUrl.hostname, () => {
|
||||
console.log(`Onboarding page is available at ${serverUrl.href}`);
|
||||
});
|
||||
});
|
||||
@@ -498,7 +503,7 @@ async function startFailureServer(errors: string): Promise<void> {
|
||||
let server: ReturnType<typeof createServer> | undefined;
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
server = createServer(async (req, res) => {
|
||||
server = createServer((req, res) => {
|
||||
if (req.method === "POST") {
|
||||
res.end(() => {
|
||||
resolve();
|
||||
@@ -510,7 +515,7 @@ async function startFailureServer(errors: string): Promise<void> {
|
||||
}
|
||||
});
|
||||
|
||||
server.listen(Number.parseInt(serverUrl.port), serverUrl.hostname, () => {
|
||||
server.listen(Number.parseInt(serverUrl.port, 10), serverUrl.hostname, () => {
|
||||
console.error(`Failure page is available at ${serverUrl.href}`);
|
||||
});
|
||||
});
|
||||
@@ -518,6 +523,27 @@ async function startFailureServer(errors: string): Promise<void> {
|
||||
await new Promise((resolve) => server?.close(resolve));
|
||||
}
|
||||
|
||||
async function onSettingsErrors(errors: string[]): Promise<void> {
|
||||
let pErrors = "";
|
||||
|
||||
console.error("\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
|
||||
console.error(" READ THIS CAREFULLY\n");
|
||||
console.error("Refusing to start because configuration is not valid, found the following errors:");
|
||||
|
||||
for (const error of errors) {
|
||||
console.error(`- ${error}`);
|
||||
|
||||
pErrors += `<p>- ${escapeHtml(error)}</p>`;
|
||||
}
|
||||
|
||||
console.error("\nIf you don't know how to solve this, read https://www.zigbee2mqtt.io/guide/configuration");
|
||||
console.error("\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n");
|
||||
|
||||
if (!process.env.Z2M_ONBOARD_NO_SERVER && !process.env.Z2M_ONBOARD_NO_FAILURE_PAGE) {
|
||||
await startFailureServer(pErrors);
|
||||
}
|
||||
}
|
||||
|
||||
export async function onboard(): Promise<boolean> {
|
||||
if (!existsSync(data.getPath())) {
|
||||
mkdirSync(data.getPath(), {recursive: true});
|
||||
@@ -525,15 +551,38 @@ export async function onboard(): Promise<boolean> {
|
||||
|
||||
const confExists = existsSync(data.joinPath("configuration.yaml"));
|
||||
|
||||
if (!confExists) {
|
||||
settings.writeMinimalDefaults();
|
||||
} else {
|
||||
if (confExists) {
|
||||
// initial caching, ensure file is valid yaml first
|
||||
try {
|
||||
settings.getPersistedSettings();
|
||||
} catch (error) {
|
||||
await onSettingsErrors(
|
||||
error instanceof YAMLFileException
|
||||
? [`Your configuration file: '${error.file}' is invalid (use https://jsonformatter.org/yaml-validator to find and fix the issue)`]
|
||||
: [`${error}`],
|
||||
);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// migrate first
|
||||
const {migrateIfNecessary} = await import("./settingsMigration.js");
|
||||
|
||||
migrateIfNecessary();
|
||||
|
||||
// make sure existing settings are valid before applying envs
|
||||
const errors = settings.validateNonRequired();
|
||||
|
||||
if (errors.length > 0) {
|
||||
await onSettingsErrors(errors);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// trigger initial writing of `ZIGBEE2MQTT_CONFIG_*` ENVs
|
||||
settings.write();
|
||||
} else {
|
||||
settings.writeMinimalDefaults();
|
||||
}
|
||||
|
||||
// use `configuration.yaml` file to detect "brand new install"
|
||||
@@ -553,24 +602,7 @@ export async function onboard(): Promise<boolean> {
|
||||
const errors = settings.validate();
|
||||
|
||||
if (errors.length > 0) {
|
||||
let pErrors = "";
|
||||
|
||||
console.error("\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
|
||||
console.error(" READ THIS CAREFULLY\n");
|
||||
console.error("Refusing to start because configuration is not valid, found the following errors:");
|
||||
|
||||
for (const error of errors) {
|
||||
console.error(`- ${error}`);
|
||||
|
||||
pErrors += `<p>- ${escapeHtml(error)}</p>`;
|
||||
}
|
||||
|
||||
console.error("\nIf you don't know how to solve this, read https://www.zigbee2mqtt.io/guide/configuration");
|
||||
console.error("\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n");
|
||||
|
||||
if (!process.env.Z2M_ONBOARD_NO_SERVER && !process.env.Z2M_ONBOARD_NO_FAILURE_PAGE) {
|
||||
await startFailureServer(pErrors);
|
||||
}
|
||||
await onSettingsErrors(errors);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import type {UnixDgramSocket} from "unix-dgram";
|
||||
|
||||
import {platform} from "node:os";
|
||||
import type {UnixDgramSocket} from "unix-dgram";
|
||||
|
||||
import logger from "./logger";
|
||||
|
||||
|
||||
@@ -67,6 +67,7 @@
|
||||
"title": "Timeout",
|
||||
"requiresRestart": true,
|
||||
"default": 10,
|
||||
"minimum": 1,
|
||||
"description": "Time after which an active device will be marked as offline in minutes"
|
||||
},
|
||||
"max_jitter": {
|
||||
@@ -78,7 +79,7 @@
|
||||
},
|
||||
"backoff": {
|
||||
"type": "boolean",
|
||||
"title": "Enabled",
|
||||
"title": "Backoff",
|
||||
"description": "Enable timeout backoff on failed availability pings (x1.5, x3, x6, x12...)",
|
||||
"default": true
|
||||
},
|
||||
@@ -103,6 +104,7 @@
|
||||
"title": "Timeout",
|
||||
"requiresRestart": true,
|
||||
"default": 1500,
|
||||
"minimum": 1,
|
||||
"description": "Time after which an passive device will be marked as offline in minutes"
|
||||
}
|
||||
},
|
||||
@@ -248,8 +250,8 @@
|
||||
"type": "number",
|
||||
"title": "Baudrate",
|
||||
"requiresRestart": true,
|
||||
"description": "Baud rate speed for serial port, this can be anything firmware support but default is 115200 for Z-Stack and EZSP, 38400 for Deconz, however note that some EZSP firmware need 57600",
|
||||
"examples": [38400, 57600, 115200]
|
||||
"description": "Baud rate speed for the serial port. This must match what the firmware on your adapter supports (most commonly 115200).",
|
||||
"examples": [115200, 921600, 460800, 230400, 57600, 38400]
|
||||
},
|
||||
"rtscts": {
|
||||
"type": "boolean",
|
||||
@@ -291,13 +293,16 @@
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"enddevice": {
|
||||
"type": "string"
|
||||
"type": "string",
|
||||
"default": "#fff8ce"
|
||||
},
|
||||
"coordinator": {
|
||||
"type": "string"
|
||||
"type": "string",
|
||||
"default": "#e04e5d"
|
||||
},
|
||||
"router": {
|
||||
"type": "string"
|
||||
"type": "string",
|
||||
"default": "#4ea3e0"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -305,13 +310,16 @@
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"enddevice": {
|
||||
"type": "string"
|
||||
"type": "string",
|
||||
"default": "#000000"
|
||||
},
|
||||
"coordinator": {
|
||||
"type": "string"
|
||||
"type": "string",
|
||||
"default": "#ffffff"
|
||||
},
|
||||
"router": {
|
||||
"type": "string"
|
||||
"type": "string",
|
||||
"default": "#ffffff"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -319,10 +327,12 @@
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"active": {
|
||||
"type": "string"
|
||||
"type": "string",
|
||||
"default": "#009900"
|
||||
},
|
||||
"inactive": {
|
||||
"type": "string"
|
||||
"type": "string",
|
||||
"default": "#994444"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -340,7 +350,8 @@
|
||||
"type": "number",
|
||||
"title": "Update check interval",
|
||||
"description": "Your device may request a check for a new firmware update. This value determines how frequently third party servers may actually be contacted to look for firmware updates. The value is set in minutes, and the default is 1 day.",
|
||||
"default": 1440
|
||||
"default": 1440,
|
||||
"minimum": 1
|
||||
},
|
||||
"disable_automatic_update_check": {
|
||||
"type": "boolean",
|
||||
@@ -387,9 +398,9 @@
|
||||
},
|
||||
"package": {
|
||||
"type": "string",
|
||||
"enum": ["zigbee2mqtt-frontend", "zigbee2mqtt-windfront"],
|
||||
"enum": ["zigbee2mqtt-windfront", "zigbee2mqtt-frontend"],
|
||||
"title": "Package",
|
||||
"default": "zigbee2mqtt-frontend",
|
||||
"default": "zigbee2mqtt-windfront",
|
||||
"requiresRestart": true,
|
||||
"description": "Package used for the frontend"
|
||||
},
|
||||
@@ -446,6 +457,12 @@
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"disable_ui_serving": {
|
||||
"type": ["boolean", "null"],
|
||||
"title": "Disable UI serving",
|
||||
"description": "If true, the frontend UI is not served, only the WebSocket is maintained by Zigbee2MQTT (you are required to serve a standalone UI yourself as needed).",
|
||||
"requiresRestart": true
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
@@ -509,7 +526,8 @@
|
||||
"enum": ["console", "file", "syslog"]
|
||||
},
|
||||
"title": "Log output",
|
||||
"description": "Output location of the log, leave empty to suppress logging"
|
||||
"description": "Output location of the log, leave empty to suppress logging",
|
||||
"default": ["console", "file"]
|
||||
},
|
||||
"log_directory": {
|
||||
"type": "string",
|
||||
@@ -524,7 +542,7 @@
|
||||
"requiresRestart": true,
|
||||
"description": "Log file name, can also contain timestamp",
|
||||
"examples": ["zigbee2mqtt_%TIMESTAMP%.log"],
|
||||
"default": "log.txt"
|
||||
"default": "log.log"
|
||||
},
|
||||
"log_level": {
|
||||
"type": "string",
|
||||
@@ -545,7 +563,14 @@
|
||||
"title": "Log Namespaced Levels",
|
||||
"description": "Set individual log levels for certain namespaces",
|
||||
"default": {},
|
||||
"examples": [{ "z2m:mqtt": "warning" }, { "zh:ember:uart:ash": "info" }]
|
||||
"examples": [
|
||||
{
|
||||
"z2m:mqtt": "warning"
|
||||
},
|
||||
{
|
||||
"zh:ember:uart:ash": "info"
|
||||
}
|
||||
]
|
||||
},
|
||||
"log_debug_to_mqtt_frontend": {
|
||||
"type": "boolean",
|
||||
@@ -648,12 +673,15 @@
|
||||
},
|
||||
{
|
||||
"type": "number",
|
||||
"title": "Pan ID (number)"
|
||||
"title": "Pan ID (number)",
|
||||
"minimum": 1,
|
||||
"maximum": 65534
|
||||
}
|
||||
],
|
||||
"title": "Pan ID",
|
||||
"requiresRestart": true,
|
||||
"description": "ZigBee pan ID, changing requires re-pairing all devices!"
|
||||
"description": "Zigbee pan ID, changing requires re-pairing all devices!",
|
||||
"default": 6754
|
||||
},
|
||||
"ext_pan_id": {
|
||||
"oneOf": [
|
||||
@@ -671,14 +699,15 @@
|
||||
],
|
||||
"title": "Ext Pan ID",
|
||||
"requiresRestart": true,
|
||||
"description": "Zigbee extended pan ID, changing requires re-pairing all devices!"
|
||||
"description": "Zigbee extended pan ID, changing requires re-pairing all devices!",
|
||||
"default": [221, 221, 221, 221, 221, 221, 221, 221]
|
||||
},
|
||||
"channel": {
|
||||
"type": "number",
|
||||
"minimum": 11,
|
||||
"maximum": 26,
|
||||
"default": 11,
|
||||
"title": "ZigBee channel",
|
||||
"title": "Zigbee channel",
|
||||
"requiresRestart": true,
|
||||
"description": "Zigbee channel, changing might require re-pairing some devices! (Note: use a ZLL channel: 11, 15, 20, or 25 to avoid problems)",
|
||||
"examples": [15, 20, 25]
|
||||
@@ -689,6 +718,7 @@
|
||||
"type": ["number", "null"],
|
||||
"minimum": 1,
|
||||
"maximum": 64,
|
||||
"default": null,
|
||||
"description": "Adapter concurrency (e.g. 2 for CC2531 or 16 for CC26X2R1) (default: null, uses recommended value)"
|
||||
},
|
||||
"adapter_delay": {
|
||||
@@ -697,6 +727,7 @@
|
||||
"title": "Adapter delay",
|
||||
"minimum": 0,
|
||||
"maximum": 1000,
|
||||
"default": null,
|
||||
"description": "Adapter delay"
|
||||
},
|
||||
"cache_state": {
|
||||
@@ -746,14 +777,16 @@
|
||||
],
|
||||
"title": "Network key",
|
||||
"requiresRestart": true,
|
||||
"description": "Network encryption key, changing requires re-pairing all devices!"
|
||||
"description": "Network encryption key, changing requires re-pairing all devices!",
|
||||
"default": [1, 3, 5, 7, 9, 11, 13, 15, 0, 2, 4, 6, 8, 10, 12, 13]
|
||||
},
|
||||
"timestamp_format": {
|
||||
"type": "string",
|
||||
"title": "Timestamp format",
|
||||
"requiresRestart": true,
|
||||
"description": "Log timestamp format",
|
||||
"examples": ["YYYY-MM-DD HH:mm:ss"]
|
||||
"description": "Log timestamp format (see https://github.com/taylorhakes/fecha?tab=readme-ov-file#formatting-tokens for all supported tokens)",
|
||||
"default": "YYYY-MM-DD HH:mm:ss",
|
||||
"examples": ["YYYY-MM-DD HH:mm:ss.SSS"]
|
||||
},
|
||||
"transmit_power": {
|
||||
"type": ["number", "null"],
|
||||
@@ -767,9 +800,32 @@
|
||||
"type": "string",
|
||||
"enum": ["attribute_and_json", "attribute", "json"],
|
||||
"title": "MQTT output type",
|
||||
"description": "Examples when 'state' of a device is published json: topic: 'zigbee2mqtt/my_bulb' payload '{\"state\": \"ON\"}' attribute: topic 'zigbee2mqtt/my_bulb/state' payload 'ON' attribute_and_json: both json and attribute (see above)"
|
||||
"description": "Examples when 'state' of a device is published json: topic: 'zigbee2mqtt/my_bulb' payload '{\"state\": \"ON\"}' attribute: topic 'zigbee2mqtt/my_bulb/state' payload 'ON' attribute_and_json: both json and attribute (see above)",
|
||||
"default": "json"
|
||||
}
|
||||
}
|
||||
},
|
||||
"health": {
|
||||
"title": "Health",
|
||||
"description": "Periodically check the health of Zigbee2MQTT",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"interval": {
|
||||
"type": "number",
|
||||
"title": "Interval",
|
||||
"description": "Interval between checks in minutes",
|
||||
"default": 10,
|
||||
"minimum": 1,
|
||||
"requiresRestart": true
|
||||
},
|
||||
"reset_on_check": {
|
||||
"type": "boolean",
|
||||
"title": "Reset on check",
|
||||
"description": "If true, will reset stats every time the health check is executed (only applicable to stats that can be reset).",
|
||||
"default": false
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
},
|
||||
"required": ["mqtt"],
|
||||
@@ -800,7 +856,8 @@
|
||||
"description": "Sets the MQTT Message Expiry in seconds, Make sure to set mqtt.version to 5"
|
||||
},
|
||||
"qos": {
|
||||
"type": "number",
|
||||
"type": ["number"],
|
||||
"enum": [0, 1, 2],
|
||||
"title": "QoS",
|
||||
"description": "QoS level for MQTT messages of this device"
|
||||
},
|
||||
@@ -868,7 +925,7 @@
|
||||
"title": "Home Assistant",
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string",
|
||||
"type": ["string", "null"],
|
||||
"title": "Home Assistant name",
|
||||
"description": "Name of the device in Home Assistant"
|
||||
}
|
||||
@@ -890,13 +947,16 @@
|
||||
"type": "boolean"
|
||||
},
|
||||
"qos": {
|
||||
"type": "number"
|
||||
"type": ["number"],
|
||||
"enum": [0, 1, 2],
|
||||
"title": "QoS",
|
||||
"description": "QoS level for MQTT messages of this group"
|
||||
},
|
||||
"off_state": {
|
||||
"type": ["string"],
|
||||
"enum": ["all_members_off", "last_member_state"],
|
||||
"title": "Group off state",
|
||||
"default": "auto",
|
||||
"default": "all_members_off",
|
||||
"requiresRestart": true,
|
||||
"description": "Control when to publish state OFF or CLOSE for a group. 'all_members_off': only publish state OFF/CLOSE when all group members are in state OFF/CLOSE, 'last_member_state': publish state OFF whenever one of its members changes to OFF"
|
||||
},
|
||||
|
||||
+30
-24
@@ -1,14 +1,11 @@
|
||||
import type {ValidateFunction} from "ajv";
|
||||
|
||||
import path from "node:path";
|
||||
|
||||
import type {ValidateFunction} from "ajv";
|
||||
import Ajv from "ajv";
|
||||
import objectAssignDeep from "object-assign-deep";
|
||||
|
||||
import data from "./data";
|
||||
import schemaJson from "./settings.schema.json";
|
||||
import utils from "./utils";
|
||||
import yaml, {YAMLFileException} from "./yaml";
|
||||
import yaml from "./yaml";
|
||||
|
||||
export {schemaJson};
|
||||
// When updating also update:
|
||||
@@ -43,7 +40,7 @@ export const defaults = {
|
||||
},
|
||||
frontend: {
|
||||
enabled: false,
|
||||
package: "zigbee2mqtt-frontend",
|
||||
package: "zigbee2mqtt-windfront",
|
||||
port: 8080,
|
||||
base_url: "/",
|
||||
},
|
||||
@@ -53,6 +50,9 @@ export const defaults = {
|
||||
force_disable_retain: false,
|
||||
// 1MB = roughly 3.5KB per device * 300 devices for `/bridge/devices`
|
||||
maximum_packet_size: 1048576,
|
||||
keepalive: 60,
|
||||
reject_unauthorized: true,
|
||||
version: 4,
|
||||
},
|
||||
serial: {
|
||||
disable_led: false,
|
||||
@@ -113,6 +113,10 @@ export const defaults = {
|
||||
timestamp_format: "YYYY-MM-DD HH:mm:ss",
|
||||
output: "json",
|
||||
},
|
||||
health: {
|
||||
interval: 10,
|
||||
reset_on_check: false,
|
||||
},
|
||||
} satisfies RecursivePartial<Settings>;
|
||||
|
||||
let _settings: Partial<Settings> | undefined;
|
||||
@@ -254,15 +258,7 @@ export function write(): void {
|
||||
}
|
||||
|
||||
export function validate(): string[] {
|
||||
try {
|
||||
getPersistedSettings();
|
||||
} catch (error) {
|
||||
if (error instanceof YAMLFileException) {
|
||||
return [`Your YAML file: '${error.file}' is invalid (use https://jsonformatter.org/yaml-validator to find and fix the issue)`];
|
||||
}
|
||||
|
||||
return [`${error}`];
|
||||
}
|
||||
getPersistedSettings();
|
||||
|
||||
if (!ajvSetting(_settings)) {
|
||||
// biome-ignore lint/style/noNonNullAssertion: When `ajvSetting()` return false it always has `errors`
|
||||
@@ -292,9 +288,6 @@ export function validate(): string[] {
|
||||
if ("icon" in e && e.icon && !e.icon.startsWith("http://") && !e.icon.startsWith("https://") && !e.icon.startsWith("device_icons/")) {
|
||||
errors.push(`Device icon of '${e.friendly_name}' should start with 'device_icons/', got '${e.icon}'`);
|
||||
}
|
||||
if (e.qos != null && ![0, 1, 2].includes(e.qos)) {
|
||||
errors.push(`QOS for '${e.friendly_name}' not valid, should be 0, 1 or 2 got ${e.qos}`);
|
||||
}
|
||||
};
|
||||
|
||||
const settingsWithDefaults = get();
|
||||
@@ -318,6 +311,19 @@ export function validate(): string[] {
|
||||
return errors;
|
||||
}
|
||||
|
||||
export function validateNonRequired(): string[] {
|
||||
getPersistedSettings();
|
||||
|
||||
if (!ajvSetting(_settings)) {
|
||||
// biome-ignore lint/style/noNonNullAssertion: When `ajvSetting()` return false it always has `errors`
|
||||
const errors = ajvSetting.errors!.filter((e) => e.keyword !== "required");
|
||||
|
||||
return errors.map((v) => `${v.instancePath.substring(1)} ${v.message}`);
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
function read(): Partial<Settings> {
|
||||
const s = yaml.read(CONFIG_FILE_PATH) as Partial<Settings>;
|
||||
|
||||
@@ -475,12 +481,12 @@ export function apply(settings: Record<string, unknown>, throwOnError = true): b
|
||||
const newSettings = objectAssignDeep.noMutate(_settings, settings);
|
||||
|
||||
utils.removeNullPropertiesFromObject(newSettings, NULLABLE_SETTINGS);
|
||||
ajvSetting(newSettings);
|
||||
|
||||
if (throwOnError) {
|
||||
const errors = ajvSetting.errors?.filter((e) => e.keyword !== "required");
|
||||
if (!ajvSetting(newSettings) && throwOnError) {
|
||||
// biome-ignore lint/style/noNonNullAssertion: When `ajvSetting()` return false it always has `errors`
|
||||
const errors = ajvSetting.errors!.filter((e) => e.keyword !== "required");
|
||||
|
||||
if (errors?.length) {
|
||||
if (errors.length) {
|
||||
const error = errors[0];
|
||||
throw new Error(`${error.instancePath.substring(1)} ${error.message}`);
|
||||
}
|
||||
@@ -596,12 +602,12 @@ export function addGroup(name: string, id?: string): GroupOptions {
|
||||
settings.groups = {};
|
||||
}
|
||||
|
||||
if (id == null) {
|
||||
if (id == null || (typeof id === "string" && id.trim() === "")) {
|
||||
// look for free ID
|
||||
id = "1";
|
||||
|
||||
while (settings.groups[id]) {
|
||||
id = (Number.parseInt(id) + 1).toString();
|
||||
id = (Number.parseInt(id, 10) + 1).toString();
|
||||
}
|
||||
} else {
|
||||
// ensure provided ID is not in use
|
||||
|
||||
+19
-14
@@ -1,20 +1,19 @@
|
||||
import type * as zhc from "zigbee-herdsman-converters";
|
||||
|
||||
import type {Zigbee2MQTTAPI, Zigbee2MQTTResponse, Zigbee2MQTTResponseEndpoints, Zigbee2MQTTScene} from "../types/api";
|
||||
|
||||
import assert from "node:assert";
|
||||
import {exec} from "node:child_process";
|
||||
import crypto from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import equals from "fast-deep-equal/es6";
|
||||
import humanizeDuration from "humanize-duration";
|
||||
import type * as zhc from "zigbee-herdsman-converters";
|
||||
import type {Zigbee2MQTTAPI, Zigbee2MQTTResponse, Zigbee2MQTTResponseEndpoints, Zigbee2MQTTScene} from "../types/api";
|
||||
|
||||
import data from "./data";
|
||||
|
||||
const BASE64_IMAGE_REGEX = /data:image\/(?<extension>.+);base64,(?<data>.+)/;
|
||||
|
||||
export const DEFAULT_BIND_GROUP_ID = 901;
|
||||
|
||||
function pad(num: number): string {
|
||||
const norm = Math.floor(Math.abs(num));
|
||||
return (norm < 10 ? "0" : "") + norm;
|
||||
@@ -87,7 +86,6 @@ function formatDate(time: number, type: "ISO_8601" | "ISO_8601_local" | "epoch"
|
||||
|
||||
function objectIsEmpty(object: object): boolean {
|
||||
// much faster than checking `Object.keys(object).length`
|
||||
// biome-ignore lint/style/useNamingConvention: bad detection
|
||||
for (const _k in object) return false;
|
||||
return true;
|
||||
}
|
||||
@@ -204,14 +202,21 @@ function containsControlCharacter(str: string): boolean {
|
||||
|
||||
function getAllFiles(path_: string): string[] {
|
||||
const result = [];
|
||||
for (let item of fs.readdirSync(path_)) {
|
||||
item = path.join(path_, item);
|
||||
if (fs.lstatSync(item).isFile()) {
|
||||
result.push(item);
|
||||
|
||||
for (const item of fs.readdirSync(path_, {withFileTypes: true})) {
|
||||
if (item.isSymbolicLink()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const fileName = path.join(path_, item.name);
|
||||
|
||||
if (fs.lstatSync(fileName).isFile()) {
|
||||
result.push(fileName);
|
||||
} else {
|
||||
result.push(...getAllFiles(item));
|
||||
result.push(...getAllFiles(fileName));
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -279,9 +284,9 @@ function isZHGroup(obj: unknown): obj is zh.Group {
|
||||
return obj?.constructor.name.toLowerCase() === "group";
|
||||
}
|
||||
|
||||
const hours = (hours: number): number => 1000 * 60 * 60 * hours;
|
||||
const minutes = (minutes: number): number => 1000 * 60 * minutes;
|
||||
const seconds = (seconds: number): number => 1000 * seconds;
|
||||
export const hours = (hours: number): number => 1000 * 60 * 60 * hours;
|
||||
export const minutes = (minutes: number): number => 1000 * 60 * minutes;
|
||||
export const seconds = (seconds: number): number => 1000 * seconds;
|
||||
|
||||
async function publishLastSeen(
|
||||
data: eventdata.LastSeenChanged,
|
||||
|
||||
+1
-1
@@ -21,7 +21,7 @@ export class YAMLFileException extends YAMLException {
|
||||
function read(file: string): KeyValue {
|
||||
try {
|
||||
const result = yaml.load(fs.readFileSync(file, "utf8"));
|
||||
assert(result instanceof Object);
|
||||
assert(result instanceof Object, `The content of ${file} is expected to be an object`);
|
||||
return result as KeyValue;
|
||||
} catch (error) {
|
||||
if (error instanceof YAMLException) {
|
||||
|
||||
+58
-47
@@ -1,13 +1,9 @@
|
||||
import type {Events as ZHEvents} from "zigbee-herdsman";
|
||||
import type {StartResult} from "zigbee-herdsman/dist/adapter/tstype";
|
||||
|
||||
import {randomInt} from "node:crypto";
|
||||
|
||||
import bind from "bind-decorator";
|
||||
import stringify from "json-stable-stringify-without-jsonify";
|
||||
|
||||
import type {Events as ZHEvents} from "zigbee-herdsman";
|
||||
import {Controller} from "zigbee-herdsman";
|
||||
|
||||
import type {StartResult} from "zigbee-herdsman/dist/adapter/tstype";
|
||||
import Device from "./model/device";
|
||||
import Group from "./model/group";
|
||||
import data from "./util/data";
|
||||
@@ -18,8 +14,7 @@ import utils from "./util/utils";
|
||||
const entityIDRegex = /^(.+?)(?:\/([^/]+))?$/;
|
||||
|
||||
export default class Zigbee {
|
||||
// @ts-expect-error initialized in start
|
||||
private herdsman: Controller;
|
||||
#herdsman!: Controller;
|
||||
private eventBus: EventBus;
|
||||
private groupLookup = new Map<number /* group ID */, Group>();
|
||||
private deviceLookup = new Map<string /* IEEE address */, Device>();
|
||||
@@ -29,6 +24,10 @@ export default class Zigbee {
|
||||
this.eventBus = eventBus;
|
||||
}
|
||||
|
||||
get zhController() {
|
||||
return this.#herdsman;
|
||||
}
|
||||
|
||||
async start(): Promise<StartResult> {
|
||||
const infoHerdsman = await utils.getDependencyVersion("zigbee-herdsman");
|
||||
logger.info(`Starting zigbee-herdsman (${infoHerdsman.version})`);
|
||||
@@ -67,37 +66,37 @@ export default class Zigbee {
|
||||
|
||||
let startResult: StartResult;
|
||||
try {
|
||||
this.herdsman = new Controller(herdsmanSettings);
|
||||
startResult = await this.herdsman.start();
|
||||
this.#herdsman = new Controller(herdsmanSettings);
|
||||
startResult = await this.#herdsman.start();
|
||||
} catch (error) {
|
||||
logger.error("Error while starting zigbee-herdsman");
|
||||
throw error;
|
||||
}
|
||||
|
||||
this.coordinatorIeeeAddr = this.herdsman.getDevicesByType("Coordinator")[0].ieeeAddr;
|
||||
this.coordinatorIeeeAddr = this.#herdsman.getDevicesByType("Coordinator")[0].ieeeAddr;
|
||||
await this.resolveDevicesDefinitions();
|
||||
|
||||
this.herdsman.on("adapterDisconnected", () => this.eventBus.emitAdapterDisconnected());
|
||||
this.herdsman.on("lastSeenChanged", (data: ZHEvents.LastSeenChangedPayload) => {
|
||||
this.#herdsman.on("adapterDisconnected", () => this.eventBus.emitAdapterDisconnected());
|
||||
this.#herdsman.on("lastSeenChanged", (data: ZHEvents.LastSeenChangedPayload) => {
|
||||
// biome-ignore lint/style/noNonNullAssertion: assumed valid
|
||||
this.eventBus.emitLastSeenChanged({device: this.resolveDevice(data.device.ieeeAddr)!, reason: data.reason});
|
||||
});
|
||||
this.herdsman.on("permitJoinChanged", (data: ZHEvents.PermitJoinChangedPayload) => {
|
||||
this.#herdsman.on("permitJoinChanged", (data: ZHEvents.PermitJoinChangedPayload) => {
|
||||
this.eventBus.emitPermitJoinChanged(data);
|
||||
});
|
||||
this.herdsman.on("deviceNetworkAddressChanged", (data: ZHEvents.DeviceNetworkAddressChangedPayload) => {
|
||||
this.#herdsman.on("deviceNetworkAddressChanged", (data: ZHEvents.DeviceNetworkAddressChangedPayload) => {
|
||||
// biome-ignore lint/style/noNonNullAssertion: assumed valid
|
||||
const device = this.resolveDevice(data.device.ieeeAddr)!;
|
||||
logger.debug(`Device '${device.name}' changed network address`);
|
||||
this.eventBus.emitDeviceNetworkAddressChanged({device});
|
||||
});
|
||||
this.herdsman.on("deviceAnnounce", (data: ZHEvents.DeviceAnnouncePayload) => {
|
||||
this.#herdsman.on("deviceAnnounce", (data: ZHEvents.DeviceAnnouncePayload) => {
|
||||
// biome-ignore lint/style/noNonNullAssertion: assumed valid
|
||||
const device = this.resolveDevice(data.device.ieeeAddr)!;
|
||||
logger.debug(`Device '${device.name}' announced itself`);
|
||||
this.eventBus.emitDeviceAnnounce({device});
|
||||
});
|
||||
this.herdsman.on("deviceInterview", async (data: ZHEvents.DeviceInterviewPayload) => {
|
||||
this.#herdsman.on("deviceInterview", async (data: ZHEvents.DeviceInterviewPayload) => {
|
||||
const device = this.resolveDevice(data.device.ieeeAddr);
|
||||
/* v8 ignore next */ if (!device) return; // Prevent potential race
|
||||
await device.resolveDefinition();
|
||||
@@ -105,19 +104,19 @@ export default class Zigbee {
|
||||
this.logDeviceInterview(d);
|
||||
this.eventBus.emitDeviceInterview(d);
|
||||
});
|
||||
this.herdsman.on("deviceJoined", async (data: ZHEvents.DeviceJoinedPayload) => {
|
||||
this.#herdsman.on("deviceJoined", async (data: ZHEvents.DeviceJoinedPayload) => {
|
||||
const device = this.resolveDevice(data.device.ieeeAddr);
|
||||
/* v8 ignore next */ if (!device) return; // Prevent potential race
|
||||
await device.resolveDefinition();
|
||||
logger.info(`Device '${device.name}' joined`);
|
||||
this.eventBus.emitDeviceJoined({device});
|
||||
});
|
||||
this.herdsman.on("deviceLeave", (data: ZHEvents.DeviceLeavePayload) => {
|
||||
this.#herdsman.on("deviceLeave", (data: ZHEvents.DeviceLeavePayload) => {
|
||||
const name = settings.getDevice(data.ieeeAddr)?.friendly_name || data.ieeeAddr;
|
||||
logger.warning(`Device '${name}' left the network`);
|
||||
this.eventBus.emitDeviceLeave({ieeeAddr: data.ieeeAddr, name, device: this.deviceLookup.get(data.ieeeAddr)});
|
||||
});
|
||||
this.herdsman.on("message", async (data: ZHEvents.MessagePayload) => {
|
||||
this.#herdsman.on("message", async (data: ZHEvents.MessagePayload) => {
|
||||
// biome-ignore lint/style/noNonNullAssertion: assumed valid
|
||||
const device = this.resolveDevice(data.device.ieeeAddr)!;
|
||||
await device.resolveDefinition();
|
||||
@@ -133,7 +132,7 @@ export default class Zigbee {
|
||||
|
||||
logger.info(`zigbee-herdsman started (${startResult})`);
|
||||
logger.info(`Coordinator firmware version: '${stringify(await this.getCoordinatorVersion())}'`);
|
||||
logger.debug(`Zigbee network parameters: ${stringify(await this.herdsman.getNetworkParameters())}`);
|
||||
logger.debug(`Zigbee network parameters: ${stringify(await this.#herdsman.getNetworkParameters())}`);
|
||||
|
||||
for (const device of this.devicesIterator(utils.deviceNotCoordinator)) {
|
||||
// If a passlist is used, all other device will be removed from the network.
|
||||
@@ -202,39 +201,39 @@ export default class Zigbee {
|
||||
}
|
||||
|
||||
async getCoordinatorVersion(): Promise<zh.CoordinatorVersion> {
|
||||
return await this.herdsman.getCoordinatorVersion();
|
||||
return await this.#herdsman.getCoordinatorVersion();
|
||||
}
|
||||
|
||||
isStopping(): boolean {
|
||||
return this.herdsman.isStopping();
|
||||
return this.#herdsman.isStopping();
|
||||
}
|
||||
|
||||
async backup(): Promise<void> {
|
||||
return await this.herdsman.backup();
|
||||
return await this.#herdsman.backup();
|
||||
}
|
||||
|
||||
async coordinatorCheck(): Promise<{missingRouters: Device[]}> {
|
||||
const check = await this.herdsman.coordinatorCheck();
|
||||
const check = await this.#herdsman.coordinatorCheck();
|
||||
// biome-ignore lint/style/noNonNullAssertion: assumed valid
|
||||
return {missingRouters: check.missingRouters.map((d) => this.resolveDevice(d.ieeeAddr)!)};
|
||||
}
|
||||
|
||||
async getNetworkParameters(): Promise<zh.NetworkParameters> {
|
||||
return await this.herdsman.getNetworkParameters();
|
||||
return await this.#herdsman.getNetworkParameters();
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
logger.info("Stopping zigbee-herdsman...");
|
||||
await this.herdsman.stop();
|
||||
await this.#herdsman.stop();
|
||||
logger.info("Stopped zigbee-herdsman");
|
||||
}
|
||||
|
||||
getPermitJoin(): boolean {
|
||||
return this.herdsman.getPermitJoin();
|
||||
return this.#herdsman.getPermitJoin();
|
||||
}
|
||||
|
||||
getPermitJoinEnd(): number | undefined {
|
||||
return this.herdsman.getPermitJoinEnd();
|
||||
return this.#herdsman.getPermitJoinEnd();
|
||||
}
|
||||
|
||||
async permitJoin(time: number, device?: Device): Promise<void> {
|
||||
@@ -244,7 +243,7 @@ export default class Zigbee {
|
||||
logger.info("Zigbee: disabling joining new devices.");
|
||||
}
|
||||
|
||||
await this.herdsman.permitJoin(time, device?.zh);
|
||||
await this.#herdsman.permitJoin(time, device?.zh);
|
||||
}
|
||||
|
||||
async resolveDevicesDefinitions(ignoreCache = false): Promise<void> {
|
||||
@@ -255,7 +254,7 @@ export default class Zigbee {
|
||||
|
||||
@bind private resolveDevice(ieeeAddr: string): Device | undefined {
|
||||
if (!this.deviceLookup.has(ieeeAddr)) {
|
||||
const device = this.herdsman.getDeviceByIeeeAddr(ieeeAddr);
|
||||
const device = this.#herdsman.getDeviceByIeeeAddr(ieeeAddr);
|
||||
if (device) {
|
||||
this.deviceLookup.set(ieeeAddr, new Device(device));
|
||||
}
|
||||
@@ -269,12 +268,20 @@ export default class Zigbee {
|
||||
}
|
||||
|
||||
private resolveGroup(groupID: number): Group | undefined {
|
||||
const group = this.herdsman.getGroupByID(Number(groupID));
|
||||
if (group && !this.groupLookup.has(groupID)) {
|
||||
this.groupLookup.set(groupID, new Group(group, this.resolveDevice));
|
||||
if (!this.groupLookup.has(groupID)) {
|
||||
const group = this.#herdsman.getGroupByID(groupID);
|
||||
|
||||
if (group) {
|
||||
this.groupLookup.set(groupID, new Group(group, this.resolveDevice));
|
||||
}
|
||||
}
|
||||
|
||||
return this.groupLookup.get(groupID);
|
||||
const group = this.groupLookup.get(groupID);
|
||||
|
||||
if (group) {
|
||||
group.ensureInSettings();
|
||||
return group;
|
||||
}
|
||||
}
|
||||
|
||||
resolveEntity(key: string | number | zh.Device): Device | Group | undefined {
|
||||
@@ -335,33 +342,33 @@ export default class Zigbee {
|
||||
}
|
||||
|
||||
firstCoordinatorEndpoint(): zh.Endpoint {
|
||||
return this.herdsman.getDevicesByType("Coordinator")[0].endpoints[0];
|
||||
return this.#herdsman.getDevicesByType("Coordinator")[0].endpoints[0];
|
||||
}
|
||||
|
||||
*devicesAndGroupsIterator(
|
||||
devicePredicate?: (value: zh.Device) => boolean,
|
||||
groupPredicate?: (value: zh.Group) => boolean,
|
||||
): Generator<Device | Group> {
|
||||
for (const device of this.herdsman.getDevicesIterator(devicePredicate)) {
|
||||
for (const device of this.#herdsman.getDevicesIterator(devicePredicate)) {
|
||||
// biome-ignore lint/style/noNonNullAssertion: assumed valid
|
||||
yield this.resolveDevice(device.ieeeAddr)!;
|
||||
}
|
||||
|
||||
for (const group of this.herdsman.getGroupsIterator(groupPredicate)) {
|
||||
for (const group of this.#herdsman.getGroupsIterator(groupPredicate)) {
|
||||
// biome-ignore lint/style/noNonNullAssertion: assumed valid
|
||||
yield this.resolveGroup(group.groupID)!;
|
||||
}
|
||||
}
|
||||
|
||||
*groupsIterator(predicate?: (value: zh.Group) => boolean): Generator<Group> {
|
||||
for (const group of this.herdsman.getGroupsIterator(predicate)) {
|
||||
for (const group of this.#herdsman.getGroupsIterator(predicate)) {
|
||||
// biome-ignore lint/style/noNonNullAssertion: assumed valid
|
||||
yield this.resolveGroup(group.groupID)!;
|
||||
}
|
||||
}
|
||||
|
||||
*devicesIterator(predicate?: (value: zh.Device) => boolean): Generator<Device> {
|
||||
for (const device of this.herdsman.getDevicesIterator(predicate)) {
|
||||
for (const device of this.#herdsman.getDevicesIterator(predicate)) {
|
||||
// biome-ignore lint/style/noNonNullAssertion: assumed valid
|
||||
yield this.resolveDevice(device.ieeeAddr)!;
|
||||
}
|
||||
@@ -395,37 +402,41 @@ export default class Zigbee {
|
||||
}
|
||||
|
||||
async touchlinkFactoryResetFirst(): Promise<boolean> {
|
||||
return await this.herdsman.touchlinkFactoryResetFirst();
|
||||
return await this.#herdsman.touchlink.factoryResetFirst();
|
||||
}
|
||||
|
||||
async touchlinkFactoryReset(ieeeAddr: string, channel: number): Promise<boolean> {
|
||||
return await this.herdsman.touchlinkFactoryReset(ieeeAddr, channel);
|
||||
return await this.#herdsman.touchlink.factoryReset(ieeeAddr, channel);
|
||||
}
|
||||
|
||||
async addInstallCode(installCode: string): Promise<void> {
|
||||
await this.herdsman.addInstallCode(installCode);
|
||||
await this.#herdsman.addInstallCode(installCode);
|
||||
}
|
||||
|
||||
async touchlinkIdentify(ieeeAddr: string, channel: number): Promise<void> {
|
||||
await this.herdsman.touchlinkIdentify(ieeeAddr, channel);
|
||||
await this.#herdsman.touchlink.identify(ieeeAddr, channel);
|
||||
}
|
||||
|
||||
async touchlinkScan(): Promise<{ieeeAddr: string; channel: number}[]> {
|
||||
return await this.herdsman.touchlinkScan();
|
||||
return await this.#herdsman.touchlink.scan();
|
||||
}
|
||||
|
||||
createGroup(id: number): Group {
|
||||
this.herdsman.createGroup(id);
|
||||
this.#herdsman.createGroup(id);
|
||||
// biome-ignore lint/style/noNonNullAssertion: just created
|
||||
return this.resolveGroup(id)!;
|
||||
}
|
||||
|
||||
deviceByNetworkAddress(networkAddress: number): Device | undefined {
|
||||
const device = this.herdsman.getDeviceByNetworkAddress(networkAddress);
|
||||
const device = this.#herdsman.getDeviceByNetworkAddress(networkAddress);
|
||||
return device && this.resolveDevice(device.ieeeAddr);
|
||||
}
|
||||
|
||||
groupByID(id: number): Group | undefined {
|
||||
return this.resolveGroup(id);
|
||||
}
|
||||
|
||||
removeGroupFromLookup(id: number): void {
|
||||
this.groupLookup.delete(id);
|
||||
}
|
||||
}
|
||||
|
||||
+25
-24
@@ -1,16 +1,16 @@
|
||||
{
|
||||
"name": "zigbee2mqtt",
|
||||
"version": "2.4.0",
|
||||
"version": "2.7.1",
|
||||
"description": "Zigbee to MQTT bridge using Zigbee-herdsman",
|
||||
"main": "index.js",
|
||||
"types": "dist/types/api.d.ts",
|
||||
"packageManager": "pnpm@10.4.1",
|
||||
"packageManager": "pnpm@10.18.3",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/Koenkk/zigbee2mqtt.git"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^20 || ^22 || ^24"
|
||||
"node": "^20.15.0 || ^22.2.0 || ^24"
|
||||
},
|
||||
"keywords": [
|
||||
"xiaomi",
|
||||
@@ -23,13 +23,15 @@
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsc && node index.js writehash",
|
||||
"build:types": "pnpm run clean && tsc --project tsconfig.types.json && cp lib/util/settings.schema.json dist/util",
|
||||
"build:watch": "tsc --watch",
|
||||
"check": "biome check",
|
||||
"check": "biome check --error-on-warnings",
|
||||
"check:w": "biome check --write",
|
||||
"start": "node index.js",
|
||||
"test": "vitest run --config ./test/vitest.config.mts",
|
||||
"test:coverage": "vitest run --config ./test/vitest.config.mts --coverage",
|
||||
"test:watch": "vitest watch --config ./test/vitest.config.mts",
|
||||
"bench": "vitest bench --run --config ./test/vitest.config.mts",
|
||||
"prepack": "pnpm run clean && pnpm run build",
|
||||
"clean": "rimraf coverage dist tsconfig.tsbuildinfo"
|
||||
},
|
||||
@@ -42,43 +44,42 @@
|
||||
"dependencies": {
|
||||
"ajv": "^8.17.1",
|
||||
"bind-decorator": "^1.0.11",
|
||||
"debounce": "^2.2.0",
|
||||
"debounce": "^3.0.0",
|
||||
"express-static-gzip": "^3.0.0",
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"finalhandler": "^2.1.0",
|
||||
"humanize-duration": "^3.32.1",
|
||||
"finalhandler": "^2.1.1",
|
||||
"humanize-duration": "^3.33.1",
|
||||
"js-yaml": "^4.1.0",
|
||||
"json-stable-stringify-without-jsonify": "^1.0.1",
|
||||
"jszip": "^3.10.1",
|
||||
"moment": "^2.30.1",
|
||||
"mqtt": "^5.11.0",
|
||||
"mqtt": "^5.14.1",
|
||||
"object-assign-deep": "^0.4.0",
|
||||
"rimraf": "^6.0.1",
|
||||
"semver": "^7.7.1",
|
||||
"rimraf": "^6.1.2",
|
||||
"semver": "^7.7.3",
|
||||
"source-map-support": "^0.5.21",
|
||||
"throttleit": "^2.1.0",
|
||||
"winston": "^3.17.0",
|
||||
"winston": "^3.18.3",
|
||||
"winston-syslog": "^2.7.1",
|
||||
"winston-transport": "^4.9.0",
|
||||
"ws": "^8.18.1",
|
||||
"zigbee-herdsman": "4.1.0",
|
||||
"zigbee-herdsman-converters": "23.53.0",
|
||||
"zigbee2mqtt-frontend": "0.9.13",
|
||||
"zigbee2mqtt-windfront": "^1.0.2"
|
||||
"zigbee-herdsman": "7.0.4",
|
||||
"zigbee-herdsman-converters": "25.83.1",
|
||||
"zigbee2mqtt-frontend": "0.9.21",
|
||||
"zigbee2mqtt-windfront": "2.4.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@biomejs/biome": "^1.9.4",
|
||||
"@biomejs/biome": "^2.3.8",
|
||||
"@types/finalhandler": "^1.2.3",
|
||||
"@types/humanize-duration": "^3.27.4",
|
||||
"@types/js-yaml": "^4.0.9",
|
||||
"@types/node": "^22.14.1",
|
||||
"@types/node": "^24.10.1",
|
||||
"@types/object-assign-deep": "^0.4.3",
|
||||
"@types/readable-stream": "4.0.20",
|
||||
"@types/serve-static": "^1.15.7",
|
||||
"@types/readable-stream": "4.0.22",
|
||||
"@types/serve-static": "^2.2.0",
|
||||
"@types/ws": "8.18.1",
|
||||
"@vitest/coverage-v8": "^3.1.1",
|
||||
"tmp": "^0.2.3",
|
||||
"typescript": "^5.8.3",
|
||||
"tmp": "^0.2.5",
|
||||
"typescript": "^5.9.3",
|
||||
"vitest": "^3.1.1"
|
||||
},
|
||||
"pnpm": {
|
||||
@@ -96,6 +97,6 @@
|
||||
"zigbee2mqtt": "cli.js"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"unix-dgram": "^2.0.6"
|
||||
"unix-dgram": "^2.0.7"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+683
-635
File diff suppressed because it is too large
Load Diff
@@ -1,157 +0,0 @@
|
||||
const path = require("node:path");
|
||||
const fs = require("node:fs");
|
||||
const process = require("node:process");
|
||||
const {execSync} = require("node:child_process");
|
||||
const zhc = require("zigbee-herdsman-converters");
|
||||
|
||||
const z2mTillVersion = process.argv[2];
|
||||
const zhcTillVersion = process.argv[3];
|
||||
const zhTillVersion = process.argv[4];
|
||||
const frontendTillVersion = process.argv[5];
|
||||
|
||||
const changelogs = [
|
||||
{
|
||||
tillVersion: z2mTillVersion,
|
||||
project: "koenkk/zigbee2mqtt",
|
||||
contents: fs.readFileSync(path.join(__dirname, "..", "CHANGELOG.md"), "utf-8").split("\n"),
|
||||
},
|
||||
{
|
||||
tillVersion: zhcTillVersion,
|
||||
project: "koenkk/zigbee-herdsman-converters",
|
||||
contents: fs.readFileSync(path.join(__dirname, "..", "node_modules", "zigbee-herdsman-converters", "CHANGELOG.md"), "utf-8").split("\n"),
|
||||
},
|
||||
{
|
||||
tillVersion: zhTillVersion,
|
||||
project: "koenkk/zigbee-herdsman",
|
||||
contents: fs.readFileSync(path.join(__dirname, "..", "node_modules", "zigbee-herdsman", "CHANGELOG.md"), "utf-8").split("\n"),
|
||||
},
|
||||
{
|
||||
tillVersion: frontendTillVersion,
|
||||
project: "nurikk/zigbee2mqtt-frontend",
|
||||
isFrontend: true,
|
||||
contents: fs.readFileSync(path.join(__dirname, "..", "node_modules", "zigbee2mqtt-frontend", "CHANGELOG.md"), "utf-8").split("\n"),
|
||||
},
|
||||
];
|
||||
|
||||
const releaseRe = /## \[(.+)\]/;
|
||||
const changes = {features: [], fixes: [], detect: [], add: [], error: [], frontend: []};
|
||||
let context = null;
|
||||
const changeRe = [
|
||||
/^\* (\*\*(.+):\*\*)?(.+)\((\[#\d+\]\(.+\))\) \(\[.+\]\(https:.+\/(.+)\)\)$/,
|
||||
/^\* (\*\*(.+):\*\*)?(.+)(https:\/\/github\.com.+) \(\[.+\]\(https:.+\/(.+)\)\)$/,
|
||||
/^\* (\*\*(.+):\*\*)?(.+)() \(\[.+\]\(https:.+\/(.+)\)\)$/,
|
||||
];
|
||||
const frontendChangeRe = /^\* (\*\*.+:\*\* )()?(.+) \(\[.+\]\(https:.+\/()(.+)\)\)(.+)?$/;
|
||||
|
||||
let commitUserLookup = {};
|
||||
const commitUserFile = path.join(__dirname, "commit-user-lookup.json");
|
||||
if (fs.existsSync(commitUserFile)) {
|
||||
commitUserLookup = JSON.parse(fs.readFileSync(commitUserFile, "utf8"));
|
||||
}
|
||||
|
||||
const definitions = require("zigbee-herdsman-converters/devices/index").default.map((d) => zhc.prepareDefinition(d));
|
||||
const whiteLabels = definitions.filter((d) => d.whiteLabel).flatMap((d) => d.whiteLabel);
|
||||
const capitalizeFirstChar = (str) => str.charAt(0).toUpperCase() + str.slice(1);
|
||||
|
||||
for (const changelog of changelogs) {
|
||||
for (const line of changelog.contents) {
|
||||
const releaseMatch = line.match(releaseRe);
|
||||
const changeMatch = changelog.isFrontend ? line.match(frontendChangeRe) : changeRe.map((re) => line.match(re)).find((e) => e);
|
||||
if (releaseMatch) {
|
||||
if (releaseMatch[1] === changelog.tillVersion) {
|
||||
break;
|
||||
}
|
||||
} else if (line === "### Features") {
|
||||
context = "features";
|
||||
} else if (line === "### Bug Fixes") {
|
||||
context = "fixes";
|
||||
} else if (line.startsWith("* **ignore:**")) {
|
||||
// continue;
|
||||
} else if (changeMatch) {
|
||||
let localContext = changelog.isFrontend ? "frontend" : changeMatch[2] ? changeMatch[2] : context;
|
||||
if (!changes[localContext]) localContext = "error";
|
||||
|
||||
const commit = changeMatch[5];
|
||||
const commitUserKey = `${changelog.project}-${commit} `;
|
||||
let user =
|
||||
commitUserKey in commitUserLookup
|
||||
? commitUserLookup[commitUserKey]
|
||||
: execSync(`curl -s https://api.github.com/repos/${changelog.project}/commits/${commit} | jq -r '.author.login'`)
|
||||
.toString()
|
||||
.trim();
|
||||
if (user !== "null") commitUserLookup[commitUserKey] = user;
|
||||
const messages = [];
|
||||
let message = changeMatch[3].trim();
|
||||
if (message.endsWith(".")) message = message.substring(0, message.length - 1);
|
||||
|
||||
if (changelog.isFrontend) {
|
||||
changes[localContext].push(
|
||||
`- [${commit.slice(0, 7)}](https://github.com/${changelog.project}/commit/${commit}) ${message} (@${user})`,
|
||||
);
|
||||
messages.push(capitalizeFirstChar(message));
|
||||
} else {
|
||||
const otherUser = message.match(/\[@(.+)\]\(https:\/\/github.com\/.+\)/) || message.match(/@(.+)/);
|
||||
if (otherUser) {
|
||||
user = otherUser[1];
|
||||
message = message.replace(otherUser[0], "");
|
||||
}
|
||||
|
||||
if (localContext === "add") {
|
||||
for (const model of message.split(",")) {
|
||||
const definition = definitions.find((d) => d.model === model.trim());
|
||||
const whiteLabel = whiteLabels.find((d) => d.model === model.trim());
|
||||
const match = definition || whiteLabel;
|
||||
if (match) {
|
||||
messages.push(`\`${match.model}\` ${match.vendor} ${match.description}`);
|
||||
} else {
|
||||
changes.error.push(`${line} (model '${model}' does not exist)`);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
messages.push(capitalizeFirstChar(message));
|
||||
}
|
||||
|
||||
let issue = changeMatch[4].trim();
|
||||
if (issue && !issue.startsWith("[#")) issue = `[#${issue.split("/").pop()}](${issue})`;
|
||||
if (!issue) {
|
||||
issue = "_NO_ISSUE_";
|
||||
localContext = "error";
|
||||
}
|
||||
|
||||
for (const message of messages) {
|
||||
changes[localContext].push(`- ${issue} ${message} (@${user})`);
|
||||
}
|
||||
}
|
||||
} else if (line === "# Changelog" || line === "### ⚠ BREAKING CHANGES" || !line) {
|
||||
// continue;
|
||||
} else {
|
||||
changes.error.push(`- Unmatched line: ${line}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let result = "";
|
||||
const names = [
|
||||
["features", "Improvements"],
|
||||
["fixes", "Fixes"],
|
||||
["frontend", "Frontend"],
|
||||
["add", "New supported devices"],
|
||||
["detect", "Fixed device detections"],
|
||||
["error", "Changelog generator error"],
|
||||
];
|
||||
for (const name of names) {
|
||||
result += `# ${name[1]}\n`;
|
||||
if (name[0] === "add") {
|
||||
result += `This release adds support for ${changes.add.length} devices: \n`;
|
||||
}
|
||||
|
||||
for (const change of changes[name[0]]) {
|
||||
result += `${change}\n`;
|
||||
}
|
||||
|
||||
result += "\n";
|
||||
}
|
||||
|
||||
fs.writeFileSync(commitUserFile, JSON.stringify(commitUserLookup), "utf-8");
|
||||
|
||||
console.log(result.trim());
|
||||
@@ -0,0 +1,185 @@
|
||||
import {execSync} from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import process from "node:process";
|
||||
import zhc from "zigbee-herdsman-converters";
|
||||
import definitionIndex from "zigbee-herdsman-converters/devices/index";
|
||||
|
||||
const z2mTillVersion = process.argv[2];
|
||||
const zhcTillVersion = process.argv[3];
|
||||
const zhTillVersion = process.argv[4];
|
||||
const frontendTillVersion = process.argv[5];
|
||||
const windfrontTillVersion = process.argv[6];
|
||||
|
||||
const changelogs = [
|
||||
{
|
||||
tillVersion: z2mTillVersion,
|
||||
project: "koenkk/zigbee2mqtt",
|
||||
contents: fs.readFileSync(path.join(import.meta.dirname, "..", "CHANGELOG.md"), "utf-8").split("\n"),
|
||||
},
|
||||
{
|
||||
tillVersion: zhcTillVersion,
|
||||
project: "koenkk/zigbee-herdsman-converters",
|
||||
contents: fs
|
||||
.readFileSync(path.join(import.meta.dirname, "..", "node_modules", "zigbee-herdsman-converters", "CHANGELOG.md"), "utf-8")
|
||||
.split("\n"),
|
||||
},
|
||||
{
|
||||
tillVersion: zhTillVersion,
|
||||
project: "koenkk/zigbee-herdsman",
|
||||
contents: fs.readFileSync(path.join(import.meta.dirname, "..", "node_modules", "zigbee-herdsman", "CHANGELOG.md"), "utf-8").split("\n"),
|
||||
},
|
||||
{
|
||||
tillVersion: frontendTillVersion,
|
||||
project: "nurikk/zigbee2mqtt-frontend",
|
||||
isFrontend: true,
|
||||
contents: fs.readFileSync(path.join(import.meta.dirname, "..", "node_modules", "zigbee2mqtt-frontend", "CHANGELOG.md"), "utf-8").split("\n"),
|
||||
},
|
||||
{
|
||||
tillVersion: windfrontTillVersion,
|
||||
project: "Nerivec/zigbee2mqtt-windfront",
|
||||
},
|
||||
];
|
||||
|
||||
const releaseRe = /## \[(.+)\]/;
|
||||
const windfrontChangeRe = /^\* (feat|fix): (.+?)(?: by @([^\s]+) in (https:\/\/github\.com\/Nerivec\/zigbee2mqtt-windfront\/pull\/(\d+)))?$/gm;
|
||||
const changes = {features: [], fixes: [], detect: [], add: [], error: [], frontend: [], windfront: []};
|
||||
let context = null;
|
||||
const changeRe = [
|
||||
/^\* (\*\*(.+):\*\*)?(.+)\((\[#\d+\]\(.+\))\) \(\[.+\]\(https:.+\/(.+)\)\)$/,
|
||||
/^\* (\*\*(.+):\*\*)?(.+)(https:\/\/github\.com.+) \(\[.+\]\(https:.+\/(.+)\)\)$/,
|
||||
/^\* (\*\*(.+):\*\*)?(.+)() \(\[.+\]\(https:.+\/(.+)\)\)$/,
|
||||
];
|
||||
const frontendChangeRe = /^\* (\*\*.+:\*\* )()?(.+) \(\[.+\]\(https:.+\/()(.+)\)\)(.+)?$/;
|
||||
|
||||
let commitUserLookup = {};
|
||||
const commitUserFile = path.join(import.meta.dirname, "commit-user-lookup.json");
|
||||
if (fs.existsSync(commitUserFile)) {
|
||||
commitUserLookup = JSON.parse(fs.readFileSync(commitUserFile, "utf8"));
|
||||
}
|
||||
|
||||
const definitions = definitionIndex.default.map((d) => zhc.prepareDefinition(d));
|
||||
const whiteLabels = definitions.filter((d) => d.whiteLabel).flatMap((d) => d.whiteLabel);
|
||||
const capitalizeFirstChar = (str) => str.charAt(0).toUpperCase() + str.slice(1);
|
||||
|
||||
for (const changelog of changelogs) {
|
||||
if (changelog.project === "Nerivec/zigbee2mqtt-windfront") {
|
||||
const releaseRsp = await fetch("https://api.github.com/repos/Nerivec/zigbee2mqtt-windfront/releases");
|
||||
const releases = await releaseRsp.json();
|
||||
for (const release of releases) {
|
||||
if (release.name === `v${windfrontTillVersion}`) {
|
||||
break;
|
||||
}
|
||||
|
||||
let match = windfrontChangeRe.exec(release.body);
|
||||
while (match !== null) {
|
||||
const [, type, message, user, prLink, prId] = match;
|
||||
const entry = `- ${prId && prLink ? `[#${prId}](${prLink}) ` : ""}${type}: ${message} ${user ? `(@${user.split("[")[0]})` : ""}`;
|
||||
changes.windfront.push(entry);
|
||||
match = windfrontChangeRe.exec(release.body);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (const line of changelog.contents) {
|
||||
const releaseMatch = line.match(releaseRe);
|
||||
const changeMatch = changelog.isFrontend ? line.match(frontendChangeRe) : changeRe.map((re) => line.match(re)).find((e) => e);
|
||||
if (releaseMatch) {
|
||||
if (releaseMatch[1] === changelog.tillVersion) {
|
||||
break;
|
||||
}
|
||||
} else if (line === "### Features") {
|
||||
context = "features";
|
||||
} else if (line === "### Bug Fixes") {
|
||||
context = "fixes";
|
||||
} else if (line.startsWith("* **ignore:**")) {
|
||||
// continue;
|
||||
} else if (changeMatch) {
|
||||
let localContext = changelog.isFrontend ? "frontend" : changeMatch[2] ? changeMatch[2] : context;
|
||||
if (!changes[localContext]) localContext = "error";
|
||||
|
||||
const commit = changeMatch[5];
|
||||
const commitUserKey = `${changelog.project}-${commit} `;
|
||||
let user =
|
||||
commitUserKey in commitUserLookup
|
||||
? commitUserLookup[commitUserKey]
|
||||
: execSync(`curl -s https://api.github.com/repos/${changelog.project}/commits/${commit} | jq -r '.author.login'`)
|
||||
.toString()
|
||||
.trim();
|
||||
if (user !== "null") commitUserLookup[commitUserKey] = user;
|
||||
const messages = [];
|
||||
let message = changeMatch[3].trim();
|
||||
if (message.endsWith(".")) message = message.substring(0, message.length - 1);
|
||||
|
||||
if (changelog.isFrontend) {
|
||||
changes[localContext].push(
|
||||
`- [${commit.slice(0, 7)}](https://github.com/${changelog.project}/commit/${commit}) ${message} (@${user})`,
|
||||
);
|
||||
messages.push(capitalizeFirstChar(message));
|
||||
} else {
|
||||
const otherUser = message.match(/\[@(.+)\]\(https:\/\/github.com\/.+\)/) || message.match(/@(.+)/);
|
||||
if (otherUser) {
|
||||
user = otherUser[1];
|
||||
message = message.replace(otherUser[0], "");
|
||||
}
|
||||
|
||||
if (localContext === "add") {
|
||||
for (const model of message.split(",")) {
|
||||
const definition = definitions.find((d) => d.model === model.trim());
|
||||
const whiteLabel = whiteLabels.find((d) => d.model === model.trim());
|
||||
const match = definition || whiteLabel;
|
||||
if (match) {
|
||||
messages.push(`\`${match.model}\` ${match.vendor} ${match.description}`);
|
||||
} else {
|
||||
changes.error.push(`${line} (model '${model}' does not exist)`);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
messages.push(capitalizeFirstChar(message));
|
||||
}
|
||||
|
||||
let issue = changeMatch[4].trim();
|
||||
if (issue && !issue.startsWith("[#")) issue = `[#${issue.split("/").pop()}](${issue})`;
|
||||
if (!issue) {
|
||||
issue = "_NO_ISSUE_";
|
||||
localContext = "error";
|
||||
}
|
||||
|
||||
for (const message of messages) {
|
||||
changes[localContext].push(`- ${issue} ${message} (@${user})`);
|
||||
}
|
||||
}
|
||||
} else if (line === "# Changelog" || line === "### ⚠ BREAKING CHANGES" || !line) {
|
||||
// continue;
|
||||
} else {
|
||||
changes.error.push(`- Unmatched line: ${line}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let result = "";
|
||||
const names = [
|
||||
["features", "Improvements"],
|
||||
["fixes", "Fixes"],
|
||||
["windfront", "Windfront"],
|
||||
["frontend", "Frontend"],
|
||||
["add", "New supported devices"],
|
||||
["detect", "Fixed device detections"],
|
||||
["error", "Changelog generator error"],
|
||||
];
|
||||
for (const name of names) {
|
||||
result += `# ${name[1]}\n`;
|
||||
if (name[0] === "add") {
|
||||
result += `This release adds support for ${changes.add.length} devices: \n`;
|
||||
}
|
||||
|
||||
for (const change of changes[name[0]]) {
|
||||
result += `${change}\n`;
|
||||
}
|
||||
|
||||
result += "\n";
|
||||
}
|
||||
|
||||
fs.writeFileSync(commitUserFile, JSON.stringify(commitUserLookup), "utf-8");
|
||||
|
||||
console.log(result.trim());
|
||||
@@ -0,0 +1,149 @@
|
||||
import {execSync} from "node:child_process";
|
||||
|
||||
export async function newDeviceSupport(github, _core, context, zhcDir) {
|
||||
const issue = context.payload.issue;
|
||||
// Hide previous bot comments
|
||||
const comments = await github.rest.issues.listComments({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issue.number,
|
||||
});
|
||||
|
||||
for (const comment of comments.data) {
|
||||
if (comment.user.type === "Bot" && comment.user.login === "github-actions[bot]") {
|
||||
await github.graphql(`mutation {
|
||||
minimizeComment(input: {subjectId: "${comment.node_id}", classifier: OUTDATED}) {
|
||||
clientMutationId
|
||||
}
|
||||
}`);
|
||||
}
|
||||
}
|
||||
|
||||
const titleAndBody = `${issue.title}\n\n${issue.body ?? ""}`;
|
||||
|
||||
// Check if Tuya manufacturer name is already supported.
|
||||
const tuyaManufacturerNameRe = /['"](_T\w+_(\w+))['"]/g;
|
||||
const tuyaManufacturerNames = Array.from(titleAndBody.matchAll(tuyaManufacturerNameRe), (m) => [m[1], m[2]]);
|
||||
console.log("Found tuyaManufacturerNames", tuyaManufacturerNames);
|
||||
if (tuyaManufacturerNames.length > 0) {
|
||||
for (const [fullName, partialName] of tuyaManufacturerNames) {
|
||||
const fullMatch = (() => {
|
||||
try {
|
||||
return execSync(`grep -r --include="*.ts" "${fullName}" "${zhcDir}"`, {encoding: "utf8"});
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
})();
|
||||
|
||||
console.log(`Checking full match for '${fullName}', result: '${fullMatch}'`);
|
||||
if (fullMatch) {
|
||||
await github.rest.issues.createComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issue.number,
|
||||
body: `👋 Hi there! The Tuya device with manufacturer name \`${fullName}\` is already supported in the latest dev branch.
|
||||
See this [guide](https://www.zigbee2mqtt.io/advanced/more/switch-to-dev-branch.html) on how to update, after updating you can remove your external converter.
|
||||
|
||||
In case you created the external converter with the goal to extend or fix an issue with the out-of-the-box support, please submit a pull request.
|
||||
For instructions on how to create a pull request see the [docs](https://www.zigbee2mqtt.io/advanced/support-new-devices/01_support_new_devices.html#_4-create-a-pull-request).
|
||||
If you need help with the process, feel free to ask here and we'll be happy to assist.`,
|
||||
});
|
||||
await github.rest.issues.update({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issue.number,
|
||||
state: "closed",
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const partialMatch = (() => {
|
||||
try {
|
||||
return execSync(`grep -r --include="*.ts" "${partialName}" "${zhcDir}"`, {encoding: "utf8"});
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
})();
|
||||
|
||||
console.log(`Checking partial match for '${partialName}', result: '${partialMatch}'`);
|
||||
if (partialMatch) {
|
||||
const candidates = Array.from(partialMatch.matchAll(tuyaManufacturerNameRe), (m) => m[1]);
|
||||
|
||||
await github.rest.issues.createComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issue.number,
|
||||
body: `👋 Hi there! A similar Tuya device of which the manufacturer name also ends with \`_${partialName}\` is already supported.
|
||||
This means the device can probably be easily be supported by re-using the existing converter.
|
||||
|
||||
I found the following matches: ${candidates.map((c) => `\`${c}\``).join(", ")}
|
||||
Try to stop Z2M, change all occurrences of \`${fullName}\` in the \`data/database.db\` to one of the matches above and start Z2M.
|
||||
|
||||
Let us know if it works so we can support this device out-of-the-box!`,
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Check if zigbee model is already supported.
|
||||
const zigbeeModelRe = /zigbeeModel: \[['"](.+)['"]\]/g;
|
||||
const zigbeeModels = Array.from(titleAndBody.matchAll(zigbeeModelRe), (m) => m[1]);
|
||||
|
||||
if (zigbeeModels.length > 0) {
|
||||
for (const zigbeeModel of zigbeeModels) {
|
||||
const fullMatch = (() => {
|
||||
try {
|
||||
return execSync(`grep -r --include="*.ts" '"${zigbeeModel}"' "${zhcDir}"`, {encoding: "utf8"});
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
})();
|
||||
|
||||
if (fullMatch) {
|
||||
await github.rest.issues.createComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issue.number,
|
||||
body: `👋 Hi there! The device with zigbee model \`${zigbeeModel}\` is already supported in the latest dev branch.
|
||||
See this [guide](https://www.zigbee2mqtt.io/advanced/more/switch-to-dev-branch.html) on how to update, after updating you can remove your external converter.
|
||||
|
||||
In case you created the external converter with the goal to extend or fix an issue with the out-of-the-box support, please submit a pull request.
|
||||
For instructions on how to create a pull request see the [docs](https://www.zigbee2mqtt.io/advanced/support-new-devices/01_support_new_devices.html#_4-create-a-pull-request).
|
||||
|
||||
If you need help with the process, feel free to ask here and we'll be happy to assist.`,
|
||||
});
|
||||
await github.rest.issues.update({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issue.number,
|
||||
state: "closed",
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Create a request to pull request comment
|
||||
await github.rest.issues.createComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issue.number,
|
||||
body: `🙏 Thank you for creating this issue and sharing your external converter!
|
||||
|
||||
In case all features work, please submit a pull request on this repository so the device can be supported out-of-the-box with the next release.
|
||||
For instructions on how to create a pull request see the [docs](https://www.zigbee2mqtt.io/advanced/support-new-devices/01_support_new_devices.html#_4-create-a-pull-request).
|
||||
|
||||
If **NOT** all features work, please follow the [How To Support new devices](https://www.zigbee2mqtt.io/advanced/support-new-devices/01_support_new_devices.html).
|
||||
${
|
||||
tuyaManufacturerNames.length > 0
|
||||
? "Since this is a Tuya also consider [How To Support new Tuya devices](https://www.zigbee2mqtt.io/advanced/support-new-devices/02_support_new_tuya_devices.html)."
|
||||
: ""
|
||||
}
|
||||
|
||||
If you need help with the process, feel free to ask here and we'll be happy to assist.`,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import {hrtime} from "node:process";
|
||||
import type {bench} from "vitest";
|
||||
|
||||
export const BENCH_OPTIONS: NonNullable<Parameters<typeof bench>[2]> = {
|
||||
throws: true,
|
||||
warmupTime: 1000,
|
||||
now: () => Number(hrtime.bigint()) / 1e6,
|
||||
setup: (_task, mode) => {
|
||||
// Run the garbage collector before warmup at each cycle
|
||||
if (mode === "warmup" && typeof globalThis.gc === "function") {
|
||||
globalThis.gc();
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,662 @@
|
||||
import {existsSync, mkdirSync} from "node:fs";
|
||||
import stringify from "json-stable-stringify-without-jsonify";
|
||||
import {bench, describe, vi} from "vitest";
|
||||
import {type Controller, Zcl, Zdo, ZSpec} from "zigbee-herdsman";
|
||||
import type Adapter from "zigbee-herdsman/dist/adapter/adapter";
|
||||
import type {ZclPayload} from "zigbee-herdsman/dist/adapter/events";
|
||||
import {Device, InterviewState} from "zigbee-herdsman/dist/controller/model/device";
|
||||
import {Endpoint} from "zigbee-herdsman/dist/controller/model/endpoint";
|
||||
import Entity from "zigbee-herdsman/dist/controller/model/entity";
|
||||
import {Group} from "zigbee-herdsman/dist/controller/model/group";
|
||||
import type {DeviceType} from "zigbee-herdsman/dist/controller/tstype";
|
||||
import {Foundation} from "zigbee-herdsman/dist/zspec/zcl/definition/foundation";
|
||||
import type {RequestToResponseMap} from "zigbee-herdsman/dist/zspec/zdo/definition/tstypes";
|
||||
import data from "../lib/util/data";
|
||||
import {BENCH_OPTIONS} from "./benchOptions";
|
||||
|
||||
vi.doMock("zigbee-herdsman", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("zigbee-herdsman")>();
|
||||
class MockHerdsman {
|
||||
on: Controller["on"] = vi.fn();
|
||||
start: Controller["start"] = async () => "resumed" as const;
|
||||
stop: Controller["stop"] = async () => {};
|
||||
isStopping: Controller["isStopping"] = () => false;
|
||||
getCoordinatorVersion: Controller["getCoordinatorVersion"] = async () =>
|
||||
Promise.resolve({
|
||||
type: "Dummy",
|
||||
meta: {revision: "9.9.9"},
|
||||
});
|
||||
getNetworkParameters: Controller["getNetworkParameters"] = async () => Promise.resolve({...NETWORK_PARAMS});
|
||||
getPermitJoin: Controller["getPermitJoin"] = () => false;
|
||||
getPermitJoinEnd: Controller["getPermitJoinEnd"] = () => undefined;
|
||||
getDeviceByIeeeAddr: Controller["getDeviceByIeeeAddr"] = (ieeeAddr) => ZH_DEVICES.find((device) => device.ieeeAddr === ieeeAddr);
|
||||
getGroupByID: Controller["getGroupByID"] = (id) => ZH_GROUPS.find((group) => group.groupID === id);
|
||||
getDevicesByType: Controller["getDevicesByType"] = (type) => ZH_DEVICES.filter((device) => device.type === type);
|
||||
getDeviceByNetworkAddress: Controller["getDeviceByNetworkAddress"] = (networkAddress) =>
|
||||
ZH_DEVICES.find((device) => device.networkAddress === networkAddress);
|
||||
*getDevicesIterator(predicate: ((device: Device) => boolean) | undefined) {
|
||||
for (const device of ZH_DEVICES) {
|
||||
if (!predicate || predicate(device)) {
|
||||
yield device;
|
||||
}
|
||||
}
|
||||
}
|
||||
*getGroupsIterator(predicate: ((group: Group) => boolean) | undefined) {
|
||||
for (const group of ZH_GROUPS) {
|
||||
if (!predicate || predicate(group)) {
|
||||
yield group;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...actual,
|
||||
Controller: MockHerdsman,
|
||||
};
|
||||
});
|
||||
|
||||
process.env.ZIGBEE2MQTT_DATA = "data-bench";
|
||||
data._testReload();
|
||||
|
||||
if (!existsSync(data.getPath())) {
|
||||
mkdirSync(data.getPath(), {recursive: true});
|
||||
}
|
||||
|
||||
const createEndpoint = (id: number, ieeeAddr: string, networkAddress: number) => {
|
||||
const ep = Endpoint.create(
|
||||
id,
|
||||
id === ZSpec.GP_ENDPOINT ? ZSpec.GP_PROFILE_ID : ZSpec.HA_PROFILE_ID,
|
||||
id === ZSpec.GP_ENDPOINT ? 0x66 : 0x65,
|
||||
id === ZSpec.GP_ENDPOINT ? [Zcl.Clusters.greenPower.ID] : [Zcl.Clusters.genBasic.ID, Zcl.Clusters.genOnOff.ID],
|
||||
id === ZSpec.GP_ENDPOINT ? [Zcl.Clusters.greenPower.ID] : [Zcl.Clusters.genBasic.ID],
|
||||
networkAddress,
|
||||
ieeeAddr,
|
||||
);
|
||||
ep.save = () => {};
|
||||
|
||||
return ep;
|
||||
};
|
||||
// `Device.create` requires `Database`, bypass it by using the private constructor directly
|
||||
const createDevice = (
|
||||
dbId: number,
|
||||
type: DeviceType,
|
||||
ieeeAddr: string,
|
||||
networkAddress: number,
|
||||
manufacturerID: number | undefined,
|
||||
manufacturerName: string | undefined,
|
||||
powerSource: string | undefined,
|
||||
modelID: string | undefined,
|
||||
): Device => {
|
||||
const haEp = createEndpoint(ZSpec.HA_ENDPOINT, ieeeAddr, networkAddress);
|
||||
const ep2 = createEndpoint(2, ieeeAddr, networkAddress);
|
||||
const endpoints = [haEp, ep2];
|
||||
|
||||
if (type === "Coordinator" || type === "Router") {
|
||||
const gpEp = createEndpoint(ZSpec.GP_ENDPOINT, ieeeAddr, networkAddress);
|
||||
|
||||
endpoints.push(gpEp);
|
||||
}
|
||||
|
||||
// @ts-expect-error mocking private
|
||||
const device = new Device(
|
||||
dbId,
|
||||
type,
|
||||
ieeeAddr,
|
||||
networkAddress,
|
||||
manufacturerID,
|
||||
endpoints,
|
||||
manufacturerName,
|
||||
powerSource,
|
||||
modelID,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
InterviewState.Successful,
|
||||
{},
|
||||
undefined,
|
||||
undefined,
|
||||
0,
|
||||
undefined,
|
||||
);
|
||||
|
||||
// in-memory only
|
||||
device.save = () => {};
|
||||
|
||||
return device;
|
||||
};
|
||||
// `Group.create` requires `Database`, bypass it by using the private constructor directly
|
||||
const createGroup = (dbId: number, id: number): Group => {
|
||||
// @ts-expect-error mocking private
|
||||
const group = new Group(dbId, id, [], {});
|
||||
|
||||
// in-memory only
|
||||
group.save = () => {};
|
||||
|
||||
return group;
|
||||
};
|
||||
|
||||
const COORD_IEEE = "0x0101010101010101";
|
||||
const EXT_PAN_ID = [0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd];
|
||||
const NETWORK_PARAMS = {
|
||||
panID: 0x1a62,
|
||||
extendedPanID: `0x${Buffer.from(EXT_PAN_ID).toString("hex")}`,
|
||||
channel: 11,
|
||||
nwkUpdateID: 1,
|
||||
};
|
||||
const NETWORK_KEY = [1, 3, 5, 7, 9, 11, 13, 15, 0, 2, 4, 6, 8, 10, 12, 13];
|
||||
const ZH_DEVICES: Device[] = [];
|
||||
const ZH_GROUPS: Group[] = [];
|
||||
const MANY_DEVICES = 100;
|
||||
|
||||
const initDevices = () => {
|
||||
ZH_DEVICES.splice(0, ZH_DEVICES.length);
|
||||
|
||||
ZH_DEVICES.push(
|
||||
createDevice(
|
||||
0,
|
||||
"Coordinator",
|
||||
COORD_IEEE,
|
||||
ZSpec.COORDINATOR_ADDRESS,
|
||||
Zcl.ManufacturerCode.SILICON_LABORATORIES,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
),
|
||||
);
|
||||
ZH_DEVICES.push(
|
||||
createDevice(1, "Router", "0xf1f1f1f1f1f1f1f1", 0x0001, Zcl.ManufacturerCode.INNR_LIGHTING_BV, "Innr", "Mains (single phase)", "AE 262"),
|
||||
);
|
||||
ZH_DEVICES.push(
|
||||
createDevice(2, "EndDevice", "0xe2e2e2e2e2e2e2e2", 0x0002, Zcl.ManufacturerCode.TUYA_GLOBAL_INC, "_TYZB01_kvwjujy9", "Battery", "TS0222"),
|
||||
);
|
||||
ZH_DEVICES.push(createDevice(3, "GreenPower", "0x00000000015d3d3d", 0x0003, undefined, undefined, undefined, "GreenPower_7"));
|
||||
// these have configure, without setTimeout, they hammer really badly (# of fn calls), so, only one of each
|
||||
ZH_DEVICES.push(
|
||||
createDevice(
|
||||
4,
|
||||
"Router",
|
||||
"0xd3d3d3d3d3d3d3d3",
|
||||
0x0004,
|
||||
Zcl.ManufacturerCode.LEDVANCE_GMBH,
|
||||
"LEDVANCE",
|
||||
"Mains (single phase)",
|
||||
"PLUG OUTDOOR EU T",
|
||||
),
|
||||
);
|
||||
ZH_DEVICES.push(
|
||||
createDevice(5, "Router", "0xc4c4c4c4c4c4c4c4", 0x0005, Zcl.ManufacturerCode.INOVELLI, "Inovelli", "Mains (single phase)", "VZM35-SN"),
|
||||
);
|
||||
ZH_DEVICES.push(
|
||||
createDevice(
|
||||
6,
|
||||
"Router",
|
||||
"0xb5b5b5b5b5b5b5b5",
|
||||
0x0006,
|
||||
Zcl.ManufacturerCode.SILICON_LABORATORIES,
|
||||
"SMLIGHT",
|
||||
"Mains (single phase)",
|
||||
"SLZB-06Mg24",
|
||||
),
|
||||
);
|
||||
ZH_DEVICES.push(
|
||||
createDevice(
|
||||
7,
|
||||
"Router",
|
||||
"0xa6a6a6a6a6a6a6a6",
|
||||
0x0007,
|
||||
Zcl.ManufacturerCode.TUYA_GLOBAL_INC,
|
||||
"_TZE200_p0gzbqct",
|
||||
"Mains (single phase)",
|
||||
"TS0601",
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const initGroups = () => {
|
||||
ZH_GROUPS.splice(0, ZH_GROUPS.length);
|
||||
|
||||
ZH_GROUPS.push(createGroup(0, 1));
|
||||
};
|
||||
|
||||
const addManyDevices = () => {
|
||||
for (let i = 0; i < MANY_DEVICES; i++) {
|
||||
const ieee = `0xf1f1f1f1f1f1f1${i.toString(16).padStart(2, "0")}`;
|
||||
|
||||
// device without `configure` (too many calls otherwise)
|
||||
ZH_DEVICES.push(createDevice(1, "Router", ieee, 0x0008 + i, Zcl.ManufacturerCode.INNR_LIGHTING_BV, "Innr", "Mains (single phase)", "AE 262"));
|
||||
}
|
||||
};
|
||||
|
||||
const getMidDeviceIeee = () =>
|
||||
`0xf1f1f1f1f1f1f1${Math.floor(MANY_DEVICES / 2)
|
||||
.toString(16)
|
||||
.padStart(2, "0")}`;
|
||||
|
||||
Device.byIeeeAddr = (ieeeAddr, _includeDeleted) => ZH_DEVICES.find((device) => device.ieeeAddr === ieeeAddr);
|
||||
Device.byType = (type) => ZH_DEVICES.filter((device) => device.type === type);
|
||||
|
||||
const adapter = {
|
||||
sendZclFrameToEndpoint: async (
|
||||
_ieeeAddr: string,
|
||||
networkAddress: number,
|
||||
endpoint: number,
|
||||
zclFrame: Zcl.Frame,
|
||||
_timeout: number,
|
||||
disableResponse: boolean,
|
||||
_disableRecovery: boolean,
|
||||
sourceEndpoint?: number,
|
||||
): Promise<ZclPayload | undefined> => {
|
||||
const payload: {[key: string]: unknown}[] = [];
|
||||
|
||||
if (!disableResponse) {
|
||||
if (zclFrame.header.isGlobal) {
|
||||
switch (zclFrame.command.ID) {
|
||||
case Foundation.read.ID: {
|
||||
for (const attr of zclFrame.payload) {
|
||||
const attribute = zclFrame.cluster.getAttribute(attr.attrId);
|
||||
|
||||
if (attribute && attribute.type !== Zcl.DataType.NO_DATA && attribute.type < Zcl.DataType.OCTET_STR) {
|
||||
payload.push({
|
||||
attrId: attr.attrId,
|
||||
dataType: attribute.type,
|
||||
attrData: 1,
|
||||
status: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const messageContents = Zcl.Frame.create(
|
||||
0,
|
||||
Zcl.Direction.SERVER_TO_CLIENT,
|
||||
true,
|
||||
undefined,
|
||||
10,
|
||||
Foundation.readRsp.ID,
|
||||
zclFrame.cluster.ID,
|
||||
payload,
|
||||
{},
|
||||
).toBuffer();
|
||||
|
||||
return await Promise.resolve({
|
||||
clusterID: zclFrame.cluster.ID,
|
||||
header: Zcl.Header.fromBuffer(messageContents),
|
||||
address: networkAddress,
|
||||
data: messageContents,
|
||||
endpoint: sourceEndpoint ?? 1,
|
||||
linkquality: 200,
|
||||
groupID: 0,
|
||||
wasBroadcast: false,
|
||||
destinationEndpoint: endpoint,
|
||||
});
|
||||
}
|
||||
case Foundation.configReport.ID: {
|
||||
for (const item of zclFrame.payload) {
|
||||
payload.push({attrId: item.attrId, status: 0, direction: 1});
|
||||
}
|
||||
|
||||
const messageContents = Zcl.Frame.create(
|
||||
0,
|
||||
Zcl.Direction.SERVER_TO_CLIENT,
|
||||
true,
|
||||
undefined,
|
||||
10,
|
||||
Foundation.configReportRsp.ID,
|
||||
zclFrame.cluster.ID,
|
||||
payload,
|
||||
{},
|
||||
).toBuffer();
|
||||
|
||||
return await Promise.resolve({
|
||||
clusterID: zclFrame.cluster.ID,
|
||||
header: Zcl.Header.fromBuffer(messageContents),
|
||||
address: networkAddress,
|
||||
data: messageContents,
|
||||
endpoint: sourceEndpoint ?? 1,
|
||||
linkquality: 200,
|
||||
groupID: 0,
|
||||
wasBroadcast: false,
|
||||
destinationEndpoint: endpoint,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return await Promise.resolve(undefined);
|
||||
},
|
||||
sendZclFrameToGroup: async (_groupID: number, _zclFrame: Zcl.Frame, _sourceEndpoint?: number): Promise<void> => await Promise.resolve(),
|
||||
sendZdo: async (
|
||||
_ieeeAddress: string,
|
||||
_networkAddress: number,
|
||||
clusterId: Zdo.ClusterId,
|
||||
_payload: Buffer,
|
||||
_disableResponse: boolean,
|
||||
): Promise<RequestToResponseMap[keyof RequestToResponseMap] | undefined> => {
|
||||
switch (clusterId) {
|
||||
case Zdo.ClusterId.BIND_REQUEST:
|
||||
case Zdo.ClusterId.UNBIND_REQUEST: {
|
||||
return await Promise.resolve([Zdo.Status.SUCCESS, undefined]);
|
||||
}
|
||||
}
|
||||
|
||||
return await Promise.resolve(undefined);
|
||||
},
|
||||
};
|
||||
|
||||
Entity.injectAdapter(adapter as Adapter);
|
||||
|
||||
// use plain type to avoid early import that otherwise messes with data path
|
||||
let controller: import("../lib/controller.js").Controller;
|
||||
const origSetImmediate = global.setImmediate;
|
||||
const origSetTimeout = global.setTimeout;
|
||||
|
||||
const mockGlobalThis = () => {
|
||||
const setImmediateProms: (void | Promise<void>)[] = [];
|
||||
const setTimeoutProms: (void | Promise<void>)[] = [];
|
||||
|
||||
// @ts-expect-error mock
|
||||
globalThis.setImmediate = (callback: () => void) => {
|
||||
setImmediateProms.push(callback());
|
||||
};
|
||||
// @ts-expect-error mock
|
||||
globalThis.setTimeout = (callback: () => void) => {
|
||||
setTimeoutProms.push(callback());
|
||||
};
|
||||
|
||||
return {setImmediateProms, setTimeoutProms};
|
||||
};
|
||||
|
||||
const unmockGlobalThis = () => {
|
||||
globalThis.setImmediate = origSetImmediate;
|
||||
globalThis.setTimeout = origSetTimeout;
|
||||
};
|
||||
|
||||
const settle = async (mockedGlobal: ReturnType<typeof mockGlobalThis>) => {
|
||||
await Promise.allSettled(mockedGlobal.setImmediateProms);
|
||||
await Promise.allSettled(mockedGlobal.setTimeoutProms);
|
||||
await new Promise((resolve) => origSetImmediate(resolve));
|
||||
};
|
||||
|
||||
const initSettings = async (pathValuePairs?: [string[], string | number | boolean][]) => {
|
||||
const settings = await import("../lib/util/settings.js");
|
||||
|
||||
settings.writeMinimalDefaults();
|
||||
// disable logging, too much influence on perf
|
||||
settings.set(["advanced", "log_level"], "error");
|
||||
settings.set(["advanced", "log_output"], []);
|
||||
settings.set(["advanced", "pan_id"], NETWORK_PARAMS.panID);
|
||||
settings.set(["advanced", "ext_pan_id"], EXT_PAN_ID);
|
||||
settings.set(["advanced", "network_key"], NETWORK_KEY);
|
||||
|
||||
if (pathValuePairs) {
|
||||
for (const [path, value] of pathValuePairs) {
|
||||
settings.set(path, value);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const initController = async () => {
|
||||
const {Controller} = await import("../lib/controller.js");
|
||||
|
||||
controller = new Controller(
|
||||
async () => {},
|
||||
async () => {},
|
||||
);
|
||||
|
||||
// all dummies, can trigger `controller.mqtt.onMessage(topic, message)` as needed
|
||||
// @ts-expect-error mocking private
|
||||
controller.mqtt.client = {
|
||||
options: {
|
||||
protocolVersion: 5,
|
||||
protocol: "mqtt",
|
||||
host: "localhost",
|
||||
port: 1883,
|
||||
},
|
||||
queue: [],
|
||||
reconnecting: false,
|
||||
disconnecting: false,
|
||||
disconnected: false,
|
||||
endAsync: async () => {},
|
||||
// @ts-expect-error Z2M does not make use of return
|
||||
publishAsync: async () => {},
|
||||
};
|
||||
controller.mqtt.connect = async () => {
|
||||
// @ts-expect-error private
|
||||
await controller.mqtt.onConnect();
|
||||
};
|
||||
controller.mqtt.subscribe = async () => {};
|
||||
controller.mqtt.unsubscribe = async () => {};
|
||||
|
||||
// will be in-memory only
|
||||
controller.state.start = () => {};
|
||||
controller.state.stop = () => {};
|
||||
};
|
||||
|
||||
describe("Controller with dummy zigbee/mqtt", () => {
|
||||
bench(
|
||||
"[defaults] start & stop controller",
|
||||
async () => {
|
||||
initDevices();
|
||||
initGroups();
|
||||
await initSettings();
|
||||
await initController();
|
||||
const mockedGlobal = mockGlobalThis();
|
||||
|
||||
await controller.start();
|
||||
await settle(mockedGlobal);
|
||||
|
||||
if ((await controller.zigbee.getCoordinatorVersion()).type !== "Dummy") {
|
||||
throw new Error("Invalid");
|
||||
}
|
||||
|
||||
await controller.stop();
|
||||
unmockGlobalThis();
|
||||
},
|
||||
BENCH_OPTIONS,
|
||||
);
|
||||
|
||||
bench(
|
||||
"[HA] start & stop controller",
|
||||
async () => {
|
||||
initDevices();
|
||||
initGroups();
|
||||
await initSettings([[["homeassistant", "enabled"], true]]);
|
||||
await initController();
|
||||
const mockedGlobal = mockGlobalThis();
|
||||
|
||||
await controller.start();
|
||||
controller.mqtt.onMessage("homeassistant/status", Buffer.from("online", "utf8"));
|
||||
await settle(mockedGlobal);
|
||||
|
||||
if ((await controller.zigbee.getCoordinatorVersion()).type !== "Dummy") {
|
||||
throw new Error("Invalid");
|
||||
}
|
||||
|
||||
await controller.stop();
|
||||
unmockGlobalThis();
|
||||
},
|
||||
BENCH_OPTIONS,
|
||||
);
|
||||
|
||||
describe("defaults runtime", () => {
|
||||
const setup: NonNullable<Parameters<typeof bench>[2]>["setup"] = async (task, mode) => {
|
||||
BENCH_OPTIONS.setup!(task, mode);
|
||||
initDevices();
|
||||
initGroups();
|
||||
await initSettings();
|
||||
await initController();
|
||||
const mockedGlobal = mockGlobalThis();
|
||||
|
||||
await controller.start();
|
||||
await settle(mockedGlobal);
|
||||
};
|
||||
const teardown = async () => {
|
||||
await controller.stop();
|
||||
unmockGlobalThis();
|
||||
};
|
||||
|
||||
bench(
|
||||
"[defaults] receive device message",
|
||||
async () => {
|
||||
const mockedGlobal = mockGlobalThis();
|
||||
|
||||
controller.eventBus.emitDeviceMessage({
|
||||
type: "attributeReport",
|
||||
device: controller.zigbee.resolveEntity("0xf1f1f1f1f1f1f1f1"),
|
||||
endpoint: ZSpec.HA_ENDPOINT,
|
||||
linkquality: 200,
|
||||
groupID: 0,
|
||||
cluster: "genOnOff",
|
||||
data: {onOff: 1},
|
||||
meta: {},
|
||||
});
|
||||
await settle(mockedGlobal);
|
||||
},
|
||||
{...BENCH_OPTIONS, setup, teardown},
|
||||
);
|
||||
|
||||
bench(
|
||||
"[defaults] receive MQTT message",
|
||||
async () => {
|
||||
const mockedGlobal = mockGlobalThis();
|
||||
|
||||
controller.mqtt.onMessage("zigbee2mqtt/0xf1f1f1f1f1f1f1f1/set", Buffer.from(`{"state": "OFF"}`, "utf8"));
|
||||
await settle(mockedGlobal);
|
||||
},
|
||||
{...BENCH_OPTIONS, setup, teardown},
|
||||
);
|
||||
|
||||
bench(
|
||||
"[defaults] add group member",
|
||||
async () => {
|
||||
const mockedGlobal = mockGlobalThis();
|
||||
|
||||
controller.eventBus.emitMQTTMessage({
|
||||
topic: "zigbee2mqtt/bridge/request/group/members/add",
|
||||
message: stringify({
|
||||
device: "0xf1f1f1f1f1f1f1f1",
|
||||
group: `${ZH_GROUPS[0].groupID}`,
|
||||
endpoint: ZSpec.HA_ENDPOINT,
|
||||
}),
|
||||
});
|
||||
|
||||
await settle(mockedGlobal);
|
||||
|
||||
if (ZH_GROUPS[0].members.length !== 1) {
|
||||
throw new Error("Invalid state");
|
||||
}
|
||||
},
|
||||
{...BENCH_OPTIONS, setup, teardown},
|
||||
);
|
||||
});
|
||||
|
||||
describe("defaults/stress runtime", () => {
|
||||
const setup: NonNullable<Parameters<typeof bench>[2]>["setup"] = async (task, mode) => {
|
||||
BENCH_OPTIONS.setup!(task, mode);
|
||||
initDevices();
|
||||
initGroups();
|
||||
addManyDevices();
|
||||
await initSettings();
|
||||
await initController();
|
||||
const mockedGlobal = mockGlobalThis();
|
||||
|
||||
await controller.start();
|
||||
await settle(mockedGlobal);
|
||||
};
|
||||
|
||||
const teardown = async () => {
|
||||
await controller.stop();
|
||||
unmockGlobalThis();
|
||||
};
|
||||
|
||||
// this is mostly just to confirm the number of devices does not influence the processing (much)
|
||||
bench(
|
||||
"[defaults/stress] receive device message",
|
||||
async () => {
|
||||
const mockedGlobal = mockGlobalThis();
|
||||
|
||||
controller.eventBus.emitDeviceMessage({
|
||||
type: "attributeReport",
|
||||
device: controller.zigbee.resolveEntity(getMidDeviceIeee()),
|
||||
endpoint: ZSpec.HA_ENDPOINT,
|
||||
linkquality: 200,
|
||||
groupID: 0,
|
||||
cluster: "genOnOff",
|
||||
data: {onOff: 1},
|
||||
meta: {},
|
||||
});
|
||||
await settle(mockedGlobal);
|
||||
},
|
||||
{...BENCH_OPTIONS, setup, teardown},
|
||||
);
|
||||
});
|
||||
|
||||
describe("HA runtime", () => {
|
||||
const setup: NonNullable<Parameters<typeof bench>[2]>["setup"] = async (task, mode) => {
|
||||
BENCH_OPTIONS.setup!(task, mode);
|
||||
initDevices();
|
||||
initGroups();
|
||||
await initSettings([[["homeassistant", "enabled"], true]]);
|
||||
await initController();
|
||||
const mockedGlobal = mockGlobalThis();
|
||||
|
||||
await controller.start();
|
||||
controller.mqtt.onMessage("homeassistant/status", Buffer.from("online", "utf8"));
|
||||
await settle(mockedGlobal);
|
||||
};
|
||||
|
||||
const teardown = async () => {
|
||||
await controller.stop();
|
||||
unmockGlobalThis();
|
||||
};
|
||||
|
||||
bench(
|
||||
"[HA] receive device message",
|
||||
async () => {
|
||||
const mockedGlobal = mockGlobalThis();
|
||||
|
||||
controller.eventBus.emitDeviceMessage({
|
||||
type: "attributeReport",
|
||||
device: controller.zigbee.resolveEntity("0xf1f1f1f1f1f1f1f1"),
|
||||
endpoint: ZSpec.HA_ENDPOINT,
|
||||
linkquality: 200,
|
||||
groupID: 0,
|
||||
cluster: "genOnOff",
|
||||
data: {onOff: 1},
|
||||
meta: {},
|
||||
});
|
||||
await settle(mockedGlobal);
|
||||
},
|
||||
{...BENCH_OPTIONS, setup, teardown},
|
||||
);
|
||||
|
||||
bench(
|
||||
"[HA] receive MQTT message",
|
||||
async () => {
|
||||
const mockedGlobal = mockGlobalThis();
|
||||
|
||||
controller.mqtt.onMessage("zigbee2mqtt/0xf1f1f1f1f1f1f1f1/set", Buffer.from(`{"state": "OFF"}`, "utf8"));
|
||||
await settle(mockedGlobal);
|
||||
},
|
||||
{...BENCH_OPTIONS, setup, teardown},
|
||||
);
|
||||
|
||||
bench(
|
||||
"[HA] receive MQTT discovery message",
|
||||
async () => {
|
||||
const mockedGlobal = mockGlobalThis();
|
||||
|
||||
controller.mqtt.onMessage(
|
||||
"homeassistant/sensor/0xe2e2e2e2e2e2e2e2/update/config",
|
||||
Buffer.from(stringify({availability: [{topic: "zigbee2mqtt/bridge/state", value_template: "{{ value_json.state }}"}]}), "utf8"),
|
||||
);
|
||||
await settle(mockedGlobal);
|
||||
},
|
||||
{...BENCH_OPTIONS, setup, teardown},
|
||||
);
|
||||
});
|
||||
});
|
||||
+13
-27
@@ -1,3 +1,5 @@
|
||||
// biome-ignore assist/source/organizeImports: import mocks first
|
||||
import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from "vitest";
|
||||
import * as data from "./mocks/data";
|
||||
import {mockLogger} from "./mocks/logger";
|
||||
import {
|
||||
@@ -9,23 +11,19 @@ import {
|
||||
mockMQTTUnsubscribeAsync,
|
||||
} from "./mocks/mqtt";
|
||||
import {flushPromises} from "./mocks/utils";
|
||||
import {devices, mockController as mockZHController, events as mockZHEvents, returnDevices} from "./mocks/zigbeeHerdsman";
|
||||
|
||||
import type {Mock, MockInstance} from "vitest";
|
||||
|
||||
import type Device from "../lib/model/device";
|
||||
import type {Device as ZhDevice} from "./mocks/zigbeeHerdsman";
|
||||
import {devices, mockController as mockZHController, events as mockZHEvents, returnDevices} from "./mocks/zigbeeHerdsman";
|
||||
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import stringify from "json-stable-stringify-without-jsonify";
|
||||
import tmp from "tmp";
|
||||
|
||||
import type {Mock, MockInstance} from "vitest";
|
||||
import {Controller as ZHController} from "zigbee-herdsman";
|
||||
|
||||
import {Controller} from "../lib/controller";
|
||||
import type Device from "../lib/model/device";
|
||||
import * as settings from "../lib/util/settings";
|
||||
|
||||
const LOG_MQTT_NS = "z2m:mqtt";
|
||||
@@ -58,7 +56,6 @@ describe("Controller", () => {
|
||||
let mockExit: Mock;
|
||||
|
||||
const getZ2MDevice = (zhDevice: string | number | ZhDevice): Device => {
|
||||
// @ts-expect-error private
|
||||
return controller.zigbee.resolveEntity(zhDevice)! as Device;
|
||||
};
|
||||
|
||||
@@ -115,6 +112,8 @@ describe("Controller", () => {
|
||||
expect(mockMQTTConnectAsync).toHaveBeenCalledWith("mqtt://localhost", {
|
||||
will: {payload: Buffer.from('{"state":"offline"}'), retain: true, topic: "zigbee2mqtt/bridge/state", qos: 1},
|
||||
properties: {maximumPacketSize: 1048576},
|
||||
keepalive: 60,
|
||||
protocolVersion: 4,
|
||||
});
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
"zigbee2mqtt/bulb",
|
||||
@@ -296,11 +295,9 @@ describe("Controller", () => {
|
||||
await controller.start();
|
||||
await flushPromises();
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
// @ts-expect-error private
|
||||
await controller.mqtt.publish("z2m/#/status", "empty");
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledTimes(0);
|
||||
expect(mockLogger.error).toHaveBeenCalledWith(`Topic 'z2m/#/status' includes wildcard characters, skipping publish.`);
|
||||
// @ts-expect-error private
|
||||
await controller.mqtt.publish("z2m/+/status", "empty");
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledTimes(0);
|
||||
expect(mockLogger.error).toHaveBeenCalledWith(`Topic 'z2m/+/status' includes wildcard characters, skipping publish.`);
|
||||
@@ -413,14 +410,15 @@ describe("Controller", () => {
|
||||
});
|
||||
|
||||
it("Start controller adapter disconnects", async () => {
|
||||
mockZHController.stop.mockRejectedValueOnce("failed");
|
||||
// Fail to stop extension exit code 1 should not override adapter disconnect exit code 2
|
||||
vi.spyOn(Array.from(controller.extensions)[0], "stop").mockRejectedValueOnce(new Error("failed"));
|
||||
await controller.start();
|
||||
await mockZHEvents.adapterDisconnected();
|
||||
await flushPromises();
|
||||
expect(mockMQTTEndAsync).toHaveBeenCalledTimes(1);
|
||||
expect(mockZHController.stop).toHaveBeenCalledTimes(1);
|
||||
expect(mockExit).toHaveBeenCalledTimes(1);
|
||||
expect(mockExit).toHaveBeenCalledWith(1, false);
|
||||
expect(mockExit).toHaveBeenCalledWith(2, false);
|
||||
});
|
||||
|
||||
it("does not throw when extension fails to stop on controller stop", async () => {
|
||||
@@ -503,7 +501,6 @@ describe("Controller", () => {
|
||||
});
|
||||
|
||||
it("Handle mqtt message", async () => {
|
||||
// @ts-expect-error private
|
||||
const spyEventbusEmitMQTTMessage = vi.spyOn(controller.eventBus, "emitMQTTMessage").mockImplementation(vi.fn());
|
||||
|
||||
await controller.start();
|
||||
@@ -514,7 +511,6 @@ describe("Controller", () => {
|
||||
});
|
||||
|
||||
it("Skip MQTT messages on topic we published to", async () => {
|
||||
// @ts-expect-error private
|
||||
const spyEventbusEmitMQTTMessage = vi.spyOn(controller.eventBus, "emitMQTTMessage").mockImplementation(vi.fn());
|
||||
|
||||
await controller.start();
|
||||
@@ -522,7 +518,6 @@ describe("Controller", () => {
|
||||
await mockMQTTEvents.message("zigbee2mqtt/skip-this-topic", "skipped");
|
||||
expect(spyEventbusEmitMQTTMessage).toHaveBeenCalledWith({topic: "zigbee2mqtt/skip-this-topic", message: "skipped"});
|
||||
mockLogger.debug.mockClear();
|
||||
// @ts-expect-error private
|
||||
await controller.mqtt.publish("skip-this-topic", "", {});
|
||||
await mockMQTTEvents.message("zigbee2mqtt/skip-this-topic", "skipped");
|
||||
expect(mockLogger.debug).toHaveBeenCalledTimes(0);
|
||||
@@ -844,13 +839,11 @@ describe("Controller", () => {
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
|
||||
const device = getZ2MDevice("bulb");
|
||||
// @ts-expect-error private
|
||||
expect(controller.state.get(device)).toStrictEqual({brightness: 50, color_temp: 370, linkquality: 99, state: "ON"});
|
||||
|
||||
await controller.publishEntityState(device, {state: "ON", brightness: 200, color_temp: 370, linkquality: 87});
|
||||
await flushPromises();
|
||||
|
||||
// @ts-expect-error private
|
||||
expect(controller.state.get(device)).toStrictEqual({brightness: 200, color_temp: 370, state: "ON"});
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledTimes(5);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith("zigbee2mqtt/bulb/state", "ON", {qos: 0, retain: true});
|
||||
@@ -870,13 +863,11 @@ describe("Controller", () => {
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
|
||||
const device = getZ2MDevice("bulb");
|
||||
// @ts-expect-error private
|
||||
expect(controller.state.get(device)).toStrictEqual({brightness: 50, color_temp: 370, linkquality: 99, state: "ON"});
|
||||
|
||||
await controller.publishEntityState(device, {state: "ON", brightness: 200, color_temp: 370, linkquality: 87});
|
||||
await flushPromises();
|
||||
|
||||
// @ts-expect-error private
|
||||
expect(controller.state.get(device)).toStrictEqual({brightness: 200, color_temp: 370, state: "ON"});
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledTimes(5);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith("zigbee2mqtt/bulb/state", "ON", {qos: 0, retain: true});
|
||||
@@ -1048,6 +1039,8 @@ describe("Controller", () => {
|
||||
expect(mockMQTTConnectAsync).toHaveBeenCalledTimes(1);
|
||||
const expected = {
|
||||
will: {payload: Buffer.from('{"state":"offline"}'), retain: false, topic: "zigbee2mqtt/bridge/state", qos: 1},
|
||||
keepalive: 60,
|
||||
protocolVersion: 4,
|
||||
properties: {maximumPacketSize: 1048576},
|
||||
};
|
||||
expect(mockMQTTConnectAsync).toHaveBeenCalledWith("mqtt://localhost", expected);
|
||||
@@ -1057,10 +1050,7 @@ describe("Controller", () => {
|
||||
await controller.start();
|
||||
await flushPromises();
|
||||
|
||||
const retainedMessages = Object.keys(
|
||||
// @ts-expect-error private
|
||||
controller.mqtt.retainedMessages,
|
||||
).length;
|
||||
const retainedMessages = Object.keys(controller.mqtt.retainedMessages).length;
|
||||
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
await vi.advanceTimersByTimeAsync(2500); // before any startup configure triggers
|
||||
@@ -1081,7 +1071,6 @@ describe("Controller", () => {
|
||||
|
||||
it("Should prevent any message being published with retain flag when force_disable_retain is set", async () => {
|
||||
settings.set(["mqtt", "force_disable_retain"], true);
|
||||
// @ts-expect-error private
|
||||
await controller.mqtt.connect();
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
// @ts-expect-error private
|
||||
@@ -1139,7 +1128,6 @@ describe("Controller", () => {
|
||||
it("Should remove state of removed device when stopped", async () => {
|
||||
await controller.start();
|
||||
const device = getZ2MDevice("bulb");
|
||||
// @ts-expect-error private
|
||||
expect(controller.state.get(device)).toStrictEqual({brightness: 50, color_temp: 370, linkquality: 99, state: "ON"});
|
||||
device.zh.isDeleted = true;
|
||||
await controller.stop();
|
||||
@@ -1148,7 +1136,6 @@ describe("Controller", () => {
|
||||
});
|
||||
|
||||
it("EventBus should handle sync errors", async () => {
|
||||
// @ts-expect-error private
|
||||
const eventbus = controller.eventBus;
|
||||
const callback = vi.fn().mockImplementation(() => {
|
||||
throw new Error("Whoops!");
|
||||
@@ -1161,7 +1148,6 @@ describe("Controller", () => {
|
||||
});
|
||||
|
||||
it("EventBus should handle async errors", async () => {
|
||||
// @ts-expect-error private
|
||||
const eventbus = controller.eventBus;
|
||||
const callback = vi.fn().mockRejectedValue(new Error("Whoops!"));
|
||||
eventbus.onStateChange({constructor: {name: "Test"}}, callback);
|
||||
|
||||
+1
-2
@@ -1,7 +1,6 @@
|
||||
import path from "node:path";
|
||||
|
||||
import tmp from "tmp";
|
||||
|
||||
import {describe, expect, it} from "vitest";
|
||||
import data from "../lib/util/data";
|
||||
|
||||
describe("Data", () => {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// biome-ignore assist/source/organizeImports: import mocks first
|
||||
import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from "vitest";
|
||||
import * as data from "../mocks/data";
|
||||
import {mockLogger} from "../mocks/logger";
|
||||
import {events as mockMQTTEvents, mockMQTTPublishAsync} from "../mocks/mqtt";
|
||||
@@ -5,9 +7,7 @@ import {flushPromises} from "../mocks/utils";
|
||||
import {devices, events as mockZHEvents, returnDevices} from "../mocks/zigbeeHerdsman";
|
||||
|
||||
import assert from "node:assert";
|
||||
|
||||
import stringify from "json-stable-stringify-without-jsonify";
|
||||
|
||||
import {Controller} from "../../lib/controller";
|
||||
import Availability from "../../lib/extension/availability";
|
||||
import * as settings from "../../lib/util/settings";
|
||||
@@ -282,9 +282,7 @@ describe("Extension: Availability", () => {
|
||||
});
|
||||
|
||||
it("Should retrieve device state when it reconnects", async () => {
|
||||
// @ts-expect-error private
|
||||
const device = controller.zigbee.resolveEntity(devices.bulb_color.ieeeAddr);
|
||||
// @ts-expect-error private
|
||||
controller.state.set(device, {state: "OFF"});
|
||||
|
||||
const endpoint = devices.bulb_color.getEndpoint(1);
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// biome-ignore assist/source/organizeImports: import mocks first
|
||||
import {afterAll, beforeAll, beforeEach, describe, expect, it, vi} from "vitest";
|
||||
import * as data from "../mocks/data";
|
||||
import {mockDebounce} from "../mocks/debounce";
|
||||
import {mockLogger} from "../mocks/logger";
|
||||
@@ -6,10 +8,10 @@ import {flushPromises} from "../mocks/utils";
|
||||
import {type Device, devices, groups, events as mockZHEvents} from "../mocks/zigbeeHerdsman";
|
||||
|
||||
import stringify from "json-stable-stringify-without-jsonify";
|
||||
|
||||
import {Controller} from "../../lib/controller";
|
||||
import Bind from "../../lib/extension/bind";
|
||||
import * as settings from "../../lib/util/settings";
|
||||
import {DEFAULT_BIND_GROUP_ID} from "../../lib/util/utils";
|
||||
|
||||
const mocksClear = [
|
||||
mockDebounce,
|
||||
@@ -648,9 +650,9 @@ describe("Extension: Bind", () => {
|
||||
mockMQTTEvents.message("zigbee2mqtt/bridge/request/device/unbind", 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(endpoint.unbind).toHaveBeenCalledWith("genOnOff", DEFAULT_BIND_GROUP_ID);
|
||||
expect(endpoint.unbind).toHaveBeenCalledWith("genLevelCtrl", DEFAULT_BIND_GROUP_ID);
|
||||
expect(endpoint.unbind).toHaveBeenCalledWith("genScenes", DEFAULT_BIND_GROUP_ID);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
"zigbee2mqtt/bridge/response/device/unbind",
|
||||
stringify({
|
||||
@@ -793,4 +795,84 @@ describe("Extension: Bind", () => {
|
||||
// Should only call Hue bulb, not e.g. tradfri
|
||||
expect(devices.bulb_2.getEndpoint(1)!.read).toHaveBeenCalledTimes(0);
|
||||
});
|
||||
|
||||
it("clears all bindings", async () => {
|
||||
const device = devices.remote;
|
||||
|
||||
device.mockClear();
|
||||
mockMQTTEvents.message("zigbee2mqtt/bridge/request/device/binds/clear", stringify({transaction: "1234", target: "remote"}));
|
||||
await flushPromises();
|
||||
|
||||
expect(device.clearAllBindings).toHaveBeenCalledTimes(1);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
"zigbee2mqtt/bridge/response/device/binds/clear",
|
||||
stringify({
|
||||
transaction: "1234",
|
||||
data: {
|
||||
target: "remote",
|
||||
ieee_list: ["0xffffffffffffffff"],
|
||||
},
|
||||
status: "ok",
|
||||
}),
|
||||
{},
|
||||
);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith("zigbee2mqtt/bridge/devices", expect.any(String), {retain: true});
|
||||
});
|
||||
|
||||
it("clears targeted bindings", async () => {
|
||||
const device = devices.remote;
|
||||
const target = devices.bulb_color;
|
||||
|
||||
device.mockClear();
|
||||
mockMQTTEvents.message(
|
||||
"zigbee2mqtt/bridge/request/device/binds/clear",
|
||||
stringify({transaction: "1234", target: "remote", ieee_list: [target.ieeeAddr]}),
|
||||
);
|
||||
await flushPromises();
|
||||
|
||||
expect(device.clearAllBindings).toHaveBeenCalledTimes(1);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
"zigbee2mqtt/bridge/response/device/binds/clear",
|
||||
stringify({
|
||||
transaction: "1234",
|
||||
data: {
|
||||
target: "remote",
|
||||
ieee_list: [target.ieeeAddr],
|
||||
},
|
||||
status: "ok",
|
||||
}),
|
||||
{},
|
||||
);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith("zigbee2mqtt/bridge/devices", expect.any(String), {retain: true});
|
||||
});
|
||||
|
||||
it("throw on invalid clears bindings payload", async () => {
|
||||
const device = devices.remote;
|
||||
|
||||
device.mockClear();
|
||||
mockMQTTEvents.message("zigbee2mqtt/bridge/request/device/binds/clear", stringify({targetz: "remote"}));
|
||||
await flushPromises();
|
||||
|
||||
expect(device.clearAllBindings).toHaveBeenCalledTimes(0);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
"zigbee2mqtt/bridge/response/device/binds/clear",
|
||||
stringify({data: {}, status: "error", error: "Invalid payload"}),
|
||||
{},
|
||||
);
|
||||
});
|
||||
|
||||
it("throw on invalid clears bindings target", async () => {
|
||||
const device = devices.remote;
|
||||
|
||||
device.mockClear();
|
||||
mockMQTTEvents.message("zigbee2mqtt/bridge/request/device/binds/clear", stringify({target: "remotez"}));
|
||||
await flushPromises();
|
||||
|
||||
expect(device.clearAllBindings).toHaveBeenCalledTimes(0);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
"zigbee2mqtt/bridge/response/device/binds/clear",
|
||||
stringify({data: {}, status: "error", error: "Invalid target"}),
|
||||
{},
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
+448
-44
@@ -1,3 +1,6 @@
|
||||
// biome-ignore assist/source/organizeImports: import mocks first
|
||||
import {afterAll, beforeAll, beforeEach, describe, expect, it, vi} from "vitest";
|
||||
import {Zdo} from "zigbee-herdsman";
|
||||
import * as data from "../mocks/data";
|
||||
import {mockJSZipFile, mockJSZipGenerateAsync} from "../mocks/jszip";
|
||||
import {mockLogger} from "../mocks/logger";
|
||||
@@ -5,18 +8,17 @@ import {events as mockMQTTEvents, mockMQTTPublishAsync} from "../mocks/mqtt";
|
||||
import {flushPromises} from "../mocks/utils";
|
||||
import {CUSTOM_CLUSTERS, devices, groups, mockController as mockZHController, events as mockZHEvents, returnDevices} from "../mocks/zigbeeHerdsman";
|
||||
|
||||
import type {Mock} from "vitest";
|
||||
|
||||
import assert from "node:assert";
|
||||
import fs from "node:fs";
|
||||
import {platform} from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import stringify from "json-stable-stringify-without-jsonify";
|
||||
|
||||
import type {Mock} from "vitest";
|
||||
import {Controller} from "../../lib/controller";
|
||||
import Bridge from "../../lib/extension/bridge";
|
||||
import * as settings from "../../lib/util/settings";
|
||||
import utils from "../../lib/util/utils";
|
||||
import utils, {DEFAULT_BIND_GROUP_ID} from "../../lib/util/utils";
|
||||
import {Zcl} from "zigbee-herdsman";
|
||||
|
||||
returnDevices.push(devices.coordinator.ieeeAddr);
|
||||
returnDevices.push(devices.bulb.ieeeAddr);
|
||||
@@ -41,6 +43,19 @@ const mocksClear = [
|
||||
|
||||
const deviceIconsDir = path.join(data.mockDir, "device_icons");
|
||||
|
||||
vi.mock("node:os", async (importOriginal) => ({
|
||||
...(await importOriginal()),
|
||||
version: vi.fn(() => "Linux"),
|
||||
release: vi.fn(() => "0.0.1"),
|
||||
arch: vi.fn(() => "x64"),
|
||||
cpus: vi.fn(() => [{model: "Intel Core i7-9999"}]),
|
||||
totalmem: vi.fn(() => 10485760),
|
||||
}));
|
||||
vi.mock("node:process", async (importOriginal) => ({
|
||||
...(await importOriginal()),
|
||||
version: "v1.2.3",
|
||||
}));
|
||||
|
||||
describe("Extension: Bridge", () => {
|
||||
let controller: Controller;
|
||||
let mockRestart: Mock;
|
||||
@@ -94,12 +109,16 @@ describe("Extension: Bridge", () => {
|
||||
const zhVersion = await utils.getDependencyVersion("zigbee-herdsman");
|
||||
const zhcVersion = await utils.getDependencyVersion("zigbee-herdsman-converters");
|
||||
const directory = settings.get().advanced.log_directory;
|
||||
// console.log(mockMQTTPublishAsync.mock.calls.find((c) => c[0] === 'zigbee2mqtt/bridge/info')![1]);
|
||||
// console.log(mockMQTTPublishAsync.mock.calls.find((c) => c[0] === "zigbee2mqtt/bridge/info")![1]);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
"zigbee2mqtt/bridge/info",
|
||||
stringify({
|
||||
commit: version.commitHash,
|
||||
config: {
|
||||
health: {
|
||||
interval: 10,
|
||||
reset_on_check: false,
|
||||
},
|
||||
advanced: {
|
||||
adapter_concurrent: undefined,
|
||||
adapter_delay: undefined,
|
||||
@@ -145,6 +164,7 @@ describe("Extension: Bridge", () => {
|
||||
"0x0017880104a44559": {friendly_name: "J1_cover"},
|
||||
"0x0017880104e43559": {friendly_name: "U202DST600ZB"},
|
||||
"0x0017880104e44559": {friendly_name: "3157100_thermostat"},
|
||||
"0x18fc2600000d7ae3": {friendly_name: "bosch_rm230z"},
|
||||
"0x0017880104e45517": {friendly_name: "remote", retain: true},
|
||||
"0x0017880104e45520": {friendly_name: "button", retain: false},
|
||||
"0x0017880104e45521": {
|
||||
@@ -268,7 +288,7 @@ describe("Extension: Bridge", () => {
|
||||
},
|
||||
frontend: {
|
||||
enabled: false,
|
||||
package: "zigbee2mqtt-frontend",
|
||||
package: "zigbee2mqtt-windfront",
|
||||
port: 8080,
|
||||
base_url: "/",
|
||||
},
|
||||
@@ -294,6 +314,9 @@ describe("Extension: Bridge", () => {
|
||||
force_disable_retain: false,
|
||||
include_device_information: false,
|
||||
maximum_packet_size: 1048576,
|
||||
keepalive: 60,
|
||||
reject_unauthorized: true,
|
||||
version: 4,
|
||||
server: "mqtt://localhost",
|
||||
},
|
||||
ota: {
|
||||
@@ -315,6 +338,16 @@ describe("Extension: Bridge", () => {
|
||||
version: version.version,
|
||||
zigbee_herdsman: zhVersion,
|
||||
zigbee_herdsman_converters: zhcVersion,
|
||||
os: {
|
||||
version: "Linux - 0.0.1 - x64",
|
||||
node_version: "v1.2.3",
|
||||
cpus: "Intel Core i7-9999 (x1)",
|
||||
memory_mb: 10,
|
||||
},
|
||||
mqtt: {
|
||||
server: "mqtt://localhost:1883",
|
||||
version: 5,
|
||||
},
|
||||
}),
|
||||
{retain: true},
|
||||
);
|
||||
@@ -322,7 +355,7 @@ describe("Extension: Bridge", () => {
|
||||
|
||||
it("Should publish devices on startup", async () => {
|
||||
await resetExtension();
|
||||
// console.log(mockMQTTPublishAsync.mock.calls.find((c) => c[0] === 'zigbee2mqtt/bridge/devices')[1]);
|
||||
// console.log(mockMQTTPublishAsync.mock.calls.find((c) => c[0] === "zigbee2mqtt/bridge/devices")[1]);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
"zigbee2mqtt/bridge/devices",
|
||||
stringify([
|
||||
@@ -340,6 +373,7 @@ describe("Extension: Bridge", () => {
|
||||
},
|
||||
{
|
||||
definition: {
|
||||
source: "native",
|
||||
description: "TRADFRI bulb E26/E27, white spectrum, globe, opal, 980 lm",
|
||||
exposes: [
|
||||
{
|
||||
@@ -514,6 +548,7 @@ describe("Extension: Bridge", () => {
|
||||
property: "transition",
|
||||
type: "numeric",
|
||||
value_min: 0,
|
||||
value_step: 0.1,
|
||||
},
|
||||
{
|
||||
access: 2,
|
||||
@@ -597,6 +632,7 @@ describe("Extension: Bridge", () => {
|
||||
{
|
||||
date_code: "2019.09",
|
||||
definition: {
|
||||
source: "native",
|
||||
description: "Hue Go",
|
||||
exposes: [
|
||||
{
|
||||
@@ -739,6 +775,7 @@ describe("Extension: Bridge", () => {
|
||||
property: "transition",
|
||||
type: "numeric",
|
||||
value_min: 0,
|
||||
value_step: 0.1,
|
||||
},
|
||||
{
|
||||
access: 2,
|
||||
@@ -792,6 +829,7 @@ describe("Extension: Bridge", () => {
|
||||
},
|
||||
{
|
||||
definition: {
|
||||
source: "native",
|
||||
description: "Hue dimmer switch",
|
||||
exposes: [
|
||||
{
|
||||
@@ -895,6 +933,7 @@ describe("Extension: Bridge", () => {
|
||||
disabled: false,
|
||||
endpoints: {
|
||||
"1": {
|
||||
name: "ep1",
|
||||
bindings: [
|
||||
{cluster: "genLevelCtrl", target: {endpoint: 1, ieee_address: "0x000b57fffec6a5b3", type: "endpoint"}},
|
||||
{cluster: "genOnOff", target: {endpoint: 1, ieee_address: "0x000b57fffec6a5b3", type: "endpoint"}},
|
||||
@@ -906,7 +945,13 @@ describe("Extension: Bridge", () => {
|
||||
configured_reportings: [],
|
||||
scenes: [],
|
||||
},
|
||||
"2": {bindings: [], clusters: {input: ["genBasic"], output: ["genOta", "genOnOff"]}, configured_reportings: [], scenes: []},
|
||||
"2": {
|
||||
name: "ep2",
|
||||
bindings: [],
|
||||
clusters: {input: ["genBasic"], output: ["genOta", "genOnOff"]},
|
||||
configured_reportings: [],
|
||||
scenes: [],
|
||||
},
|
||||
},
|
||||
friendly_name: "remote",
|
||||
ieee_address: "0x0017880104e45517",
|
||||
@@ -921,6 +966,7 @@ describe("Extension: Bridge", () => {
|
||||
},
|
||||
{
|
||||
definition: {
|
||||
source: "generated",
|
||||
description: "Automatically generated definition",
|
||||
exposes: [
|
||||
{
|
||||
@@ -1015,6 +1061,7 @@ describe("Extension: Bridge", () => {
|
||||
},
|
||||
{
|
||||
definition: {
|
||||
source: "native",
|
||||
description: "Wireless mini switch",
|
||||
exposes: [
|
||||
{
|
||||
@@ -1090,6 +1137,7 @@ describe("Extension: Bridge", () => {
|
||||
name: "device_temperature_calibration",
|
||||
property: "device_temperature_calibration",
|
||||
type: "numeric",
|
||||
value_step: 0.1,
|
||||
},
|
||||
],
|
||||
supports_ota: false,
|
||||
@@ -1125,6 +1173,7 @@ describe("Extension: Bridge", () => {
|
||||
},
|
||||
{
|
||||
definition: {
|
||||
source: "native",
|
||||
description: "Temperature and humidity sensor",
|
||||
exposes: [
|
||||
{
|
||||
@@ -1198,6 +1247,7 @@ describe("Extension: Bridge", () => {
|
||||
name: "temperature_calibration",
|
||||
property: "temperature_calibration",
|
||||
type: "numeric",
|
||||
value_step: 0.1,
|
||||
},
|
||||
{
|
||||
access: 2,
|
||||
@@ -1217,6 +1267,7 @@ describe("Extension: Bridge", () => {
|
||||
name: "humidity_calibration",
|
||||
property: "humidity_calibration",
|
||||
type: "numeric",
|
||||
value_step: 0.1,
|
||||
},
|
||||
{
|
||||
access: 2,
|
||||
@@ -1236,6 +1287,7 @@ describe("Extension: Bridge", () => {
|
||||
name: "pressure_calibration",
|
||||
property: "pressure_calibration",
|
||||
type: "numeric",
|
||||
value_step: 0.1,
|
||||
},
|
||||
{
|
||||
access: 2,
|
||||
@@ -1267,6 +1319,7 @@ describe("Extension: Bridge", () => {
|
||||
},
|
||||
{
|
||||
definition: {
|
||||
source: "native",
|
||||
description: "Mi smart plug",
|
||||
exposes: [
|
||||
{
|
||||
@@ -1346,6 +1399,7 @@ describe("Extension: Bridge", () => {
|
||||
name: "power_calibration",
|
||||
property: "power_calibration",
|
||||
type: "numeric",
|
||||
value_step: 0.1,
|
||||
},
|
||||
{
|
||||
access: 2,
|
||||
@@ -1365,6 +1419,7 @@ describe("Extension: Bridge", () => {
|
||||
name: "energy_calibration",
|
||||
property: "energy_calibration",
|
||||
type: "numeric",
|
||||
value_step: 0.1,
|
||||
},
|
||||
{
|
||||
access: 2,
|
||||
@@ -1384,6 +1439,7 @@ describe("Extension: Bridge", () => {
|
||||
name: "device_temperature_calibration",
|
||||
property: "device_temperature_calibration",
|
||||
type: "numeric",
|
||||
value_step: 0.1,
|
||||
},
|
||||
{
|
||||
access: 2,
|
||||
@@ -1414,6 +1470,7 @@ describe("Extension: Bridge", () => {
|
||||
},
|
||||
{
|
||||
definition: {
|
||||
source: "native",
|
||||
description: "zigfred plus smart in-wall switch",
|
||||
exposes: [
|
||||
{
|
||||
@@ -1831,6 +1888,7 @@ describe("Extension: Bridge", () => {
|
||||
property: "transition",
|
||||
type: "numeric",
|
||||
value_min: 0,
|
||||
value_step: 0.1,
|
||||
},
|
||||
{
|
||||
access: 2,
|
||||
@@ -1859,42 +1917,49 @@ describe("Extension: Bridge", () => {
|
||||
disabled: false,
|
||||
endpoints: {
|
||||
"10": {
|
||||
name: "l5",
|
||||
bindings: [],
|
||||
clusters: {input: ["genBasic", "genScenes", "genOnOff", "genLevelCtrl"], output: []},
|
||||
configured_reportings: [],
|
||||
scenes: [],
|
||||
},
|
||||
"11": {
|
||||
name: "l6",
|
||||
bindings: [],
|
||||
clusters: {input: ["genBasic", "genScenes", "closuresWindowCovering"], output: []},
|
||||
configured_reportings: [],
|
||||
scenes: [],
|
||||
},
|
||||
"12": {
|
||||
name: "l7",
|
||||
bindings: [],
|
||||
clusters: {input: ["genBasic", "genScenes", "closuresWindowCovering"], output: []},
|
||||
configured_reportings: [],
|
||||
scenes: [],
|
||||
},
|
||||
"5": {
|
||||
name: "l1",
|
||||
bindings: [],
|
||||
clusters: {input: ["genBasic", "genScenes", "genOnOff", "genLevelCtrl", "lightingColorCtrl"], output: []},
|
||||
configured_reportings: [],
|
||||
scenes: [],
|
||||
},
|
||||
"7": {
|
||||
name: "l2",
|
||||
bindings: [],
|
||||
clusters: {input: ["genBasic", "genScenes", "genOnOff", "genLevelCtrl"], output: []},
|
||||
configured_reportings: [],
|
||||
scenes: [],
|
||||
},
|
||||
"8": {
|
||||
name: "l3",
|
||||
bindings: [],
|
||||
clusters: {input: ["genBasic", "genScenes", "genOnOff", "genLevelCtrl"], output: []},
|
||||
configured_reportings: [],
|
||||
scenes: [],
|
||||
},
|
||||
"9": {
|
||||
name: "l4",
|
||||
bindings: [],
|
||||
clusters: {input: ["genBasic", "genScenes", "genOnOff", "genLevelCtrl"], output: []},
|
||||
configured_reportings: [],
|
||||
@@ -1915,6 +1980,7 @@ describe("Extension: Bridge", () => {
|
||||
},
|
||||
{
|
||||
definition: {
|
||||
source: "native",
|
||||
description: "TRADFRI bulb E26/E27, white spectrum, globe, opal, 980 lm",
|
||||
exposes: [
|
||||
{
|
||||
@@ -2089,6 +2155,7 @@ describe("Extension: Bridge", () => {
|
||||
property: "transition",
|
||||
type: "numeric",
|
||||
value_min: 0,
|
||||
value_step: 0.1,
|
||||
},
|
||||
{
|
||||
access: 2,
|
||||
@@ -2260,7 +2327,7 @@ describe("Extension: Bridge", () => {
|
||||
scenes: [],
|
||||
},
|
||||
{friendly_name: "gledopto_group", id: 21, members: [{endpoint: 15, ieee_address: "0x0017880104e45724"}], scenes: []},
|
||||
{friendly_name: "default_bind_group", id: 901, members: [], scenes: []},
|
||||
{friendly_name: "default_bind_group", id: DEFAULT_BIND_GROUP_ID, members: [], scenes: []},
|
||||
{
|
||||
friendly_name: "ha_discovery_group",
|
||||
id: 9,
|
||||
@@ -2349,6 +2416,7 @@ describe("Extension: Bridge", () => {
|
||||
stringify({
|
||||
data: {
|
||||
definition: {
|
||||
source: "native",
|
||||
description: "TRADFRI bulb E26/E27, white spectrum, globe, opal, 980 lm",
|
||||
exposes: [
|
||||
{
|
||||
@@ -2522,6 +2590,7 @@ describe("Extension: Bridge", () => {
|
||||
property: "transition",
|
||||
type: "numeric",
|
||||
value_min: 0,
|
||||
value_step: 0.1,
|
||||
},
|
||||
{
|
||||
access: 2,
|
||||
@@ -2584,6 +2653,7 @@ describe("Extension: Bridge", () => {
|
||||
stringify({
|
||||
data: {
|
||||
definition: {
|
||||
source: "generated",
|
||||
description: "Automatically generated definition",
|
||||
exposes: [
|
||||
{
|
||||
@@ -2909,11 +2979,13 @@ describe("Extension: Bridge", () => {
|
||||
|
||||
it("Should allow to remove group", async () => {
|
||||
const group = groups.group_1;
|
||||
const removeGroupFromLookup = vi.spyOn(controller.zigbee, "removeGroupFromLookup");
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
mockMQTTEvents.message("zigbee2mqtt/bridge/request/group/remove", "group_1");
|
||||
await flushPromises();
|
||||
expect(group.removeFromNetwork).toHaveBeenCalledTimes(1);
|
||||
expect(settings.getGroup("group_1")).toBeUndefined();
|
||||
expect(removeGroupFromLookup).toHaveBeenCalledWith(1);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith("zigbee2mqtt/bridge/groups", expect.any(String), expect.any(Object));
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
"zigbee2mqtt/bridge/response/group/remove",
|
||||
@@ -3119,7 +3191,6 @@ describe("Extension: Bridge", () => {
|
||||
});
|
||||
|
||||
it("Should allow interviewing a device by ieeeAddr", async () => {
|
||||
// @ts-expect-error private
|
||||
const device = controller.zigbee.resolveEntity(devices.bulb)!;
|
||||
assert("resolveDefinition" in device);
|
||||
device.resolveDefinition = vi.fn();
|
||||
@@ -3237,7 +3308,6 @@ describe("Extension: Bridge", () => {
|
||||
" vendor: '',\n" +
|
||||
" description: 'Automatically generated definition',\n" +
|
||||
' extend: [m.onOff({"powerOnBehavior":false})],\n' +
|
||||
" meta: {},\n" +
|
||||
"};\n",
|
||||
},
|
||||
status: "ok",
|
||||
@@ -3470,11 +3540,11 @@ describe("Extension: Bridge", () => {
|
||||
|
||||
it("Should allow to touchlink factory reset (succeeds)", async () => {
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
mockZHController.touchlinkFactoryResetFirst.mockClear();
|
||||
mockZHController.touchlinkFactoryResetFirst.mockReturnValueOnce(true);
|
||||
mockZHController.touchlink.factoryResetFirst.mockClear();
|
||||
mockZHController.touchlink.factoryResetFirst.mockReturnValueOnce(true);
|
||||
mockMQTTEvents.message("zigbee2mqtt/bridge/request/touchlink/factory_reset", "");
|
||||
await flushPromises();
|
||||
expect(mockZHController.touchlinkFactoryResetFirst).toHaveBeenCalledTimes(1);
|
||||
expect(mockZHController.touchlink.factoryResetFirst).toHaveBeenCalledTimes(1);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
"zigbee2mqtt/bridge/response/touchlink/factory_reset",
|
||||
stringify({data: {}, status: "ok"}),
|
||||
@@ -3484,12 +3554,12 @@ describe("Extension: Bridge", () => {
|
||||
|
||||
it("Should allow to touchlink factory reset specific device", async () => {
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
mockZHController.touchlinkFactoryReset.mockClear();
|
||||
mockZHController.touchlinkFactoryReset.mockReturnValueOnce(true);
|
||||
mockZHController.touchlink.factoryReset.mockClear();
|
||||
mockZHController.touchlink.factoryReset.mockReturnValueOnce(true);
|
||||
mockMQTTEvents.message("zigbee2mqtt/bridge/request/touchlink/factory_reset", stringify({ieee_address: "0x1239", channel: 12}));
|
||||
await flushPromises();
|
||||
expect(mockZHController.touchlinkFactoryReset).toHaveBeenCalledTimes(1);
|
||||
expect(mockZHController.touchlinkFactoryReset).toHaveBeenCalledWith("0x1239", 12);
|
||||
expect(mockZHController.touchlink.factoryReset).toHaveBeenCalledTimes(1);
|
||||
expect(mockZHController.touchlink.factoryReset).toHaveBeenCalledWith("0x1239", 12);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
"zigbee2mqtt/bridge/response/touchlink/factory_reset",
|
||||
stringify({data: {ieee_address: "0x1239", channel: 12}, status: "ok"}),
|
||||
@@ -3540,11 +3610,11 @@ describe("Extension: Bridge", () => {
|
||||
|
||||
it("Should allow to touchlink identify specific device", async () => {
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
mockZHController.touchlinkIdentify.mockClear();
|
||||
mockZHController.touchlink.identify.mockClear();
|
||||
mockMQTTEvents.message("zigbee2mqtt/bridge/request/touchlink/identify", stringify({ieee_address: "0x1239", channel: 12}));
|
||||
await flushPromises();
|
||||
expect(mockZHController.touchlinkIdentify).toHaveBeenCalledTimes(1);
|
||||
expect(mockZHController.touchlinkIdentify).toHaveBeenCalledWith("0x1239", 12);
|
||||
expect(mockZHController.touchlink.identify).toHaveBeenCalledTimes(1);
|
||||
expect(mockZHController.touchlink.identify).toHaveBeenCalledWith("0x1239", 12);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
"zigbee2mqtt/bridge/response/touchlink/identify",
|
||||
stringify({data: {ieee_address: "0x1239", channel: 12}, status: "ok"}),
|
||||
@@ -3554,10 +3624,10 @@ describe("Extension: Bridge", () => {
|
||||
|
||||
it("Touchlink identify fails when payload is invalid", async () => {
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
mockZHController.touchlinkIdentify.mockClear();
|
||||
mockZHController.touchlink.identify.mockClear();
|
||||
mockMQTTEvents.message("zigbee2mqtt/bridge/request/touchlink/identify", stringify({ieee_address: "0x1239"}));
|
||||
await flushPromises();
|
||||
expect(mockZHController.touchlinkIdentify).toHaveBeenCalledTimes(0);
|
||||
expect(mockZHController.touchlink.identify).toHaveBeenCalledTimes(0);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
"zigbee2mqtt/bridge/response/touchlink/identify",
|
||||
stringify({data: {}, status: "error", error: "Invalid payload"}),
|
||||
@@ -3567,11 +3637,11 @@ describe("Extension: Bridge", () => {
|
||||
|
||||
it("Should allow to touchlink factory reset (fails)", async () => {
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
mockZHController.touchlinkFactoryResetFirst.mockClear();
|
||||
mockZHController.touchlinkFactoryResetFirst.mockReturnValueOnce(false);
|
||||
mockZHController.touchlink.factoryResetFirst.mockClear();
|
||||
mockZHController.touchlink.factoryResetFirst.mockReturnValueOnce(false);
|
||||
mockMQTTEvents.message("zigbee2mqtt/bridge/request/touchlink/factory_reset", "");
|
||||
await flushPromises();
|
||||
expect(mockZHController.touchlinkFactoryResetFirst).toHaveBeenCalledTimes(1);
|
||||
expect(mockZHController.touchlink.factoryResetFirst).toHaveBeenCalledTimes(1);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
"zigbee2mqtt/bridge/response/touchlink/factory_reset",
|
||||
stringify({data: {}, status: "error", error: "Failed to factory reset device through Touchlink"}),
|
||||
@@ -3581,14 +3651,14 @@ describe("Extension: Bridge", () => {
|
||||
|
||||
it("Should allow to touchlink scan", async () => {
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
mockZHController.touchlinkScan.mockClear();
|
||||
mockZHController.touchlinkScan.mockReturnValueOnce([
|
||||
mockZHController.touchlink.scan.mockClear();
|
||||
mockZHController.touchlink.scan.mockReturnValueOnce([
|
||||
{ieeeAddr: "0x123", channel: 12},
|
||||
{ieeeAddr: "0x124", channel: 24},
|
||||
]);
|
||||
mockMQTTEvents.message("zigbee2mqtt/bridge/request/touchlink/scan", "");
|
||||
await flushPromises();
|
||||
expect(mockZHController.touchlinkScan).toHaveBeenCalledTimes(1);
|
||||
expect(mockZHController.touchlink.scan).toHaveBeenCalledTimes(1);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
"zigbee2mqtt/bridge/response/touchlink/scan",
|
||||
stringify({
|
||||
@@ -3611,7 +3681,7 @@ describe("Extension: Bridge", () => {
|
||||
endpoint.configureReporting.mockClear();
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
mockMQTTEvents.message(
|
||||
"zigbee2mqtt/bridge/request/device/configure_reporting",
|
||||
"zigbee2mqtt/bridge/request/device/reporting/configure",
|
||||
stringify({
|
||||
id: "0x000b57fffec6a5b2",
|
||||
endpoint: 1,
|
||||
@@ -3632,7 +3702,7 @@ describe("Extension: Bridge", () => {
|
||||
undefined,
|
||||
);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
"zigbee2mqtt/bridge/response/device/configure_reporting",
|
||||
"zigbee2mqtt/bridge/response/device/reporting/configure",
|
||||
stringify({
|
||||
data: {
|
||||
id: "0x000b57fffec6a5b2",
|
||||
@@ -3657,7 +3727,7 @@ describe("Extension: Bridge", () => {
|
||||
endpoint.configureReporting.mockClear();
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
mockMQTTEvents.message(
|
||||
"zigbee2mqtt/bridge/request/device/configure_reporting",
|
||||
"zigbee2mqtt/bridge/request/device/reporting/configure",
|
||||
stringify({
|
||||
id: "0x000b57fffec6a5b2",
|
||||
endpoint: "1",
|
||||
@@ -3678,7 +3748,7 @@ describe("Extension: Bridge", () => {
|
||||
undefined,
|
||||
);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
"zigbee2mqtt/bridge/response/device/configure_reporting",
|
||||
"zigbee2mqtt/bridge/response/device/reporting/configure",
|
||||
stringify({
|
||||
data: {
|
||||
id: "0x000b57fffec6a5b2",
|
||||
@@ -3702,7 +3772,7 @@ describe("Extension: Bridge", () => {
|
||||
endpoint.configureReporting.mockClear();
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
mockMQTTEvents.message(
|
||||
"zigbee2mqtt/bridge/request/device/configure_reporting",
|
||||
"zigbee2mqtt/bridge/request/device/reporting/configure",
|
||||
stringify({
|
||||
id: "bulb",
|
||||
// endpoint: '1',
|
||||
@@ -3716,7 +3786,7 @@ describe("Extension: Bridge", () => {
|
||||
await flushPromises();
|
||||
expect(endpoint.configureReporting).toHaveBeenCalledTimes(0);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
"zigbee2mqtt/bridge/response/device/configure_reporting",
|
||||
"zigbee2mqtt/bridge/response/device/reporting/configure",
|
||||
stringify({data: {}, status: "error", error: "Invalid payload"}),
|
||||
{},
|
||||
);
|
||||
@@ -3728,7 +3798,7 @@ describe("Extension: Bridge", () => {
|
||||
endpoint.configureReporting.mockClear();
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
mockMQTTEvents.message(
|
||||
"zigbee2mqtt/bridge/request/device/configure_reporting",
|
||||
"zigbee2mqtt/bridge/request/device/reporting/configure",
|
||||
stringify({
|
||||
id: "non_existing_device",
|
||||
endpoint: "1",
|
||||
@@ -3742,7 +3812,7 @@ describe("Extension: Bridge", () => {
|
||||
await flushPromises();
|
||||
expect(endpoint.configureReporting).toHaveBeenCalledTimes(0);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
"zigbee2mqtt/bridge/response/device/configure_reporting",
|
||||
"zigbee2mqtt/bridge/response/device/reporting/configure",
|
||||
stringify({data: {}, status: "error", error: "Device 'non_existing_device' does not exist"}),
|
||||
{},
|
||||
);
|
||||
@@ -3754,7 +3824,7 @@ describe("Extension: Bridge", () => {
|
||||
endpoint.configureReporting.mockClear();
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
mockMQTTEvents.message(
|
||||
"zigbee2mqtt/bridge/request/device/configure_reporting",
|
||||
"zigbee2mqtt/bridge/request/device/reporting/configure",
|
||||
stringify({
|
||||
id: "0x000b57fffec6a5b2",
|
||||
endpoint: "non_existing_endpoint",
|
||||
@@ -3768,7 +3838,243 @@ describe("Extension: Bridge", () => {
|
||||
await flushPromises();
|
||||
expect(endpoint.configureReporting).toHaveBeenCalledTimes(0);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
"zigbee2mqtt/bridge/response/device/configure_reporting",
|
||||
"zigbee2mqtt/bridge/response/device/reporting/configure",
|
||||
stringify({data: {}, status: "error", error: "Device '0x000b57fffec6a5b2' does not have endpoint 'non_existing_endpoint'"}),
|
||||
{},
|
||||
);
|
||||
});
|
||||
|
||||
it("Should allow to read reporting config with endpoint as number", async () => {
|
||||
const device = devices.bulb;
|
||||
const endpoint = device.getEndpoint(1)!;
|
||||
endpoint.bind.mockClear();
|
||||
endpoint.readReportingConfig.mockClear();
|
||||
endpoint.readReportingConfig.mockResolvedValueOnce([
|
||||
{
|
||||
status: Zcl.Status.SUCCESS,
|
||||
direction: Zcl.Direction.CLIENT_TO_SERVER,
|
||||
attrId: Zcl.Clusters.genLevelCtrl.attributes.currentLevel.ID,
|
||||
dataType: Zcl.DataType.UINT8,
|
||||
minRepIntval: 10,
|
||||
maxRepIntval: 60,
|
||||
repChange: 2,
|
||||
},
|
||||
]);
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
mockMQTTEvents.message(
|
||||
"zigbee2mqtt/bridge/request/device/reporting/read",
|
||||
stringify({
|
||||
id: "0x000b57fffec6a5b2",
|
||||
endpoint: 1,
|
||||
cluster: "genLevelCtrl",
|
||||
configs: [{attribute: "currentLevel"}],
|
||||
}),
|
||||
);
|
||||
await flushPromises();
|
||||
expect(endpoint.readReportingConfig).toHaveBeenCalledTimes(1);
|
||||
expect(endpoint.readReportingConfig).toHaveBeenCalledWith("genLevelCtrl", [{attribute: "currentLevel"}], {});
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
"zigbee2mqtt/bridge/response/device/reporting/read",
|
||||
stringify({
|
||||
data: {
|
||||
id: "0x000b57fffec6a5b2",
|
||||
endpoint: 1,
|
||||
cluster: "genLevelCtrl",
|
||||
configs: [
|
||||
{
|
||||
status: Zcl.Status.SUCCESS,
|
||||
direction: Zcl.Direction.CLIENT_TO_SERVER,
|
||||
attrId: Zcl.Clusters.genLevelCtrl.attributes.currentLevel.ID,
|
||||
dataType: Zcl.DataType.UINT8,
|
||||
minRepIntval: 10,
|
||||
maxRepIntval: 60,
|
||||
repChange: 2,
|
||||
},
|
||||
],
|
||||
},
|
||||
status: "ok",
|
||||
}),
|
||||
{},
|
||||
);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith("zigbee2mqtt/bridge/devices", expect.any(String), {retain: true});
|
||||
});
|
||||
|
||||
it("Should allow to read reporting config with endpoint as string", async () => {
|
||||
const device = devices.bulb;
|
||||
const endpoint = device.getEndpoint(1)!;
|
||||
endpoint.bind.mockClear();
|
||||
endpoint.readReportingConfig.mockClear();
|
||||
endpoint.readReportingConfig.mockResolvedValueOnce([
|
||||
{
|
||||
status: Zcl.Status.SUCCESS,
|
||||
direction: Zcl.Direction.CLIENT_TO_SERVER,
|
||||
attrId: Zcl.Clusters.genLevelCtrl.attributes.currentLevel.ID,
|
||||
dataType: Zcl.DataType.UINT8,
|
||||
minRepIntval: 10,
|
||||
maxRepIntval: 60,
|
||||
repChange: 2,
|
||||
},
|
||||
]);
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
mockMQTTEvents.message(
|
||||
"zigbee2mqtt/bridge/request/device/reporting/read",
|
||||
stringify({
|
||||
id: "0x000b57fffec6a5b2",
|
||||
endpoint: "1",
|
||||
cluster: "genLevelCtrl",
|
||||
configs: [{attribute: "currentLevel"}],
|
||||
}),
|
||||
);
|
||||
await flushPromises();
|
||||
expect(endpoint.readReportingConfig).toHaveBeenCalledTimes(1);
|
||||
expect(endpoint.readReportingConfig).toHaveBeenCalledWith("genLevelCtrl", [{attribute: "currentLevel"}], {});
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
"zigbee2mqtt/bridge/response/device/reporting/read",
|
||||
stringify({
|
||||
data: {
|
||||
id: "0x000b57fffec6a5b2",
|
||||
endpoint: "1",
|
||||
cluster: "genLevelCtrl",
|
||||
configs: [
|
||||
{
|
||||
status: Zcl.Status.SUCCESS,
|
||||
direction: Zcl.Direction.CLIENT_TO_SERVER,
|
||||
attrId: Zcl.Clusters.genLevelCtrl.attributes.currentLevel.ID,
|
||||
dataType: Zcl.DataType.UINT8,
|
||||
minRepIntval: 10,
|
||||
maxRepIntval: 60,
|
||||
repChange: 2,
|
||||
},
|
||||
],
|
||||
},
|
||||
status: "ok",
|
||||
}),
|
||||
{},
|
||||
);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith("zigbee2mqtt/bridge/devices", expect.any(String), {retain: true});
|
||||
});
|
||||
|
||||
it("Should allow to read reporting config with manufacturer code", async () => {
|
||||
const device = devices.bulb;
|
||||
const endpoint = device.getEndpoint(1)!;
|
||||
endpoint.bind.mockClear();
|
||||
endpoint.readReportingConfig.mockClear();
|
||||
endpoint.readReportingConfig.mockResolvedValueOnce([
|
||||
{
|
||||
status: Zcl.Status.SUCCESS,
|
||||
direction: Zcl.Direction.CLIENT_TO_SERVER,
|
||||
attrId: Zcl.Clusters.genLevelCtrl.attributes.currentLevel.ID,
|
||||
dataType: Zcl.DataType.UINT8,
|
||||
minRepIntval: 10,
|
||||
maxRepIntval: 60,
|
||||
repChange: 2,
|
||||
},
|
||||
]);
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
mockMQTTEvents.message(
|
||||
"zigbee2mqtt/bridge/request/device/reporting/read",
|
||||
stringify({
|
||||
id: "0x000b57fffec6a5b2",
|
||||
endpoint: 1,
|
||||
cluster: "genLevelCtrl",
|
||||
configs: [{attribute: "currentLevel"}],
|
||||
manufacturer_code: 0x1234,
|
||||
}),
|
||||
);
|
||||
await flushPromises();
|
||||
expect(endpoint.readReportingConfig).toHaveBeenCalledTimes(1);
|
||||
expect(endpoint.readReportingConfig).toHaveBeenCalledWith("genLevelCtrl", [{attribute: "currentLevel"}], {manufacturerCode: 0x1234});
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
"zigbee2mqtt/bridge/response/device/reporting/read",
|
||||
stringify({
|
||||
data: {
|
||||
id: "0x000b57fffec6a5b2",
|
||||
endpoint: 1,
|
||||
cluster: "genLevelCtrl",
|
||||
configs: [
|
||||
{
|
||||
status: Zcl.Status.SUCCESS,
|
||||
direction: Zcl.Direction.CLIENT_TO_SERVER,
|
||||
attrId: Zcl.Clusters.genLevelCtrl.attributes.currentLevel.ID,
|
||||
dataType: Zcl.DataType.UINT8,
|
||||
minRepIntval: 10,
|
||||
maxRepIntval: 60,
|
||||
repChange: 2,
|
||||
},
|
||||
],
|
||||
manufacturer_code: 0x1234,
|
||||
},
|
||||
status: "ok",
|
||||
}),
|
||||
{},
|
||||
);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith("zigbee2mqtt/bridge/devices", expect.any(String), {retain: true});
|
||||
});
|
||||
|
||||
it("Should throw error when read reporting config is called with malformed payload", async () => {
|
||||
const device = devices.bulb;
|
||||
const endpoint = device.getEndpoint(1)!;
|
||||
endpoint.readReportingConfig.mockClear();
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
mockMQTTEvents.message(
|
||||
"zigbee2mqtt/bridge/request/device/reporting/read",
|
||||
stringify({
|
||||
id: "bulb",
|
||||
// endpoint: '1',
|
||||
cluster: "genLevelCtrl",
|
||||
configs: [{attribute: "currentLevel"}],
|
||||
}),
|
||||
);
|
||||
await flushPromises();
|
||||
expect(endpoint.readReportingConfig).toHaveBeenCalledTimes(0);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
"zigbee2mqtt/bridge/response/device/reporting/read",
|
||||
stringify({data: {}, status: "error", error: "Invalid payload"}),
|
||||
{},
|
||||
);
|
||||
});
|
||||
|
||||
it("Should throw error when read reporting config is called for non-existing device", async () => {
|
||||
const device = devices.bulb;
|
||||
const endpoint = device.getEndpoint(1)!;
|
||||
endpoint.readReportingConfig.mockClear();
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
mockMQTTEvents.message(
|
||||
"zigbee2mqtt/bridge/request/device/reporting/read",
|
||||
stringify({
|
||||
id: "non_existing_device",
|
||||
endpoint: "1",
|
||||
cluster: "genLevelCtrl",
|
||||
configs: [{attribute: "currentLevel"}],
|
||||
}),
|
||||
);
|
||||
await flushPromises();
|
||||
expect(endpoint.readReportingConfig).toHaveBeenCalledTimes(0);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
"zigbee2mqtt/bridge/response/device/reporting/read",
|
||||
stringify({data: {}, status: "error", error: "Device 'non_existing_device' does not exist"}),
|
||||
{},
|
||||
);
|
||||
});
|
||||
|
||||
it("Should throw error when read reporting config is called for non-existing endpoint", async () => {
|
||||
const device = devices.bulb;
|
||||
const endpoint = device.getEndpoint(1)!;
|
||||
endpoint.readReportingConfig.mockClear();
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
mockMQTTEvents.message(
|
||||
"zigbee2mqtt/bridge/request/device/reporting/read",
|
||||
stringify({
|
||||
id: "0x000b57fffec6a5b2",
|
||||
endpoint: "non_existing_endpoint",
|
||||
cluster: "genLevelCtrl",
|
||||
configs: [{attribute: "currentLevel"}],
|
||||
}),
|
||||
);
|
||||
await flushPromises();
|
||||
expect(endpoint.readReportingConfig).toHaveBeenCalledTimes(0);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
"zigbee2mqtt/bridge/response/device/reporting/read",
|
||||
stringify({data: {}, status: "error", error: "Device '0x000b57fffec6a5b2' does not have endpoint 'non_existing_endpoint'"}),
|
||||
{},
|
||||
);
|
||||
@@ -3781,6 +4087,11 @@ describe("Extension: Bridge", () => {
|
||||
fs.writeFileSync(path.join(data.mockDir, "log", "log.log"), "test123");
|
||||
fs.mkdirSync(path.join(data.mockDir, "ext_converters", "123"));
|
||||
fs.writeFileSync(path.join(data.mockDir, "ext_converters", "123", "myfile.js"), "test123");
|
||||
fs.symlinkSync(
|
||||
path.join(data.mockDir, "ext_converters"),
|
||||
path.join(data.mockDir, "ext_converters_sym"),
|
||||
platform() === "win32" ? "junction" : "dir",
|
||||
);
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
mockMQTTEvents.message("zigbee2mqtt/bridge/request/backup", "");
|
||||
await flushPromises();
|
||||
@@ -3939,7 +4250,7 @@ describe("Extension: Bridge", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("Icon link handling", async () => {
|
||||
it("Icon link handling", () => {
|
||||
const bridge = controller.getExtension("Bridge")! as Bridge;
|
||||
expect(bridge).toBeDefined();
|
||||
|
||||
@@ -3970,14 +4281,14 @@ describe("Extension: Bridge", () => {
|
||||
expect(payload.icon).not.toBeUndefined();
|
||||
expect(payload.icon).toBe(svg_icon);
|
||||
|
||||
definition.icon = "_${model}_";
|
||||
definition.icon = "_$model_";
|
||||
// @ts-expect-error bare minimum mock
|
||||
payload = bridge.getDefinitionPayload({...device, zh: device, definition, exposes: () => definition.exposes, options: {}});
|
||||
assert(payload);
|
||||
expect(payload.icon).not.toBeUndefined();
|
||||
expect(payload.icon).toBe("_lumi.plug_");
|
||||
|
||||
definition.icon = "_${model}_${zigbeeModel}_";
|
||||
definition.icon = "_$model_$zigbeeModel_";
|
||||
// @ts-expect-error bare minimum mock
|
||||
payload = bridge.getDefinitionPayload({...device, zh: device, definition, exposes: () => definition.exposes, options: {}});
|
||||
assert(payload);
|
||||
@@ -3993,7 +4304,7 @@ describe("Extension: Bridge", () => {
|
||||
|
||||
device.modelID = "?._Z\\NC+Z02*LM";
|
||||
definition.model = "&&&&*+";
|
||||
definition.icon = "_${model}_${zigbeeModel}_";
|
||||
definition.icon = "_$model_$zigbeeModel_";
|
||||
// @ts-expect-error bare minimum mock
|
||||
payload = bridge.getDefinitionPayload({...device, zh: device, definition, exposes: () => definition.exposes, options: {}});
|
||||
assert(payload);
|
||||
@@ -4039,4 +4350,97 @@ describe("Extension: Bridge", () => {
|
||||
});
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith("zigbee2mqtt/bridge/response/device/configure", expect.any(String), {});
|
||||
});
|
||||
|
||||
it("triggers ZHC action by name with params", async () => {
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
|
||||
mockMQTTEvents.message(
|
||||
"zigbee2mqtt/bridge/request/action",
|
||||
JSON.stringify({
|
||||
action: "raw",
|
||||
params: {
|
||||
profileId: Zdo.ZDO_PROFILE_ID,
|
||||
ieeeAddress: "0xf1f2f3f4f5f6f7f8",
|
||||
networkAddress: 0x1234,
|
||||
clusterKey: Zdo.ClusterId.NETWORK_ADDRESS_REQUEST,
|
||||
zdoParams: ["0xa1a2a3a4a5a6a7a8", false, 0],
|
||||
},
|
||||
}),
|
||||
);
|
||||
await flushPromises();
|
||||
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
"zigbee2mqtt/bridge/response/action",
|
||||
JSON.stringify({data: [0x00, {assocDevList: [], eui64: "", nwkAddress: 0x1234, startIndex: 0}], status: "ok"}),
|
||||
{},
|
||||
);
|
||||
});
|
||||
|
||||
it("triggers ZHC action by name without params", async () => {
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
|
||||
mockMQTTEvents.message(
|
||||
"zigbee2mqtt/bridge/request/action",
|
||||
JSON.stringify({
|
||||
action: "raw",
|
||||
}),
|
||||
);
|
||||
await flushPromises();
|
||||
|
||||
// we're mocking the response, so it's always this as long as the action & payload are valid
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
"zigbee2mqtt/bridge/response/action",
|
||||
JSON.stringify({data: [0x00, {assocDevList: [], eui64: "", nwkAddress: 0x1234, startIndex: 0}], status: "ok"}),
|
||||
{},
|
||||
);
|
||||
});
|
||||
|
||||
it("throws on invalid action payload", async () => {
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
|
||||
mockMQTTEvents.message(
|
||||
"zigbee2mqtt/bridge/request/action",
|
||||
JSON.stringify({
|
||||
params: {
|
||||
profileId: Zdo.ZDO_PROFILE_ID,
|
||||
ieeeAddress: "0xf1f2f3f4f5f6f7f8",
|
||||
networkAddress: 0x1234,
|
||||
clusterKey: Zdo.ClusterId.NETWORK_ADDRESS_REQUEST,
|
||||
zdoParams: ["0xa1a2a3a4a5a6a7a8", false, 0],
|
||||
},
|
||||
}),
|
||||
);
|
||||
await flushPromises();
|
||||
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
"zigbee2mqtt/bridge/response/action",
|
||||
stringify({data: {}, status: "error", error: "Invalid payload"}),
|
||||
{},
|
||||
);
|
||||
});
|
||||
|
||||
it("throws on invalid action", async () => {
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
|
||||
mockMQTTEvents.message(
|
||||
"zigbee2mqtt/bridge/request/action",
|
||||
JSON.stringify({
|
||||
action: "DOES_NOT_EXIST",
|
||||
params: {
|
||||
profileId: Zdo.ZDO_PROFILE_ID,
|
||||
ieeeAddress: "0xf1f2f3f4f5f6f7f8",
|
||||
networkAddress: 0x1234,
|
||||
clusterKey: Zdo.ClusterId.NETWORK_ADDRESS_REQUEST,
|
||||
zdoParams: ["0xa1a2a3a4a5a6a7a8", false, 0],
|
||||
},
|
||||
}),
|
||||
);
|
||||
await flushPromises();
|
||||
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
"zigbee2mqtt/bridge/response/action",
|
||||
stringify({data: {}, status: "error", error: "Invalid action"}),
|
||||
{},
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
// biome-ignore assist/source/organizeImports: import mocks first
|
||||
import {afterAll, beforeAll, beforeEach, describe, expect, it, vi} from "vitest";
|
||||
import * as data from "../mocks/data";
|
||||
import {mockLogger} from "../mocks/logger";
|
||||
import {events as mockMQTTEvents, mockMQTTPublishAsync} from "../mocks/mqtt";
|
||||
import {flushPromises} from "../mocks/utils";
|
||||
import {type Device, type Endpoint, devices, events as mockZHEvents} from "../mocks/zigbeeHerdsman";
|
||||
import {type Device, devices, type Endpoint, events as mockZHEvents} from "../mocks/zigbeeHerdsman";
|
||||
|
||||
import stringify from "json-stable-stringify-without-jsonify";
|
||||
|
||||
import {InterviewState} from "zigbee-herdsman/dist/controller/model/device";
|
||||
|
||||
import {Controller} from "../../lib/controller";
|
||||
import Configure from "../../lib/extension/configure";
|
||||
import * as settings from "../../lib/util/settings";
|
||||
@@ -121,11 +121,9 @@ describe("Extension: Configure", () => {
|
||||
|
||||
it("Should reconfigure reporting on reconfigure event", async () => {
|
||||
expectBulbConfigured();
|
||||
// @ts-expect-error private
|
||||
const device = controller.zigbee.resolveEntity(devices.bulb)!;
|
||||
mockClear(device.zh);
|
||||
expectBulbNotConfigured();
|
||||
// @ts-expect-error private
|
||||
controller.eventBus.emitReconfigure({device});
|
||||
await flushPromises();
|
||||
expectBulbConfigured();
|
||||
@@ -184,11 +182,11 @@ describe("Extension: Configure", () => {
|
||||
});
|
||||
|
||||
it("Fail to configure via MQTT when device has no configure", async () => {
|
||||
await mockMQTTEvents.message("zigbee2mqtt/bridge/request/device/configure", stringify({id: "0x0017882104a44559", transaction: 20}));
|
||||
await mockMQTTEvents.message("zigbee2mqtt/bridge/request/device/configure", stringify({id: "0x0017980134e45545", transaction: 20}));
|
||||
await flushPromises();
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
"zigbee2mqtt/bridge/response/device/configure",
|
||||
stringify({data: {}, status: "error", error: "Device 'TS0601_thermostat' cannot be configured", transaction: 20}),
|
||||
stringify({data: {}, status: "error", error: "Device '0x0017980134e45545' cannot be configured", transaction: 20}),
|
||||
{},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,21 +1,19 @@
|
||||
// biome-ignore assist/source/organizeImports: import mocks first
|
||||
import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from "vitest";
|
||||
import * as data from "../mocks/data";
|
||||
import {mockLogger} from "../mocks/logger";
|
||||
import {mockMQTTEndAsync, mockMQTTPublishAsync} from "../mocks/mqtt";
|
||||
import {flushPromises} from "../mocks/utils";
|
||||
import {devices, mockController as mockZHController, returnDevices} from "../mocks/zigbeeHerdsman";
|
||||
|
||||
import type Device from "../../lib/model/device";
|
||||
import type {Device as ZhDevice} from "../mocks/zigbeeHerdsman";
|
||||
import {devices, mockController as mockZHController, returnDevices} from "../mocks/zigbeeHerdsman";
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import stringify from "json-stable-stringify-without-jsonify";
|
||||
|
||||
import * as zhc from "zigbee-herdsman-converters";
|
||||
|
||||
import {Controller} from "../../lib/controller";
|
||||
import ExternalConverters from "../../lib/extension/externalConverters";
|
||||
import type Device from "../../lib/model/device";
|
||||
import * as settings from "../../lib/util/settings";
|
||||
|
||||
const BASE_DIR = "external_converters";
|
||||
@@ -52,7 +50,6 @@ describe("Extension: ExternalConverters", () => {
|
||||
};
|
||||
|
||||
const getZ2MDevice = (zhDevice: string | number | ZhDevice): Device => {
|
||||
// @ts-expect-error private
|
||||
return controller.zigbee.resolveEntity(zhDevice)! as Device;
|
||||
};
|
||||
|
||||
@@ -75,7 +72,6 @@ describe("Extension: ExternalConverters", () => {
|
||||
|
||||
beforeEach(async () => {
|
||||
zhc.removeExternalDefinitions(); // remove all external converters
|
||||
// @ts-expect-error private - clear cached
|
||||
await controller.zigbee.resolveDevicesDefinitions(true);
|
||||
for (const mock of mocksClear) mock.mockClear();
|
||||
data.writeDefaultConfiguration();
|
||||
@@ -85,10 +81,12 @@ describe("Extension: ExternalConverters", () => {
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
fs.rmSync(mockBasePath, {recursive: true, force: true});
|
||||
|
||||
await controller?.stop();
|
||||
await flushPromises();
|
||||
|
||||
expect(fs.existsSync(path.join(mockBasePath, "node_modules"))).toStrictEqual(false);
|
||||
|
||||
fs.rmSync(mockBasePath, {recursive: true, force: true});
|
||||
});
|
||||
|
||||
describe("from folder", () => {
|
||||
@@ -351,6 +349,7 @@ describe("Extension: ExternalConverters", () => {
|
||||
);
|
||||
expect(fs.existsSync(filepath)).toStrictEqual(false);
|
||||
expect(fs.existsSync(path.join(mockBasePath, "invalid.mjs.invalid"))).toStrictEqual(true);
|
||||
expect(mockLogger.error).toHaveBeenCalledWith(expect.stringContaining("Parse failure: Expected ';', '}' or <eof>"));
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// biome-ignore assist/source/organizeImports: import mocks first
|
||||
import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from "vitest";
|
||||
import * as data from "../mocks/data";
|
||||
import {mockLogger} from "../mocks/logger";
|
||||
import {mockMQTTEndAsync, mockMQTTPublishAsync} from "../mocks/mqtt";
|
||||
@@ -6,9 +8,7 @@ import {devices, mockController as mockZHController, returnDevices} from "../moc
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import stringify from "json-stable-stringify-without-jsonify";
|
||||
|
||||
import {Controller} from "../../lib/controller";
|
||||
import ExternalExtensions from "../../lib/extension/externalExtensions";
|
||||
import * as settings from "../../lib/util/settings";
|
||||
@@ -68,10 +68,12 @@ describe("Extension: ExternalExtensions", () => {
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
fs.rmSync(mockBasePath, {recursive: true, force: true});
|
||||
|
||||
await controller?.stop();
|
||||
await flushPromises();
|
||||
|
||||
expect(fs.existsSync(path.join(mockBasePath, "node_modules"))).toStrictEqual(false);
|
||||
|
||||
fs.rmSync(mockBasePath, {recursive: true, force: true});
|
||||
});
|
||||
|
||||
describe("from folder", () => {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// biome-ignore assist/source/organizeImports: import mocks first
|
||||
import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from "vitest";
|
||||
import * as data from "../mocks/data";
|
||||
import {mockLogger} from "../mocks/logger";
|
||||
import {events as mockMQTTEvents, mockMQTTPublishAsync} from "../mocks/mqtt";
|
||||
@@ -5,11 +7,9 @@ import {type EventHandler, flushPromises} from "../mocks/utils";
|
||||
import {devices, events as mockZHEvents} from "../mocks/zigbeeHerdsman";
|
||||
|
||||
import path from "node:path";
|
||||
|
||||
import stringify from "json-stable-stringify-without-jsonify";
|
||||
import type {Mock} from "vitest";
|
||||
import ws from "ws";
|
||||
|
||||
import {Controller} from "../../lib/controller";
|
||||
import * as settings from "../../lib/util/settings";
|
||||
|
||||
@@ -23,7 +23,6 @@ const mockHTTP = {
|
||||
close: vi.fn<(cb: (err?: Error) => void) => void>((cb) => cb()),
|
||||
};
|
||||
|
||||
let mockHTTPSOnRequest: (request: {url: string}, response: number) => void;
|
||||
const mockHTTPSEvents: Record<string, EventHandler> = {};
|
||||
const mockHTTPS = {
|
||||
listen: vi.fn(),
|
||||
@@ -56,7 +55,7 @@ const mockWS = {
|
||||
handleUpgrade: vi.fn().mockImplementation((_request, _socket, _head, cb) => {
|
||||
cb(mockWSocket);
|
||||
}),
|
||||
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
|
||||
// biome-ignore lint/suspicious/noExplicitAny: ignore
|
||||
emit: vi.fn<(eventName: string, ...args: any[]) => void>(),
|
||||
close: vi.fn<(code?: number, data?: string | Buffer) => void>(),
|
||||
};
|
||||
@@ -76,10 +75,7 @@ vi.mock("node:http", () => ({
|
||||
}));
|
||||
|
||||
vi.mock("node:https", () => ({
|
||||
createServer: vi.fn().mockImplementation((onRequest) => {
|
||||
mockHTTPSOnRequest = onRequest;
|
||||
return mockHTTPS;
|
||||
}),
|
||||
createServer: vi.fn().mockImplementation(() => mockHTTPS),
|
||||
Agent: vi.fn(),
|
||||
}));
|
||||
|
||||
@@ -90,7 +86,7 @@ vi.mock("express-static-gzip", () => ({
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("zigbee2mqtt-frontend", () => ({
|
||||
vi.mock("zigbee2mqtt-windfront", () => ({
|
||||
default: {
|
||||
getPath: (): string => frontendPath,
|
||||
},
|
||||
@@ -491,4 +487,17 @@ describe("Extension: Frontend", () => {
|
||||
|
||||
await vi.waitFor(() => controller.getExtension("Frontend") === undefined);
|
||||
});
|
||||
|
||||
it("disables serving", async () => {
|
||||
settings.set(["frontend", "disable_ui_serving"], true);
|
||||
controller = new Controller(vi.fn(), vi.fn());
|
||||
await controller.start();
|
||||
|
||||
expect(mockHTTP.listen).toHaveBeenCalledTimes(0);
|
||||
mockWS.clients.push(mockWSClient);
|
||||
await controller.stop();
|
||||
expect(mockWSClient.terminate).toHaveBeenCalledTimes(1);
|
||||
expect(mockHTTP.close).toHaveBeenCalledTimes(0);
|
||||
expect(mockWS.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// biome-ignore assist/source/organizeImports: import mocks first
|
||||
import {afterAll, beforeAll, beforeEach, describe, expect, it, vi} from "vitest";
|
||||
import * as data from "../mocks/data";
|
||||
import {mockLogger} from "../mocks/logger";
|
||||
import {events as mockMQTTEvents, mockMQTTPublishAsync} from "../mocks/mqtt";
|
||||
@@ -5,9 +7,7 @@ import {flushPromises} from "../mocks/utils";
|
||||
import {devices, groups, events as mockZHEvents, resetGroupMembers, returnDevices} from "../mocks/zigbeeHerdsman";
|
||||
|
||||
import stringify from "json-stable-stringify-without-jsonify";
|
||||
|
||||
import * as zhcGlobalStore from "zigbee-herdsman-converters/lib/store";
|
||||
|
||||
import {Controller} from "../../lib/controller";
|
||||
import * as settings from "../../lib/util/settings";
|
||||
|
||||
@@ -45,7 +45,6 @@ describe("Extension: Groups", () => {
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
groups.gledopto_group.command.mockClear();
|
||||
zhcGlobalStore.clear();
|
||||
// @ts-expect-error private
|
||||
controller.state.clear();
|
||||
});
|
||||
|
||||
@@ -460,7 +459,6 @@ describe("Extension: Groups", () => {
|
||||
await mockMQTTEvents.message("zigbee2mqtt/group_1/set", stringify({state: "ON"}));
|
||||
await flushPromises();
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
// @ts-expect-error private
|
||||
controller.state.clear();
|
||||
|
||||
await mockMQTTEvents.message("zigbee2mqtt/bulb_color/set", stringify({state: "OFF"}));
|
||||
@@ -507,7 +505,7 @@ describe("Extension: Groups", () => {
|
||||
expect(mockMQTTPublishAsync).not.toHaveBeenCalledWith("zigbee2mqtt/bridge/groups", expect.any(String), expect.any(Object));
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
"zigbee2mqtt/bridge/response/group/members/add",
|
||||
stringify({data: {}, status: "error", error: "Failed to add from group (timeout)"}),
|
||||
stringify({data: {}, status: "error", error: "Failed to add to group (timeout)"}),
|
||||
{},
|
||||
);
|
||||
});
|
||||
@@ -592,6 +590,26 @@ describe("Extension: Groups", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("Remove from group via MQTT fails", async () => {
|
||||
const device = devices.bulb_color;
|
||||
const endpoint = device.getEndpoint(1)!;
|
||||
const group = groups.group_1;
|
||||
group.members.push(endpoint);
|
||||
endpoint.removeFromGroup.mockImplementationOnce(() => {
|
||||
throw new Error("timeout");
|
||||
});
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
mockMQTTEvents.message("zigbee2mqtt/bridge/request/group/members/remove", stringify({group: "group_1", device: "bulb_color"}));
|
||||
await flushPromises();
|
||||
expect(group.members.length).toStrictEqual(1);
|
||||
expect(mockMQTTPublishAsync).not.toHaveBeenCalledWith("zigbee2mqtt/bridge/groups", expect.any(String), expect.any(Object));
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
"zigbee2mqtt/bridge/response/group/members/remove",
|
||||
stringify({data: {}, status: "error", error: "Failed to remove from group (timeout)"}),
|
||||
{},
|
||||
);
|
||||
});
|
||||
|
||||
it("Remove from group via MQTT keeping device reporting", async () => {
|
||||
const device = devices.bulb_color;
|
||||
const endpoint = device.getEndpoint(1)!;
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
// biome-ignore assist/source/organizeImports: import mocks first
|
||||
import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from "vitest";
|
||||
import * as data from "../mocks/data";
|
||||
import {mockLogger} from "../mocks/logger";
|
||||
import {events as mockMQTTEvents, mockMQTTPublishAsync} from "../mocks/mqtt";
|
||||
import {flushPromises} from "../mocks/utils";
|
||||
import {devices, events as mockZHEvents, returnDevices} from "../mocks/zigbeeHerdsman";
|
||||
|
||||
import {Controller} from "../../lib/controller";
|
||||
import Health from "../../lib/extension/health";
|
||||
import * as settings from "../../lib/util/settings";
|
||||
import {minutes, seconds} from "../../lib/util/utils";
|
||||
|
||||
const mocksClear = [mockMQTTPublishAsync, mockLogger.warning, mockLogger.info];
|
||||
|
||||
returnDevices.push(devices.bulb_color.ieeeAddr, devices.bulb_color_2.ieeeAddr, devices.coordinator.ieeeAddr);
|
||||
|
||||
describe("Extension: Health", () => {
|
||||
let controller: Controller;
|
||||
|
||||
const getExtension = (): Health => controller.getExtension("Health") as Health;
|
||||
|
||||
const resetExtension = async (): Promise<void> => {
|
||||
await controller.removeExtension(getExtension());
|
||||
await controller.addExtension(new Health(...controller.extensionArgs));
|
||||
};
|
||||
|
||||
beforeAll(async () => {
|
||||
vi.useFakeTimers();
|
||||
settings.reRead();
|
||||
|
||||
controller = new Controller(vi.fn(), vi.fn());
|
||||
|
||||
await controller.start();
|
||||
await flushPromises();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
data.writeDefaultConfiguration();
|
||||
settings.reRead();
|
||||
settings.set(["devices", devices.bulb_color_2.ieeeAddr, "health"], false);
|
||||
|
||||
for (const mock of mocksClear) {
|
||||
mock.mockClear();
|
||||
}
|
||||
|
||||
getExtension().clearStats();
|
||||
});
|
||||
|
||||
afterEach(async () => {});
|
||||
|
||||
afterAll(async () => {
|
||||
await controller?.stop();
|
||||
await flushPromises();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("checks health at default interval", async () => {
|
||||
await resetExtension();
|
||||
await mockZHEvents.lastSeenChanged({device: devices.bulb_color});
|
||||
await mockZHEvents.lastSeenChanged({device: devices.bulb_color_2});
|
||||
await mockZHEvents.deviceLeave({ieeeAddr: devices.bulb_color.ieeeAddr});
|
||||
await mockZHEvents.deviceJoined({device: devices.bulb_color});
|
||||
await mockZHEvents.deviceNetworkAddressChanged({device: devices.bulb_color});
|
||||
await vi.advanceTimersByTimeAsync(seconds(1));
|
||||
await mockZHEvents.lastSeenChanged({device: devices.bulb_color});
|
||||
await vi.advanceTimersByTimeAsync(seconds(1));
|
||||
await mockZHEvents.lastSeenChanged({device: devices.bulb_color});
|
||||
await vi.advanceTimersByTimeAsync(seconds(1));
|
||||
await mockZHEvents.lastSeenChanged({device: devices.bulb_color});
|
||||
await mockMQTTEvents.message("zigbee2mqtt/mock", "mocked");
|
||||
await vi.advanceTimersByTimeAsync(minutes(11));
|
||||
|
||||
let calls = mockMQTTPublishAsync.mock.calls.filter((call) => call[0] === "zigbee2mqtt/bridge/health");
|
||||
|
||||
expect(calls.length).toStrictEqual(1);
|
||||
expect(JSON.parse(calls[0][1])).toStrictEqual({
|
||||
response_time: expect.any(Number),
|
||||
os: {
|
||||
load_average: [expect.any(Number), expect.any(Number), expect.any(Number)],
|
||||
memory_used_mb: expect.any(Number),
|
||||
memory_percent: expect.any(Number),
|
||||
},
|
||||
process: {uptime_sec: expect.any(Number), memory_used_mb: expect.any(Number), memory_percent: expect.any(Number)},
|
||||
mqtt: {
|
||||
connected: true,
|
||||
queued: 0,
|
||||
published: expect.any(Number),
|
||||
received: 1,
|
||||
},
|
||||
devices: {
|
||||
[devices.bulb_color.ieeeAddr]: {
|
||||
leave_count: 1,
|
||||
messages: 4,
|
||||
messages_per_sec: 0.0067,
|
||||
network_address_changes: 1,
|
||||
},
|
||||
[devices.bulb_color_2.ieeeAddr]: {
|
||||
leave_count: 0,
|
||||
messages: 1,
|
||||
messages_per_sec: 0.0017,
|
||||
network_address_changes: 0,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(calls[0][2]).toStrictEqual({retain: true, qos: 1});
|
||||
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
await mockMQTTEvents.message("zigbee2mqtt/mock2", "mocked2");
|
||||
await vi.advanceTimersByTimeAsync(minutes(11));
|
||||
|
||||
calls = mockMQTTPublishAsync.mock.calls.filter((call) => call[0] === "zigbee2mqtt/bridge/health");
|
||||
|
||||
expect(calls.length).toStrictEqual(1);
|
||||
expect(JSON.parse(calls[0][1])).toStrictEqual({
|
||||
response_time: expect.any(Number),
|
||||
os: {
|
||||
load_average: [expect.any(Number), expect.any(Number), expect.any(Number)],
|
||||
memory_used_mb: expect.any(Number),
|
||||
memory_percent: expect.any(Number),
|
||||
},
|
||||
process: {uptime_sec: expect.any(Number), memory_used_mb: expect.any(Number), memory_percent: expect.any(Number)},
|
||||
mqtt: {
|
||||
connected: true,
|
||||
queued: 0,
|
||||
published: expect.any(Number),
|
||||
received: 2,
|
||||
},
|
||||
devices: {
|
||||
[devices.bulb_color.ieeeAddr]: {
|
||||
leave_count: 1,
|
||||
messages: 4,
|
||||
messages_per_sec: 0.0033,
|
||||
network_address_changes: 1,
|
||||
},
|
||||
[devices.bulb_color_2.ieeeAddr]: {
|
||||
leave_count: 0,
|
||||
messages: 1,
|
||||
messages_per_sec: 0.0008,
|
||||
network_address_changes: 0,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(calls[0][2]).toStrictEqual({retain: true, qos: 1});
|
||||
});
|
||||
|
||||
it("checks health at given interval", async () => {
|
||||
settings.set(["health", "interval"], 20);
|
||||
await resetExtension();
|
||||
await vi.advanceTimersByTimeAsync(minutes(11));
|
||||
|
||||
let calls = mockMQTTPublishAsync.mock.calls.filter((call) => call[0] === "zigbee2mqtt/bridge/health");
|
||||
|
||||
expect(calls.length).toStrictEqual(0);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(minutes(10));
|
||||
|
||||
calls = mockMQTTPublishAsync.mock.calls.filter((call) => call[0] === "zigbee2mqtt/bridge/health");
|
||||
|
||||
expect(calls.length).toStrictEqual(1);
|
||||
expect(JSON.parse(calls[0][1])).toStrictEqual({
|
||||
response_time: expect.any(Number),
|
||||
os: {
|
||||
load_average: [expect.any(Number), expect.any(Number), expect.any(Number)],
|
||||
memory_used_mb: expect.any(Number),
|
||||
memory_percent: expect.any(Number),
|
||||
},
|
||||
process: {uptime_sec: expect.any(Number), memory_used_mb: expect.any(Number), memory_percent: expect.any(Number)},
|
||||
mqtt: {
|
||||
connected: true,
|
||||
queued: 0,
|
||||
published: expect.any(Number),
|
||||
received: 0,
|
||||
},
|
||||
devices: {},
|
||||
});
|
||||
expect(calls[0][2]).toStrictEqual({retain: true, qos: 1});
|
||||
});
|
||||
|
||||
it("init device health from leave", async () => {
|
||||
await resetExtension();
|
||||
await mockZHEvents.deviceLeave({ieeeAddr: devices.bulb_color.ieeeAddr});
|
||||
await mockZHEvents.deviceJoined({device: devices.bulb_color});
|
||||
await vi.advanceTimersByTimeAsync(minutes(11));
|
||||
|
||||
const calls = mockMQTTPublishAsync.mock.calls.filter((call) => call[0] === "zigbee2mqtt/bridge/health");
|
||||
|
||||
expect(calls.length).toStrictEqual(1);
|
||||
expect(JSON.parse(calls[0][1])).toStrictEqual({
|
||||
response_time: expect.any(Number),
|
||||
os: {
|
||||
load_average: [expect.any(Number), expect.any(Number), expect.any(Number)],
|
||||
memory_used_mb: expect.any(Number),
|
||||
memory_percent: expect.any(Number),
|
||||
},
|
||||
process: {uptime_sec: expect.any(Number), memory_used_mb: expect.any(Number), memory_percent: expect.any(Number)},
|
||||
mqtt: {
|
||||
connected: true,
|
||||
queued: 0,
|
||||
published: expect.any(Number),
|
||||
received: 0,
|
||||
},
|
||||
devices: {
|
||||
[devices.bulb_color.ieeeAddr]: {
|
||||
leave_count: 1,
|
||||
messages: 0,
|
||||
messages_per_sec: 0,
|
||||
network_address_changes: 0,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(calls[0][2]).toStrictEqual({retain: true, qos: 1});
|
||||
});
|
||||
|
||||
it("init device health from network address change", async () => {
|
||||
await resetExtension();
|
||||
await mockZHEvents.deviceNetworkAddressChanged({device: devices.bulb_color});
|
||||
await vi.advanceTimersByTimeAsync(minutes(11));
|
||||
|
||||
const calls = mockMQTTPublishAsync.mock.calls.filter((call) => call[0] === "zigbee2mqtt/bridge/health");
|
||||
|
||||
expect(calls.length).toStrictEqual(1);
|
||||
expect(JSON.parse(calls[0][1])).toStrictEqual({
|
||||
response_time: expect.any(Number),
|
||||
os: {
|
||||
load_average: [expect.any(Number), expect.any(Number), expect.any(Number)],
|
||||
memory_used_mb: expect.any(Number),
|
||||
memory_percent: expect.any(Number),
|
||||
},
|
||||
process: {uptime_sec: expect.any(Number), memory_used_mb: expect.any(Number), memory_percent: expect.any(Number)},
|
||||
mqtt: {
|
||||
connected: true,
|
||||
queued: 0,
|
||||
published: expect.any(Number),
|
||||
received: 0,
|
||||
},
|
||||
devices: {
|
||||
[devices.bulb_color.ieeeAddr]: {
|
||||
leave_count: 0,
|
||||
messages: 0,
|
||||
messages_per_sec: 0,
|
||||
network_address_changes: 1,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(calls[0][2]).toStrictEqual({retain: true, qos: 1});
|
||||
});
|
||||
|
||||
it("checks health then resets possible stats", async () => {
|
||||
settings.set(["health", "reset_on_check"], true);
|
||||
await resetExtension();
|
||||
await mockZHEvents.lastSeenChanged({device: devices.bulb_color});
|
||||
await mockZHEvents.lastSeenChanged({device: devices.bulb_color}); // coverage no time diff first/last
|
||||
await mockZHEvents.lastSeenChanged({device: devices.bulb_color_2});
|
||||
await vi.advanceTimersByTimeAsync(minutes(11));
|
||||
|
||||
let calls = mockMQTTPublishAsync.mock.calls.filter((call) => call[0] === "zigbee2mqtt/bridge/health");
|
||||
|
||||
expect(calls.length).toStrictEqual(1);
|
||||
expect(JSON.parse(calls[0][1])).toStrictEqual({
|
||||
response_time: expect.any(Number),
|
||||
os: {
|
||||
load_average: [expect.any(Number), expect.any(Number), expect.any(Number)],
|
||||
memory_used_mb: expect.any(Number),
|
||||
memory_percent: expect.any(Number),
|
||||
},
|
||||
process: {uptime_sec: expect.any(Number), memory_used_mb: expect.any(Number), memory_percent: expect.any(Number)},
|
||||
mqtt: {
|
||||
connected: true,
|
||||
queued: 0,
|
||||
published: expect.any(Number),
|
||||
received: 0,
|
||||
},
|
||||
devices: {
|
||||
[devices.bulb_color.ieeeAddr]: {
|
||||
leave_count: 0,
|
||||
messages: 2,
|
||||
messages_per_sec: 0.0033,
|
||||
network_address_changes: 0,
|
||||
},
|
||||
[devices.bulb_color_2.ieeeAddr]: {
|
||||
leave_count: 0,
|
||||
messages: 1,
|
||||
messages_per_sec: 0.0017,
|
||||
network_address_changes: 0,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(calls[0][2]).toStrictEqual({retain: true, qos: 1});
|
||||
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
await vi.advanceTimersByTimeAsync(minutes(11));
|
||||
|
||||
calls = mockMQTTPublishAsync.mock.calls.filter((call) => call[0] === "zigbee2mqtt/bridge/health");
|
||||
|
||||
expect(calls.length).toStrictEqual(1);
|
||||
expect(JSON.parse(calls[0][1])).toStrictEqual({
|
||||
response_time: expect.any(Number),
|
||||
os: {
|
||||
load_average: [expect.any(Number), expect.any(Number), expect.any(Number)],
|
||||
memory_used_mb: expect.any(Number),
|
||||
memory_percent: expect.any(Number),
|
||||
},
|
||||
process: {uptime_sec: expect.any(Number), memory_used_mb: expect.any(Number), memory_percent: expect.any(Number)},
|
||||
mqtt: {
|
||||
connected: true,
|
||||
queued: 0,
|
||||
published: expect.any(Number),
|
||||
received: 0,
|
||||
},
|
||||
devices: {},
|
||||
});
|
||||
expect(calls[0][2]).toStrictEqual({retain: true, qos: 1});
|
||||
});
|
||||
});
|
||||
@@ -1,25 +1,23 @@
|
||||
// biome-ignore assist/source/organizeImports: import mocks first
|
||||
import {afterAll, beforeAll, beforeEach, describe, expect, it, test, vi} from "vitest";
|
||||
import * as data from "../mocks/data";
|
||||
import {mockLogger} from "../mocks/logger";
|
||||
import {events as mockMQTTEvents, mockMQTTPublishAsync, mockMQTTSubscribeAsync, mockMQTTUnsubscribeAsync} from "../mocks/mqtt";
|
||||
import * as mockSleep from "../mocks/sleep";
|
||||
import {flushPromises, getZhcBaseDefinitions} from "../mocks/utils";
|
||||
import type {Device as ZhDevice} from "../mocks/zigbeeHerdsman";
|
||||
import {devices, groups, events as mockZHEvents} from "../mocks/zigbeeHerdsman";
|
||||
|
||||
import assert from "node:assert";
|
||||
import stringify from "json-stable-stringify-without-jsonify";
|
||||
import type {MockInstance} from "vitest";
|
||||
import * as zhc from "zigbee-herdsman-converters";
|
||||
import type {KeyValueAny} from "zigbee-herdsman-converters/lib/types";
|
||||
import {Controller} from "../../lib/controller";
|
||||
import HomeAssistant from "../../lib/extension/homeassistant";
|
||||
|
||||
import type Device from "../../lib/model/device";
|
||||
import type Group from "../../lib/model/group";
|
||||
import type {Device as ZhDevice} from "../mocks/zigbeeHerdsman";
|
||||
|
||||
import assert from "node:assert";
|
||||
|
||||
import stringify from "json-stable-stringify-without-jsonify";
|
||||
|
||||
import * as zhc from "zigbee-herdsman-converters";
|
||||
import type {KeyValueAny} from "zigbee-herdsman-converters/lib/types";
|
||||
|
||||
import {Controller} from "../../lib/controller";
|
||||
import HomeAssistant from "../../lib/extension/homeassistant";
|
||||
import * as settings from "../../lib/util/settings";
|
||||
|
||||
const mocksClear = [mockMQTTPublishAsync, mockLogger.debug, mockLogger.warning, mockLogger.error];
|
||||
@@ -58,7 +56,6 @@ describe("Extension: HomeAssistant", () => {
|
||||
};
|
||||
|
||||
const getZ2MEntity = (zhDeviceOrGroup: string | number | ZhDevice): Device | Group => {
|
||||
// @ts-expect-error private
|
||||
return controller.zigbee.resolveEntity(zhDeviceOrGroup)!;
|
||||
};
|
||||
|
||||
@@ -101,7 +98,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
|
||||
for (const baseDefinition of await getZhcBaseDefinitions()) {
|
||||
const d = zhc.prepareDefinition(baseDefinition);
|
||||
const exposes = typeof d.exposes === "function" ? d.exposes(undefined, undefined) : d.exposes;
|
||||
const exposes = typeof d.exposes === "function" ? d.exposes({isDummyDevice: true}, {}) : d.exposes;
|
||||
const device = {
|
||||
definition: d,
|
||||
isDevice: (): boolean => true,
|
||||
@@ -169,6 +166,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
"stop_hue_effect",
|
||||
],
|
||||
object_id: "ha_discovery_group",
|
||||
default_entity_id: "light.ha_discovery_group",
|
||||
unique_id: "9_light_zigbee2mqtt",
|
||||
origin: origin,
|
||||
};
|
||||
@@ -193,6 +191,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
},
|
||||
name: null,
|
||||
object_id: "bulb_enddevice",
|
||||
default_entity_id: "light.bulb_enddevice",
|
||||
origin: origin,
|
||||
schema: "json",
|
||||
state_topic: "zigbee2mqtt/bulb_enddevice",
|
||||
@@ -221,6 +220,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
payload_on: "ON",
|
||||
state_topic: "zigbee2mqtt/ha_discovery_group",
|
||||
object_id: "ha_discovery_group",
|
||||
default_entity_id: "switch.ha_discovery_group",
|
||||
unique_id: "9_switch_zigbee2mqtt",
|
||||
origin: origin,
|
||||
value_template: "{{ value_json.state }}",
|
||||
@@ -239,6 +239,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
value_template: "{{ value_json.temperature }}",
|
||||
state_topic: "zigbee2mqtt/weather_sensor",
|
||||
object_id: "weather_sensor_temperature",
|
||||
default_entity_id: "sensor.weather_sensor_temperature",
|
||||
unique_id: "0x0017880104e45522_temperature_zigbee2mqtt",
|
||||
origin: origin,
|
||||
device: {
|
||||
@@ -265,6 +266,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
value_template: "{{ value_json.humidity }}",
|
||||
state_topic: "zigbee2mqtt/weather_sensor",
|
||||
object_id: "weather_sensor_humidity",
|
||||
default_entity_id: "sensor.weather_sensor_humidity",
|
||||
unique_id: "0x0017880104e45522_humidity_zigbee2mqtt",
|
||||
origin: origin,
|
||||
enabled_by_default: true,
|
||||
@@ -291,6 +293,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
value_template: "{{ value_json.pressure }}",
|
||||
state_topic: "zigbee2mqtt/weather_sensor",
|
||||
object_id: "weather_sensor_pressure",
|
||||
default_entity_id: "sensor.weather_sensor_pressure",
|
||||
unique_id: "0x0017880104e45522_pressure_zigbee2mqtt",
|
||||
origin: origin,
|
||||
enabled_by_default: true,
|
||||
@@ -317,6 +320,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
value_template: "{{ value_json.battery }}",
|
||||
state_topic: "zigbee2mqtt/weather_sensor",
|
||||
object_id: "weather_sensor_battery",
|
||||
default_entity_id: "sensor.weather_sensor_battery",
|
||||
unique_id: "0x0017880104e45522_battery_zigbee2mqtt",
|
||||
origin: origin,
|
||||
enabled_by_default: true,
|
||||
@@ -347,6 +351,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
state_topic: "zigbee2mqtt/weather_sensor",
|
||||
name: "Linkquality",
|
||||
object_id: "weather_sensor_linkquality",
|
||||
default_entity_id: "sensor.weather_sensor_linkquality",
|
||||
unique_id: "0x0017880104e45522_linkquality_zigbee2mqtt",
|
||||
origin: origin,
|
||||
device: {
|
||||
@@ -381,6 +386,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
payload_on: "ON",
|
||||
state_topic: "zigbee2mqtt/wall_switch_double",
|
||||
object_id: "wall_switch_double_left",
|
||||
default_entity_id: "switch.wall_switch_double_left",
|
||||
unique_id: "0x0017880104e45542_switch_left_zigbee2mqtt",
|
||||
origin: origin,
|
||||
value_template: "{{ value_json.state_left }}",
|
||||
@@ -407,6 +413,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
payload_on: "ON",
|
||||
state_topic: "zigbee2mqtt/wall_switch_double",
|
||||
object_id: "wall_switch_double_right",
|
||||
default_entity_id: "switch.wall_switch_double_right",
|
||||
unique_id: "0x0017880104e45542_switch_right_zigbee2mqtt",
|
||||
origin: origin,
|
||||
value_template: "{{ value_json.state_right }}",
|
||||
@@ -439,6 +446,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
schema: "json",
|
||||
state_topic: "zigbee2mqtt/bulb",
|
||||
object_id: "bulb",
|
||||
default_entity_id: "light.bulb",
|
||||
unique_id: "0x000b57fffec6a5b2_light_zigbee2mqtt",
|
||||
origin: origin,
|
||||
};
|
||||
@@ -462,6 +470,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
icon: "mdi:gesture-double-tap",
|
||||
name: "Action",
|
||||
object_id: "button_action",
|
||||
default_entity_id: "event.button_action",
|
||||
origin,
|
||||
state_topic: "zigbee2mqtt/button",
|
||||
unique_id: "0x0017880104e45520_action_zigbee2mqtt",
|
||||
@@ -513,6 +522,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
value_template: "{{ value_json.humidity }}",
|
||||
state_topic: "zigbee2mqtt/weather_sensor",
|
||||
object_id: "weather_sensor_humidity",
|
||||
default_entity_id: "sensor.weather_sensor_humidity",
|
||||
unique_id: "0x0017880104e45522_humidity_zigbee2mqtt",
|
||||
origin: origin,
|
||||
enabled_by_default: true,
|
||||
@@ -584,6 +594,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
value_template: "{{ value_json.temperature }}",
|
||||
state_topic: "zigbee2mqtt/weather_sensor",
|
||||
object_id: "weather_sensor_temperature",
|
||||
default_entity_id: "sensor.weather_sensor_temperature",
|
||||
unique_id: "0x0017880104e45522_temperature_zigbee2mqtt",
|
||||
origin: origin,
|
||||
device: {
|
||||
@@ -609,6 +620,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
value_template: "{{ value_json.humidity }}",
|
||||
state_topic: "zigbee2mqtt/weather_sensor",
|
||||
object_id: "weather_sensor_humidity",
|
||||
default_entity_id: "sensor.weather_sensor_humidity",
|
||||
unique_id: "0x0017880104e45522_humidity_zigbee2mqtt",
|
||||
origin: origin,
|
||||
enabled_by_default: true,
|
||||
@@ -636,6 +648,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
state_topic: "zigbee2mqtt/weather_sensor",
|
||||
enabled_by_default: true,
|
||||
object_id: "weather_sensor_pressure",
|
||||
default_entity_id: "sensor.weather_sensor_pressure",
|
||||
unique_id: "0x0017880104e45522_pressure_zigbee2mqtt",
|
||||
origin: origin,
|
||||
device: {
|
||||
@@ -693,6 +706,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
state_topic: "zigbee2mqtt/weather_sensor",
|
||||
enabled_by_default: true,
|
||||
object_id: "weather_sensor_temperature",
|
||||
default_entity_id: "sensor.weather_sensor_temperature",
|
||||
unique_id: "0x0017880104e45522_temperature_zigbee2mqtt",
|
||||
origin: origin,
|
||||
device: {
|
||||
@@ -734,6 +748,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
expire_after: 30,
|
||||
icon: "mdi:test",
|
||||
object_id: "weather_sensor_humidity",
|
||||
default_entity_id: "sensor.weather_sensor_humidity",
|
||||
};
|
||||
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith("homeassistant/sensor/0x0017880104e45522/humidity/config", stringify(payload), {
|
||||
@@ -763,6 +778,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
value_template: "{{ value_json.temperature }}",
|
||||
state_topic: "zigbee2mqtt/weather_sensor",
|
||||
object_id: "weather_sensor_temperature",
|
||||
default_entity_id: "sensor.weather_sensor_temperature",
|
||||
unique_id: "0x0017880104e45522_temperature_zigbee2mqtt",
|
||||
origin: origin,
|
||||
device: {
|
||||
@@ -789,6 +805,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
value_template: "{{ value_json.humidity }}",
|
||||
state_topic: "zigbee2mqtt/weather_sensor",
|
||||
object_id: "weather_sensor_humidity",
|
||||
default_entity_id: "sensor.weather_sensor_humidity",
|
||||
unique_id: "0x0017880104e45522_humidity_zigbee2mqtt",
|
||||
origin: origin,
|
||||
enabled_by_default: true,
|
||||
@@ -816,6 +833,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
switch: {
|
||||
type: "light",
|
||||
object_id: "light",
|
||||
default_entity_id: "light.light",
|
||||
},
|
||||
light: {
|
||||
type: "this should be ignored",
|
||||
@@ -844,6 +862,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
payload_on: "ON",
|
||||
state_topic: "zigbee2mqtt/my_switch",
|
||||
object_id: "my_switch",
|
||||
default_entity_id: "light.my_switch",
|
||||
unique_id: "0x0017880104e45541_light_zigbee2mqtt",
|
||||
origin: origin,
|
||||
value_template: "{{ value_json.state }}",
|
||||
@@ -902,6 +921,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
speed_range_max: 4,
|
||||
name: null,
|
||||
object_id: "fan",
|
||||
default_entity_id: "fan.fan",
|
||||
unique_id: "0x0017880104e45548_fan_zigbee2mqtt",
|
||||
origin: origin,
|
||||
device: {
|
||||
@@ -921,7 +941,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("Should discover devices with speed-controlled fan", async () => {
|
||||
it("Should discover devices with speed-controlled fan", () => {
|
||||
const payload = {
|
||||
state_topic: "zigbee2mqtt/fanbee",
|
||||
state_value_template: "{{ value_json.state }}",
|
||||
@@ -934,6 +954,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
speed_range_max: 254,
|
||||
name: null,
|
||||
object_id: "fanbee",
|
||||
default_entity_id: "fan.fanbee",
|
||||
unique_id: "0x00124b00cfcf3298_fan_zigbee2mqtt",
|
||||
origin: origin,
|
||||
device: {
|
||||
@@ -995,6 +1016,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
temperature_state_topic: "zigbee2mqtt/TS0601_thermostat",
|
||||
temperature_unit: "C",
|
||||
object_id: "ts0601_thermostat",
|
||||
default_entity_id: "climate.ts0601_thermostat",
|
||||
unique_id: "0x0017882104a44559_climate_zigbee2mqtt",
|
||||
origin: origin,
|
||||
};
|
||||
@@ -1005,6 +1027,77 @@ describe("Extension: HomeAssistant", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("Should discover thermostat devices with read-only PI heating demand", () => {
|
||||
const payload = {
|
||||
availability: [
|
||||
{
|
||||
topic: "zigbee2mqtt/bridge/state",
|
||||
value_template: "{{ value_json.state }}",
|
||||
},
|
||||
],
|
||||
default_entity_id: "sensor.thermostat_pi_heating_demand",
|
||||
device: {
|
||||
identifiers: ["zigbee2mqtt_0x0017880104e45550"],
|
||||
manufacturer: "eCozy",
|
||||
model: "Smart heating thermostat",
|
||||
model_id: "1TST-EU",
|
||||
name: "thermostat",
|
||||
via_device: "zigbee2mqtt_bridge_0x00124b00120144ae",
|
||||
},
|
||||
entity_category: "diagnostic",
|
||||
icon: "mdi:radiator",
|
||||
name: "PI heating demand",
|
||||
object_id: "thermostat_pi_heating_demand",
|
||||
origin: origin,
|
||||
state_topic: "zigbee2mqtt/thermostat",
|
||||
unique_id: "0x0017880104e45550_pi_heating_demand_zigbee2mqtt",
|
||||
unit_of_measurement: "%",
|
||||
value_template: "{{ value_json.pi_heating_demand }}",
|
||||
};
|
||||
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith("homeassistant/sensor/0x0017880104e45550/pi_heating_demand/config", stringify(payload), {
|
||||
retain: true,
|
||||
qos: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("Should discover thermostat devices with writable PI heating demand", () => {
|
||||
const payload = {
|
||||
availability: [
|
||||
{
|
||||
topic: "zigbee2mqtt/bridge/state",
|
||||
value_template: "{{ value_json.state }}",
|
||||
},
|
||||
],
|
||||
command_topic: "zigbee2mqtt/bosch_radiator/set/pi_heating_demand",
|
||||
default_entity_id: "number.bosch_radiator_pi_heating_demand",
|
||||
device: {
|
||||
identifiers: ["zigbee2mqtt_0x18fc2600000d7ae2"],
|
||||
manufacturer: "Bosch",
|
||||
model: "Radiator thermostat II",
|
||||
model_id: "BTH-RA",
|
||||
name: "bosch_radiator",
|
||||
sw_version: "3.05.09",
|
||||
via_device: "zigbee2mqtt_bridge_0x00124b00120144ae",
|
||||
},
|
||||
icon: "mdi:radiator",
|
||||
max: 100,
|
||||
min: 0,
|
||||
name: "PI heating demand",
|
||||
object_id: "bosch_radiator_pi_heating_demand",
|
||||
origin: origin,
|
||||
state_topic: "zigbee2mqtt/bosch_radiator",
|
||||
unique_id: "0x18fc2600000d7ae2_pi_heating_demand_zigbee2mqtt",
|
||||
unit_of_measurement: "%",
|
||||
value_template: "{{ value_json.pi_heating_demand }}",
|
||||
};
|
||||
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith("homeassistant/number/0x18fc2600000d7ae2/pi_heating_demand/config", stringify(payload), {
|
||||
retain: true,
|
||||
qos: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("Should discover Bosch BTH-RA with a compatibility mapping", () => {
|
||||
const payload = {
|
||||
action_template:
|
||||
@@ -1032,6 +1125,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
modes: ["off", "heat", "auto"],
|
||||
name: null,
|
||||
object_id: "bosch_radiator",
|
||||
default_entity_id: "climate.bosch_radiator",
|
||||
origin: origin,
|
||||
temp_step: 0.5,
|
||||
temperature_command_topic: "zigbee2mqtt/bosch_radiator/set/occupied_heating_setpoint",
|
||||
@@ -1084,6 +1178,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
modes: ["heat"],
|
||||
name: null,
|
||||
object_id: "bosch_radiator",
|
||||
default_entity_id: "climate.bosch_radiator",
|
||||
origin: origin,
|
||||
temp_step: 0.5,
|
||||
temperature_command_topic: "zigbee2mqtt/bosch_radiator/set/occupied_heating_setpoint",
|
||||
@@ -1102,6 +1197,51 @@ describe("Extension: HomeAssistant", () => {
|
||||
overrideSpy.mockRestore();
|
||||
});
|
||||
|
||||
it("Should discover Bosch BTH-RM230Z with a current_humidity attribute", () => {
|
||||
const payload = {
|
||||
action_template:
|
||||
"{% set values = {None:None,'idle':'idle','heat':'heating','cool':'cooling','fan_only':'fan'} %}{{ values[value_json.running_state] }}",
|
||||
action_topic: "zigbee2mqtt/bosch_rm230z",
|
||||
availability: [{topic: "zigbee2mqtt/bridge/state", value_template: "{{ value_json.state }}"}],
|
||||
current_humidity_template: "{{ value_json.humidity }}",
|
||||
current_humidity_topic: "zigbee2mqtt/bosch_rm230z",
|
||||
current_temperature_template: "{{ value_json.local_temperature }}",
|
||||
current_temperature_topic: "zigbee2mqtt/bosch_rm230z",
|
||||
default_entity_id: "climate.bosch_rm230z",
|
||||
device: {
|
||||
identifiers: ["zigbee2mqtt_0x18fc2600000d7ae3"],
|
||||
manufacturer: "Bosch",
|
||||
model: "Room thermostat II 230V",
|
||||
model_id: "BTH-RM230Z",
|
||||
name: "bosch_rm230z",
|
||||
via_device: "zigbee2mqtt_bridge_0x00124b00120144ae",
|
||||
},
|
||||
max_temp: "30",
|
||||
min_temp: "5",
|
||||
mode_command_topic: "zigbee2mqtt/bosch_rm230z/set/system_mode",
|
||||
mode_state_template: "{{ value_json.system_mode }}",
|
||||
mode_state_topic: "zigbee2mqtt/bosch_rm230z",
|
||||
modes: ["off", "heat", "cool"],
|
||||
name: null,
|
||||
object_id: "bosch_rm230z",
|
||||
origin,
|
||||
temp_step: 0.5,
|
||||
temperature_high_command_topic: "zigbee2mqtt/bosch_rm230z/set/occupied_cooling_setpoint",
|
||||
temperature_high_state_template: "{{ value_json.occupied_cooling_setpoint }}",
|
||||
temperature_high_state_topic: "zigbee2mqtt/bosch_rm230z",
|
||||
temperature_low_command_topic: "zigbee2mqtt/bosch_rm230z/set/occupied_heating_setpoint",
|
||||
temperature_low_state_template: "{{ value_json.occupied_heating_setpoint }}",
|
||||
temperature_low_state_topic: "zigbee2mqtt/bosch_rm230z",
|
||||
temperature_unit: "C",
|
||||
unique_id: "0x18fc2600000d7ae3_climate_zigbee2mqtt",
|
||||
};
|
||||
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith("homeassistant/climate/0x18fc2600000d7ae3/climate/config", stringify(payload), {
|
||||
qos: 1,
|
||||
retain: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("Should discover devices with cover_position", () => {
|
||||
let payload;
|
||||
|
||||
@@ -1118,6 +1258,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
state_stopped: "STOP",
|
||||
name: null,
|
||||
object_id: "smart_vent",
|
||||
default_entity_id: "cover.smart_vent",
|
||||
unique_id: "0x0017880104e45551_cover_zigbee2mqtt",
|
||||
origin: origin,
|
||||
device: {
|
||||
@@ -1160,6 +1301,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
tilt_status_template: "{{ value_json.tilt }}",
|
||||
tilt_status_topic: "zigbee2mqtt/zigfred_plus/l6",
|
||||
object_id: "zigfred_plus_l6",
|
||||
default_entity_id: "cover.zigfred_plus_l6",
|
||||
unique_id: "0xf4ce368a38be56a1_cover_l6_zigbee2mqtt",
|
||||
origin: origin,
|
||||
value_template: "{{ value_json.state }}",
|
||||
@@ -1182,14 +1324,15 @@ describe("Extension: HomeAssistant", () => {
|
||||
command_topic: "zigbee2mqtt/0xa4c138018cf95021/left/set",
|
||||
device: {
|
||||
identifiers: ["zigbee2mqtt_0xa4c138018cf95021"],
|
||||
manufacturer: "Lonsonho",
|
||||
model: "Dual curtain/blind module",
|
||||
model_id: "TS130F_dual",
|
||||
manufacturer: "Girier",
|
||||
model: "Dual smart curtain switch",
|
||||
model_id: "TS130F_GIRIER_DUAL",
|
||||
name: "0xa4c138018cf95021",
|
||||
via_device: "zigbee2mqtt_bridge_0x00124b00120144ae",
|
||||
},
|
||||
name: "Left",
|
||||
object_id: "0xa4c138018cf95021_left",
|
||||
default_entity_id: "cover.0xa4c138018cf95021_left",
|
||||
origin: origin,
|
||||
position_template: "{{ value_json.position }}",
|
||||
position_topic: "zigbee2mqtt/0xa4c138018cf95021/left",
|
||||
@@ -1212,14 +1355,15 @@ describe("Extension: HomeAssistant", () => {
|
||||
command_topic: "zigbee2mqtt/0xa4c138018cf95021/right/set",
|
||||
device: {
|
||||
identifiers: ["zigbee2mqtt_0xa4c138018cf95021"],
|
||||
manufacturer: "Lonsonho",
|
||||
model: "Dual curtain/blind module",
|
||||
model_id: "TS130F_dual",
|
||||
manufacturer: "Girier",
|
||||
model: "Dual smart curtain switch",
|
||||
model_id: "TS130F_GIRIER_DUAL",
|
||||
name: "0xa4c138018cf95021",
|
||||
via_device: "zigbee2mqtt_bridge_0x00124b00120144ae",
|
||||
},
|
||||
name: "Right",
|
||||
object_id: "0xa4c138018cf95021_right",
|
||||
default_entity_id: "cover.0xa4c138018cf95021_right",
|
||||
origin: origin,
|
||||
position_template: "{{ value_json.position }}",
|
||||
position_topic: "zigbee2mqtt/0xa4c138018cf95021/right",
|
||||
@@ -1233,6 +1377,8 @@ describe("Extension: HomeAssistant", () => {
|
||||
value_template: '{% if "moving" in value_json and value_json.moving %} {{ value_json.moving }} {% else %} STOP {% endif %}',
|
||||
};
|
||||
|
||||
console.log(mockMQTTPublishAsync.mock.calls.find((c) => c[0] === "homeassistant/cover/0xa4c138018cf95021/cover_left/config"));
|
||||
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith("homeassistant/cover/0xa4c138018cf95021/cover_left/config", stringify(payload_left), {
|
||||
retain: true,
|
||||
qos: 1,
|
||||
@@ -1255,6 +1401,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
state_topic: "zigbee2mqtt/weather_sensor",
|
||||
enabled_by_default: true,
|
||||
object_id: "weather_sensor_temperature",
|
||||
default_entity_id: "sensor.weather_sensor_temperature",
|
||||
unique_id: "0x0017880104e45522_temperature_zigbee2mqtt",
|
||||
origin: origin,
|
||||
device: {
|
||||
@@ -1433,6 +1580,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
value_template: "{{ value_json.temperature }}",
|
||||
state_topic: "zigbee2mqtt/weather_sensor",
|
||||
object_id: "weather_sensor_temperature",
|
||||
default_entity_id: "sensor.weather_sensor_temperature",
|
||||
unique_id: "0x0017880104e45522_temperature_zigbee2mqtt",
|
||||
origin: origin,
|
||||
device: {
|
||||
@@ -1467,7 +1615,6 @@ describe("Extension: HomeAssistant", () => {
|
||||
assert("ieeeAddr" in device);
|
||||
resetDiscoveryPayloads(device.ieeeAddr);
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
// @ts-expect-error private
|
||||
controller.eventBus.emitEntityOptionsChanged({entity: device, from: {}, to: {test: 123}});
|
||||
await flushPromises();
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(`homeassistant/light/${device.ID}/light/config`, expect.any(String), expect.any(Object));
|
||||
@@ -1564,7 +1711,8 @@ describe("Extension: HomeAssistant", () => {
|
||||
await flushPromises();
|
||||
await vi.runOnlyPendingTimersAsync();
|
||||
await flushPromises();
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledTimes(0);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledTimes(1);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith("zigbee2mqtt/bridge/health", expect.any(String), expect.any(Object));
|
||||
});
|
||||
|
||||
it("Shouldnt send all status when home assistant comes online with different topic", async () => {
|
||||
@@ -1577,7 +1725,8 @@ describe("Extension: HomeAssistant", () => {
|
||||
await flushPromises();
|
||||
await vi.runOnlyPendingTimersAsync();
|
||||
await flushPromises();
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledTimes(0);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledTimes(1);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith("zigbee2mqtt/bridge/health", expect.any(String), expect.any(Object));
|
||||
});
|
||||
|
||||
it("Should discover devices with availability", async () => {
|
||||
@@ -1592,6 +1741,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
value_template: "{{ value_json.temperature }}",
|
||||
state_topic: "zigbee2mqtt/weather_sensor",
|
||||
object_id: "weather_sensor_temperature",
|
||||
default_entity_id: "sensor.weather_sensor_temperature",
|
||||
unique_id: "0x0017880104e45522_temperature_zigbee2mqtt",
|
||||
origin: origin,
|
||||
device: {
|
||||
@@ -1661,6 +1811,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
value_template: "{{ value_json.temperature }}",
|
||||
state_topic: "zigbee2mqtt/weather_sensor_renamed",
|
||||
object_id: "weather_sensor_renamed_temperature",
|
||||
default_entity_id: "sensor.weather_sensor_renamed_temperature",
|
||||
origin: origin,
|
||||
unique_id: "0x0017880104e45522_temperature_zigbee2mqtt",
|
||||
device: {
|
||||
@@ -1746,6 +1897,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
"stop_hue_effect",
|
||||
],
|
||||
object_id: "ha_discovery_group_new",
|
||||
default_entity_id: "light.ha_discovery_group_new",
|
||||
unique_id: "9_light_zigbee2mqtt",
|
||||
origin: origin,
|
||||
};
|
||||
@@ -1782,6 +1934,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
value_template: "{{ value_json.temperature }}",
|
||||
state_topic: "zigbee2mqtt/weather_sensor_renamed",
|
||||
object_id: "weather_sensor_renamed_temperature",
|
||||
default_entity_id: "sensor.weather_sensor_renamed_temperature",
|
||||
unique_id: "0x0017880104e45522_temperature_zigbee2mqtt",
|
||||
origin: origin,
|
||||
device: {
|
||||
@@ -1818,6 +1971,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
entity_picture: "https://github.com/Koenkk/zigbee2mqtt/raw/master/images/logo.png",
|
||||
name: null,
|
||||
object_id: "bulb",
|
||||
default_entity_id: "update.bulb",
|
||||
origin,
|
||||
payload_install: `{"id": "0x000b57fffec6a5b2"}`,
|
||||
state_topic: "zigbee2mqtt/bulb",
|
||||
@@ -1981,6 +2135,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
icon: "mdi:gesture-double-tap",
|
||||
name: "Action",
|
||||
object_id: "button_action",
|
||||
default_entity_id: "event.button_action",
|
||||
origin: origin,
|
||||
state_topic: "zigbee2mqtt/button",
|
||||
unique_id: "0x0017880104e45520_action_zigbee2mqtt",
|
||||
@@ -2211,6 +2366,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
"stop_hue_effect",
|
||||
],
|
||||
object_id: "ha_discovery_group",
|
||||
default_entity_id: "light.ha_discovery_group",
|
||||
unique_id: "9_light_zigbee2mqtt",
|
||||
origin: origin,
|
||||
};
|
||||
@@ -2255,6 +2411,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
"stop_hue_effect",
|
||||
],
|
||||
object_id: "ha_discovery_group",
|
||||
default_entity_id: "light.ha_discovery_group",
|
||||
unique_id: "9_light_zigbee2mqtt",
|
||||
origin: origin,
|
||||
};
|
||||
@@ -2297,6 +2454,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
state_topic: "zigbee2mqtt/bulb",
|
||||
supported_color_modes: ["color_temp"],
|
||||
object_id: "bulb",
|
||||
default_entity_id: "light.bulb",
|
||||
unique_id: "0x000b57fffec6a5b2_light_zigbee2mqtt",
|
||||
origin: origin,
|
||||
};
|
||||
@@ -2331,6 +2489,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
name: "Last seen",
|
||||
state_topic: "zigbee2mqtt/bulb",
|
||||
object_id: "bulb_last_seen",
|
||||
default_entity_id: "sensor.bulb_last_seen",
|
||||
unique_id: "0x000b57fffec6a5b2_last_seen_zigbee2mqtt",
|
||||
origin: origin,
|
||||
value_template: "{{ value_json.last_seen }}",
|
||||
@@ -2344,7 +2503,12 @@ describe("Extension: HomeAssistant", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("Should discover devices with configuration url", async () => {
|
||||
it.each([
|
||||
// Windfront includes the instance ID in the URL.
|
||||
["zigbee2mqtt-windfront", "http://zigbee.mqtt/#/device/0/0x0017880104e45522/info"],
|
||||
["zigbee2mqtt-frontend", "http://zigbee.mqtt/#/device/0x0017880104e45522/info"],
|
||||
])("Should discover devices with configuration url (%s)", async (packageName: string, expectedUrl: string) => {
|
||||
settings.set(["frontend", "package"], packageName);
|
||||
settings.set(["frontend", "url"], "http://zigbee.mqtt");
|
||||
|
||||
await resetExtension();
|
||||
@@ -2358,6 +2522,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
value_template: "{{ value_json.temperature }}",
|
||||
state_topic: "zigbee2mqtt/weather_sensor",
|
||||
object_id: "weather_sensor_temperature",
|
||||
default_entity_id: "sensor.weather_sensor_temperature",
|
||||
unique_id: "0x0017880104e45522_temperature_zigbee2mqtt",
|
||||
origin: origin,
|
||||
device: {
|
||||
@@ -2366,7 +2531,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
model: "Temperature and humidity sensor",
|
||||
model_id: "WSDCGQ11LM",
|
||||
manufacturer: "Aqara",
|
||||
configuration_url: "http://zigbee.mqtt/#/device/0x0017880104e45522/info",
|
||||
configuration_url: expectedUrl,
|
||||
via_device: "zigbee2mqtt_bridge_0x00124b00120144ae",
|
||||
},
|
||||
availability: [{topic: "zigbee2mqtt/bridge/state", value_template: "{{ value_json.state }}"}],
|
||||
@@ -2385,7 +2550,6 @@ describe("Extension: HomeAssistant", () => {
|
||||
resetDiscoveryPayloads(device.ieeeAddr);
|
||||
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
// @ts-expect-error private
|
||||
controller.eventBus.emitScenesChanged({entity: device});
|
||||
await flushPromises();
|
||||
|
||||
@@ -2399,6 +2563,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
command_topic: "zigbee2mqtt/bulb_color_2/set",
|
||||
payload_on: '{ "scene_recall": 1 }',
|
||||
object_id: "bulb_color_2_1_chill_scene",
|
||||
default_entity_id: "scene.bulb_color_2_1_chill_scene",
|
||||
unique_id: "0x000b57fffec6a5b4_scene_1_zigbee2mqtt",
|
||||
device: {
|
||||
identifiers: ["zigbee2mqtt_0x000b57fffec6a5b4"],
|
||||
@@ -2422,7 +2587,6 @@ describe("Extension: HomeAssistant", () => {
|
||||
resetDiscoveryPayloads("9");
|
||||
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
// @ts-expect-error private
|
||||
controller.eventBus.emitScenesChanged({entity: group});
|
||||
await flushPromises();
|
||||
|
||||
@@ -2439,6 +2603,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
command_topic: "zigbee2mqtt/ha_discovery_group/set",
|
||||
payload_on: '{ "scene_recall": 4 }',
|
||||
object_id: "ha_discovery_group_4_scene_4",
|
||||
default_entity_id: "scene.ha_discovery_group_4_scene_4",
|
||||
unique_id: "9_scene_4_zigbee2mqtt",
|
||||
device: {
|
||||
identifiers: ["zigbee2mqtt_1221051039810110150109113116116_9"],
|
||||
@@ -2456,7 +2621,8 @@ describe("Extension: HomeAssistant", () => {
|
||||
stringify(payload),
|
||||
{retain: true, qos: 1},
|
||||
);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledTimes(6);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledTimes(7);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith("zigbee2mqtt/bridge/health", expect.any(String), expect.any(Object));
|
||||
});
|
||||
|
||||
it("Should not clear bridge entities unnecessarily", async () => {
|
||||
@@ -2466,6 +2632,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
const payload = {
|
||||
name: "Restart",
|
||||
object_id: "zigbee2mqtt_bridge_restart",
|
||||
default_entity_id: "light.zigbee2mqtt_bridge_restart",
|
||||
unique_id: "bridge_0x00124b00120144ae_restart_zigbee2mqtt",
|
||||
device_class: "restart",
|
||||
command_topic: "zigbee2mqtt/bridge/request/restart",
|
||||
@@ -2483,7 +2650,6 @@ describe("Extension: HomeAssistant", () => {
|
||||
availability_mode: "all",
|
||||
};
|
||||
|
||||
// @ts-expect-error private
|
||||
controller.eventBus.emitMQTTMessage({
|
||||
topic: topic,
|
||||
message: stringify(payload),
|
||||
@@ -2508,6 +2674,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
payload = {
|
||||
name: "Connection state",
|
||||
object_id: "zigbee2mqtt_bridge_connection_state",
|
||||
default_entity_id: "binary_sensor.zigbee2mqtt_bridge_connection_state",
|
||||
entity_category: "diagnostic",
|
||||
device_class: "connectivity",
|
||||
unique_id: "bridge_0x00124b00120144ae_connection_state_zigbee2mqtt",
|
||||
@@ -2527,6 +2694,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
payload = {
|
||||
name: "Restart required",
|
||||
object_id: "zigbee2mqtt_bridge_restart_required",
|
||||
default_entity_id: "binary_sensor.zigbee2mqtt_bridge_restart_required",
|
||||
entity_category: "diagnostic",
|
||||
device_class: "problem",
|
||||
enabled_by_default: false,
|
||||
@@ -2550,6 +2718,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
payload = {
|
||||
name: "Restart",
|
||||
object_id: "zigbee2mqtt_bridge_restart",
|
||||
default_entity_id: "button.zigbee2mqtt_bridge_restart",
|
||||
unique_id: "bridge_0x00124b00120144ae_restart_zigbee2mqtt",
|
||||
device_class: "restart",
|
||||
command_topic: "zigbee2mqtt/bridge/request/restart",
|
||||
@@ -2569,6 +2738,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
payload = {
|
||||
name: "Log level",
|
||||
object_id: "zigbee2mqtt_bridge_log_level",
|
||||
default_entity_id: "select.zigbee2mqtt_bridge_log_level",
|
||||
entity_category: "config",
|
||||
unique_id: "bridge_0x00124b00120144ae_log_level_zigbee2mqtt",
|
||||
state_topic: "zigbee2mqtt/bridge/info",
|
||||
@@ -2591,6 +2761,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
payload = {
|
||||
name: "Version",
|
||||
object_id: "zigbee2mqtt_bridge_version",
|
||||
default_entity_id: "sensor.zigbee2mqtt_bridge_version",
|
||||
entity_category: "diagnostic",
|
||||
icon: "mdi:zigbee",
|
||||
unique_id: "bridge_0x00124b00120144ae_version_zigbee2mqtt",
|
||||
@@ -2610,6 +2781,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
payload = {
|
||||
name: "Coordinator version",
|
||||
object_id: "zigbee2mqtt_bridge_coordinator_version",
|
||||
default_entity_id: "sensor.zigbee2mqtt_bridge_coordinator_version",
|
||||
entity_category: "diagnostic",
|
||||
enabled_by_default: false,
|
||||
icon: "mdi:chip",
|
||||
@@ -2630,6 +2802,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
payload = {
|
||||
name: "Network map",
|
||||
object_id: "zigbee2mqtt_bridge_network_map",
|
||||
default_entity_id: "sensor.zigbee2mqtt_bridge_network_map",
|
||||
entity_category: "diagnostic",
|
||||
enabled_by_default: false,
|
||||
unique_id: "bridge_0x00124b00120144ae_network_map_zigbee2mqtt",
|
||||
@@ -2652,6 +2825,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
payload = {
|
||||
name: "Permit join",
|
||||
object_id: "zigbee2mqtt_bridge_permit_join",
|
||||
default_entity_id: "switch.zigbee2mqtt_bridge_permit_join",
|
||||
icon: "mdi:human-greeting-proximity",
|
||||
unique_id: "bridge_0x00124b00120144ae_permit_join_zigbee2mqtt",
|
||||
state_topic: "zigbee2mqtt/bridge/info",
|
||||
@@ -2688,7 +2862,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
mockMQTTPublishAsync.mockClear();
|
||||
const device = devices["BMCT-SLZ"];
|
||||
const data = {deviceMode: 0};
|
||||
const msg = {data, cluster: "boschSpecific", device, endpoint: device.getEndpoint(1), type: "attributeReport", linkquality: 10};
|
||||
const msg = {data, cluster: "boschEnergyDevice", device, endpoint: device.getEndpoint(1), type: "attributeReport", linkquality: 10};
|
||||
resetDiscoveryPayloads("0x18fc26000000cafe");
|
||||
await mockZHEvents.message(msg);
|
||||
await flushPromises();
|
||||
@@ -2707,6 +2881,7 @@ describe("Extension: HomeAssistant", () => {
|
||||
icon: "mdi:tune",
|
||||
name: "Device mode",
|
||||
object_id: "0x18fc26000000cafe_device_mode",
|
||||
default_entity_id: "select.0x18fc26000000cafe_device_mode",
|
||||
options: ["light", "shutter", "disabled"],
|
||||
origin: origin,
|
||||
state_topic: "zigbee2mqtt/0x18fc26000000cafe",
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
// biome-ignore assist/source/organizeImports: import mocks first
|
||||
import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from "vitest";
|
||||
import type {Eui64} from "zigbee-herdsman/dist/zspec/tstypes";
|
||||
import * as data from "../mocks/data";
|
||||
import {mockLogger} from "../mocks/logger";
|
||||
import {events as mockMQTTEvents, mockMQTTPublishAsync} from "../mocks/mqtt";
|
||||
@@ -7,9 +10,7 @@ import {devices, events as mockZHEvents, returnDevices} from "../mocks/zigbeeHer
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import stringify from "json-stable-stringify-without-jsonify";
|
||||
|
||||
import {Controller} from "../../lib/controller";
|
||||
import * as settings from "../../lib/util/settings";
|
||||
|
||||
@@ -25,6 +26,22 @@ returnDevices.push(
|
||||
|
||||
const mocksClear = [mockMQTTPublishAsync, mockLogger.warning, mockLogger.debug];
|
||||
|
||||
const LQI_BASE_RSP = {
|
||||
extendedPanId: [],
|
||||
deviceType: 0,
|
||||
rxOnWhenIdle: 0,
|
||||
reserved1: 0,
|
||||
permitJoining: 0,
|
||||
reserved2: 0,
|
||||
};
|
||||
|
||||
const ROUTING_BASE_RSP = {
|
||||
memoryConstrained: 0,
|
||||
manyToOne: 0,
|
||||
routeRecordRequired: 0,
|
||||
reserved1: 0,
|
||||
};
|
||||
|
||||
describe("Extension: NetworkMap", () => {
|
||||
let controller: Controller;
|
||||
|
||||
@@ -39,58 +56,62 @@ describe("Extension: NetworkMap", () => {
|
||||
* | -> CC2530_ROUTER -> WXKG02LM_rev1
|
||||
*
|
||||
*/
|
||||
devices.coordinator.lqi.mockResolvedValueOnce({
|
||||
neighbors: [
|
||||
{
|
||||
ieeeAddr: devices.bulb_color.ieeeAddr,
|
||||
networkAddress: devices.bulb_color.networkAddress,
|
||||
relationship: 2,
|
||||
depth: 1,
|
||||
linkquality: 120,
|
||||
},
|
||||
{ieeeAddr: devices.bulb.ieeeAddr, networkAddress: devices.bulb.networkAddress, relationship: 2, depth: 1, linkquality: 92},
|
||||
{
|
||||
ieeeAddr: devices.external_converter_device.ieeeAddr,
|
||||
networkAddress: devices.external_converter_device.networkAddress,
|
||||
relationship: 2,
|
||||
depth: 1,
|
||||
linkquality: 92,
|
||||
},
|
||||
],
|
||||
});
|
||||
devices.coordinator.routingTable.mockResolvedValueOnce({
|
||||
table: [{destinationAddress: devices.CC2530_ROUTER.networkAddress, status: "ACTIVE", nextHop: devices.bulb.networkAddress}],
|
||||
});
|
||||
devices.bulb.lqi.mockResolvedValueOnce({
|
||||
neighbors: [
|
||||
{
|
||||
ieeeAddr: devices.bulb_color.ieeeAddr,
|
||||
networkAddress: devices.bulb_color.networkAddress,
|
||||
relationship: 1,
|
||||
depth: 2,
|
||||
linkquality: 110,
|
||||
},
|
||||
{
|
||||
ieeeAddr: devices.CC2530_ROUTER.ieeeAddr,
|
||||
networkAddress: devices.CC2530_ROUTER.networkAddress,
|
||||
relationship: 1,
|
||||
depth: 2,
|
||||
linkquality: 100,
|
||||
},
|
||||
],
|
||||
});
|
||||
devices.CC2530_ROUTER.lqi.mockResolvedValueOnce({
|
||||
neighbors: [
|
||||
{ieeeAddr: "0x0000000000000000", networkAddress: devices.WXKG02LM_rev1.networkAddress, relationship: 1, depth: 2, linkquality: 130},
|
||||
{
|
||||
ieeeAddr: devices.bulb_color.ieeeAddr,
|
||||
networkAddress: devices.bulb_color.networkAddress,
|
||||
relationship: 4,
|
||||
depth: 2,
|
||||
linkquality: 130,
|
||||
},
|
||||
],
|
||||
});
|
||||
devices.coordinator.lqi.mockResolvedValueOnce([
|
||||
{
|
||||
eui64: devices.bulb_color.ieeeAddr as Eui64,
|
||||
nwkAddress: devices.bulb_color.networkAddress,
|
||||
relationship: 2,
|
||||
depth: 1,
|
||||
lqi: 120,
|
||||
...LQI_BASE_RSP,
|
||||
},
|
||||
{eui64: devices.bulb.ieeeAddr as Eui64, nwkAddress: devices.bulb.networkAddress, relationship: 2, depth: 1, lqi: 92, ...LQI_BASE_RSP},
|
||||
{
|
||||
eui64: devices.external_converter_device.ieeeAddr as Eui64,
|
||||
nwkAddress: devices.external_converter_device.networkAddress,
|
||||
relationship: 2,
|
||||
depth: 1,
|
||||
lqi: 92,
|
||||
...LQI_BASE_RSP,
|
||||
},
|
||||
]);
|
||||
devices.coordinator.routingTable.mockResolvedValueOnce([
|
||||
{
|
||||
destinationAddress: devices.CC2530_ROUTER.networkAddress,
|
||||
status: "ACTIVE",
|
||||
nextHopAddress: devices.bulb.networkAddress,
|
||||
...ROUTING_BASE_RSP,
|
||||
},
|
||||
]);
|
||||
devices.bulb.lqi.mockResolvedValueOnce([
|
||||
{
|
||||
eui64: devices.bulb_color.ieeeAddr as Eui64,
|
||||
nwkAddress: devices.bulb_color.networkAddress,
|
||||
relationship: 1,
|
||||
depth: 2,
|
||||
lqi: 110,
|
||||
...LQI_BASE_RSP,
|
||||
},
|
||||
{
|
||||
eui64: devices.CC2530_ROUTER.ieeeAddr as Eui64,
|
||||
nwkAddress: devices.CC2530_ROUTER.networkAddress,
|
||||
relationship: 1,
|
||||
depth: 2,
|
||||
lqi: 100,
|
||||
...LQI_BASE_RSP,
|
||||
},
|
||||
]);
|
||||
devices.CC2530_ROUTER.lqi.mockResolvedValueOnce([
|
||||
{eui64: "0x0000000000000000", nwkAddress: devices.WXKG02LM_rev1.networkAddress, relationship: 1, depth: 2, lqi: 130, ...LQI_BASE_RSP},
|
||||
{
|
||||
eui64: devices.bulb_color.ieeeAddr as Eui64,
|
||||
nwkAddress: devices.bulb_color.networkAddress,
|
||||
relationship: 4,
|
||||
depth: 2,
|
||||
lqi: 130,
|
||||
...LQI_BASE_RSP,
|
||||
},
|
||||
]);
|
||||
devices.unsupported_router.lqi.mockRejectedValueOnce("failed").mockRejectedValueOnce("failed");
|
||||
devices.unsupported_router.routingTable.mockRejectedValueOnce("failed").mockRejectedValueOnce("failed");
|
||||
};
|
||||
@@ -143,6 +164,9 @@ describe("Extension: NetworkMap", () => {
|
||||
value: {
|
||||
links: [
|
||||
{
|
||||
deviceType: 0,
|
||||
rxOnWhenIdle: 0,
|
||||
permitJoining: 0,
|
||||
depth: 1,
|
||||
linkquality: 120,
|
||||
lqi: 120,
|
||||
@@ -155,11 +179,14 @@ describe("Extension: NetworkMap", () => {
|
||||
targetIeeeAddr: "0x00124b00120144ae",
|
||||
},
|
||||
{
|
||||
deviceType: 0,
|
||||
rxOnWhenIdle: 0,
|
||||
permitJoining: 0,
|
||||
depth: 1,
|
||||
linkquality: 92,
|
||||
lqi: 92,
|
||||
relationship: 2,
|
||||
routes: [{destinationAddress: 6540, nextHop: 40369, status: "ACTIVE"}],
|
||||
routes: [{destinationAddress: 6540, nextHopAddress: 40369, status: "ACTIVE", ...ROUTING_BASE_RSP}],
|
||||
source: {ieeeAddr: "0x000b57fffec6a5b2", networkAddress: 40369},
|
||||
sourceIeeeAddr: "0x000b57fffec6a5b2",
|
||||
sourceNwkAddr: 40369,
|
||||
@@ -167,6 +194,9 @@ describe("Extension: NetworkMap", () => {
|
||||
targetIeeeAddr: "0x00124b00120144ae",
|
||||
},
|
||||
{
|
||||
deviceType: 0,
|
||||
rxOnWhenIdle: 0,
|
||||
permitJoining: 0,
|
||||
depth: 1,
|
||||
linkquality: 92,
|
||||
lqi: 92,
|
||||
@@ -179,6 +209,9 @@ describe("Extension: NetworkMap", () => {
|
||||
targetIeeeAddr: "0x00124b00120144ae",
|
||||
},
|
||||
{
|
||||
deviceType: 0,
|
||||
rxOnWhenIdle: 0,
|
||||
permitJoining: 0,
|
||||
depth: 2,
|
||||
linkquality: 110,
|
||||
lqi: 110,
|
||||
@@ -191,6 +224,9 @@ describe("Extension: NetworkMap", () => {
|
||||
targetIeeeAddr: "0x000b57fffec6a5b2",
|
||||
},
|
||||
{
|
||||
deviceType: 0,
|
||||
rxOnWhenIdle: 0,
|
||||
permitJoining: 0,
|
||||
depth: 2,
|
||||
linkquality: 100,
|
||||
lqi: 100,
|
||||
@@ -203,6 +239,9 @@ describe("Extension: NetworkMap", () => {
|
||||
targetIeeeAddr: "0x000b57fffec6a5b2",
|
||||
},
|
||||
{
|
||||
deviceType: 0,
|
||||
rxOnWhenIdle: 0,
|
||||
permitJoining: 0,
|
||||
depth: 2,
|
||||
linkquality: 130,
|
||||
lqi: 130,
|
||||
@@ -492,6 +531,9 @@ describe("Extension: NetworkMap", () => {
|
||||
value: {
|
||||
links: [
|
||||
{
|
||||
deviceType: 0,
|
||||
rxOnWhenIdle: 0,
|
||||
permitJoining: 0,
|
||||
depth: 1,
|
||||
linkquality: 120,
|
||||
lqi: 120,
|
||||
@@ -504,11 +546,14 @@ describe("Extension: NetworkMap", () => {
|
||||
targetIeeeAddr: "0x00124b00120144ae",
|
||||
},
|
||||
{
|
||||
deviceType: 0,
|
||||
rxOnWhenIdle: 0,
|
||||
permitJoining: 0,
|
||||
depth: 1,
|
||||
linkquality: 92,
|
||||
lqi: 92,
|
||||
relationship: 2,
|
||||
routes: [{destinationAddress: 6540, nextHop: 40369, status: "ACTIVE"}],
|
||||
routes: [{destinationAddress: 6540, nextHopAddress: 40369, status: "ACTIVE", ...ROUTING_BASE_RSP}],
|
||||
source: {ieeeAddr: "0x000b57fffec6a5b2", networkAddress: 40369},
|
||||
sourceIeeeAddr: "0x000b57fffec6a5b2",
|
||||
sourceNwkAddr: 40369,
|
||||
@@ -516,6 +561,9 @@ describe("Extension: NetworkMap", () => {
|
||||
targetIeeeAddr: "0x00124b00120144ae",
|
||||
},
|
||||
{
|
||||
deviceType: 0,
|
||||
rxOnWhenIdle: 0,
|
||||
permitJoining: 0,
|
||||
depth: 1,
|
||||
linkquality: 92,
|
||||
lqi: 92,
|
||||
@@ -528,6 +576,9 @@ describe("Extension: NetworkMap", () => {
|
||||
targetIeeeAddr: "0x00124b00120144ae",
|
||||
},
|
||||
{
|
||||
deviceType: 0,
|
||||
rxOnWhenIdle: 0,
|
||||
permitJoining: 0,
|
||||
depth: 2,
|
||||
linkquality: 130,
|
||||
lqi: 130,
|
||||
@@ -649,6 +700,9 @@ describe("Extension: NetworkMap", () => {
|
||||
value: {
|
||||
links: [
|
||||
{
|
||||
deviceType: 0,
|
||||
rxOnWhenIdle: 0,
|
||||
permitJoining: 0,
|
||||
depth: 1,
|
||||
linkquality: 120,
|
||||
lqi: 120,
|
||||
@@ -661,11 +715,14 @@ describe("Extension: NetworkMap", () => {
|
||||
targetIeeeAddr: "0x00124b00120144ae",
|
||||
},
|
||||
{
|
||||
deviceType: 0,
|
||||
rxOnWhenIdle: 0,
|
||||
permitJoining: 0,
|
||||
depth: 1,
|
||||
linkquality: 92,
|
||||
lqi: 92,
|
||||
relationship: 2,
|
||||
routes: [{destinationAddress: 6540, nextHop: 40369, status: "ACTIVE"}],
|
||||
routes: [{destinationAddress: 6540, nextHopAddress: 40369, status: "ACTIVE", ...ROUTING_BASE_RSP}],
|
||||
source: {ieeeAddr: "0x000b57fffec6a5b2", networkAddress: 40369},
|
||||
sourceIeeeAddr: "0x000b57fffec6a5b2",
|
||||
sourceNwkAddr: 40369,
|
||||
@@ -673,6 +730,9 @@ describe("Extension: NetworkMap", () => {
|
||||
targetIeeeAddr: "0x00124b00120144ae",
|
||||
},
|
||||
{
|
||||
deviceType: 0,
|
||||
rxOnWhenIdle: 0,
|
||||
permitJoining: 0,
|
||||
depth: 1,
|
||||
linkquality: 92,
|
||||
lqi: 92,
|
||||
@@ -685,6 +745,9 @@ describe("Extension: NetworkMap", () => {
|
||||
targetIeeeAddr: "0x00124b00120144ae",
|
||||
},
|
||||
{
|
||||
deviceType: 0,
|
||||
rxOnWhenIdle: 0,
|
||||
permitJoining: 0,
|
||||
depth: 2,
|
||||
linkquality: 130,
|
||||
lqi: 130,
|
||||
|
||||
@@ -1,19 +1,18 @@
|
||||
// biome-ignore assist/source/organizeImports: import mocks first
|
||||
import {afterAll, beforeAll, beforeEach, describe, expect, it, vi, assert} from "vitest";
|
||||
import * as data from "../mocks/data";
|
||||
import {mockLogger} from "../mocks/logger";
|
||||
import {mockMQTTPublishAsync} from "../mocks/mqtt";
|
||||
import {flushPromises} from "../mocks/utils";
|
||||
import type {Device as ZhDevice} from "../mocks/zigbeeHerdsman";
|
||||
import {devices, events as mockZHEvents, returnDevices} from "../mocks/zigbeeHerdsman";
|
||||
|
||||
import type {MockInstance} from "vitest";
|
||||
import type {OnEvent as DefinitionOnEvent} from "zigbee-herdsman-converters/lib/types";
|
||||
|
||||
import type Device from "../../lib/model/device";
|
||||
import type {Device as ZhDevice} from "../mocks/zigbeeHerdsman";
|
||||
|
||||
import * as zhc from "zigbee-herdsman-converters";
|
||||
|
||||
import type {OnEvent as ZhcOnEvent} from "zigbee-herdsman-converters/lib/types";
|
||||
import {Controller} from "../../lib/controller";
|
||||
import OnEvent from "../../lib/extension/onEvent";
|
||||
import type Device from "../../lib/model/device";
|
||||
import * as settings from "../../lib/util/settings";
|
||||
|
||||
const mocksClear = [mockMQTTPublishAsync, mockLogger.warning, mockLogger.debug];
|
||||
@@ -23,18 +22,12 @@ returnDevices.push(devices.bulb.ieeeAddr, devices.LIVOLO.ieeeAddr, devices.coord
|
||||
describe("Extension: OnEvent", () => {
|
||||
let controller: Controller;
|
||||
let onEventSpy: MockInstance<typeof zhc.onEvent>;
|
||||
let deviceOnEventSpy: MockInstance<DefinitionOnEvent>;
|
||||
let deviceOnEventSpy: MockInstance<ZhcOnEvent.Handler>;
|
||||
|
||||
const getZ2MDevice = (zhDevice: string | number | ZhDevice): Device => {
|
||||
// @ts-expect-error private
|
||||
return controller.zigbee.resolveEntity(zhDevice)! as Device;
|
||||
};
|
||||
|
||||
const clearOnEventSpies = (): void => {
|
||||
onEventSpy.mockClear();
|
||||
deviceOnEventSpy.mockClear();
|
||||
};
|
||||
|
||||
beforeAll(async () => {
|
||||
vi.useFakeTimers();
|
||||
data.writeDefaultConfiguration();
|
||||
@@ -54,7 +47,8 @@ describe("Extension: OnEvent", () => {
|
||||
}
|
||||
|
||||
await controller.removeExtension(controller.getExtension("OnEvent")!);
|
||||
clearOnEventSpies();
|
||||
onEventSpy.mockClear();
|
||||
deviceOnEventSpy.mockClear();
|
||||
await controller.addExtension(new OnEvent(...controller.extensionArgs));
|
||||
});
|
||||
|
||||
@@ -67,115 +61,121 @@ describe("Extension: OnEvent", () => {
|
||||
it("starts & stops", async () => {
|
||||
expect(onEventSpy).toHaveBeenCalledTimes(2);
|
||||
expect(deviceOnEventSpy).toHaveBeenCalledTimes(1);
|
||||
expect(deviceOnEventSpy).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
"start",
|
||||
{},
|
||||
devices.LIVOLO,
|
||||
settings.getDevice(devices.LIVOLO.ieeeAddr),
|
||||
{},
|
||||
{deviceExposesChanged: expect.any(Function)},
|
||||
);
|
||||
expect(deviceOnEventSpy).toHaveBeenNthCalledWith(1, {
|
||||
type: "start",
|
||||
data: {
|
||||
device: devices.LIVOLO,
|
||||
options: settings.getDevice(devices.LIVOLO.ieeeAddr),
|
||||
state: {},
|
||||
deviceExposesChanged: expect.any(Function),
|
||||
},
|
||||
});
|
||||
|
||||
await controller.stop();
|
||||
|
||||
expect(onEventSpy).toHaveBeenCalledTimes(4);
|
||||
expect(deviceOnEventSpy).toHaveBeenCalledTimes(2);
|
||||
expect(deviceOnEventSpy).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
"stop",
|
||||
{},
|
||||
devices.LIVOLO,
|
||||
settings.getDevice(devices.LIVOLO.ieeeAddr),
|
||||
{},
|
||||
{deviceExposesChanged: expect.any(Function)},
|
||||
);
|
||||
expect(deviceOnEventSpy).toHaveBeenNthCalledWith(2, {
|
||||
type: "stop",
|
||||
data: {
|
||||
ieeeAddr: devices.LIVOLO.ieeeAddr,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("calls on device events", async () => {
|
||||
clearOnEventSpies();
|
||||
await mockZHEvents.deviceAnnounce({device: devices.LIVOLO});
|
||||
await flushPromises();
|
||||
|
||||
expect(deviceOnEventSpy).toHaveBeenCalledTimes(1);
|
||||
expect(deviceOnEventSpy).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
"deviceAnnounce",
|
||||
{},
|
||||
devices.LIVOLO,
|
||||
settings.getDevice(devices.LIVOLO.ieeeAddr),
|
||||
{},
|
||||
{deviceExposesChanged: expect.any(Function)},
|
||||
);
|
||||
// Should always call with 'start' event first
|
||||
expect(deviceOnEventSpy).toHaveBeenCalledTimes(2);
|
||||
expect(deviceOnEventSpy).toHaveBeenNthCalledWith(1, {
|
||||
type: "start",
|
||||
data: {
|
||||
device: devices.LIVOLO,
|
||||
options: settings.getDevice(devices.LIVOLO.ieeeAddr),
|
||||
state: {},
|
||||
deviceExposesChanged: expect.any(Function),
|
||||
},
|
||||
});
|
||||
|
||||
// Device announce
|
||||
expect(deviceOnEventSpy).toHaveBeenCalledTimes(2);
|
||||
expect(deviceOnEventSpy).toHaveBeenNthCalledWith(2, {
|
||||
type: "deviceAnnounce",
|
||||
data: {
|
||||
device: devices.LIVOLO,
|
||||
options: settings.getDevice(devices.LIVOLO.ieeeAddr),
|
||||
state: {},
|
||||
deviceExposesChanged: expect.any(Function),
|
||||
},
|
||||
});
|
||||
|
||||
// Check deviceExposesChanged()
|
||||
const emitExposesAndDevicesChangedSpy = vi.spyOn(
|
||||
// @ts-expect-error protected
|
||||
controller.getExtension("OnEvent")!.eventBus,
|
||||
"emitExposesAndDevicesChanged",
|
||||
);
|
||||
|
||||
deviceOnEventSpy.mock.calls[0][5]!.deviceExposesChanged();
|
||||
|
||||
assert(deviceOnEventSpy.mock.calls[0][0]!.type === "start");
|
||||
deviceOnEventSpy.mock.calls[0][0]!.data.deviceExposesChanged();
|
||||
expect(emitExposesAndDevicesChangedSpy).toHaveBeenCalledTimes(1);
|
||||
expect(emitExposesAndDevicesChangedSpy).toHaveBeenCalledWith(getZ2MDevice(devices.LIVOLO));
|
||||
|
||||
// Call `stop` when device leaves
|
||||
await mockZHEvents.deviceLeave({ieeeAddr: devices.LIVOLO.ieeeAddr});
|
||||
await flushPromises();
|
||||
|
||||
expect(deviceOnEventSpy).toHaveBeenCalledTimes(2);
|
||||
expect(deviceOnEventSpy).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
"stop",
|
||||
{},
|
||||
devices.LIVOLO,
|
||||
settings.getDevice(devices.LIVOLO.ieeeAddr),
|
||||
{},
|
||||
{deviceExposesChanged: expect.any(Function)},
|
||||
);
|
||||
});
|
||||
|
||||
it("calls on device message", async () => {
|
||||
clearOnEventSpies();
|
||||
|
||||
await mockZHEvents.message({
|
||||
type: "attributeReport",
|
||||
device: devices.LIVOLO,
|
||||
endpoint: devices.LIVOLO.endpoints[0],
|
||||
linkquality: 213,
|
||||
groupID: 0,
|
||||
cluster: "genBasic",
|
||||
data: {zclVersion: 8},
|
||||
meta: {zclTransactionSequenceNumber: 1, manufacturerCode: devices.LIVOLO.manufacturerID},
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
expect(deviceOnEventSpy).toHaveBeenCalledTimes(1);
|
||||
expect(deviceOnEventSpy).toHaveBeenCalledWith(
|
||||
"message",
|
||||
{
|
||||
type: "attributeReport",
|
||||
endpoint: devices.LIVOLO.endpoints[0],
|
||||
cluster: "genBasic",
|
||||
data: {zclVersion: 8},
|
||||
meta: {zclTransactionSequenceNumber: 1, manufacturerCode: devices.LIVOLO.manufacturerID},
|
||||
expect(deviceOnEventSpy).toHaveBeenCalledTimes(3);
|
||||
expect(deviceOnEventSpy).toHaveBeenNthCalledWith(3, {
|
||||
type: "stop",
|
||||
data: {
|
||||
ieeeAddr: devices.LIVOLO.ieeeAddr,
|
||||
},
|
||||
devices.LIVOLO,
|
||||
settings.getDevice(devices.LIVOLO.ieeeAddr),
|
||||
{},
|
||||
{deviceExposesChanged: expect.any(Function)},
|
||||
);
|
||||
});
|
||||
|
||||
// Call `stop` when device is removed
|
||||
// @ts-expect-error private
|
||||
controller.eventBus.emitEntityRemoved({entity: getZ2MDevice(devices.LIVOLO)});
|
||||
await flushPromises();
|
||||
expect(deviceOnEventSpy).toHaveBeenCalledTimes(4);
|
||||
expect(deviceOnEventSpy).toHaveBeenNthCalledWith(4, {
|
||||
type: "stop",
|
||||
data: {
|
||||
ieeeAddr: devices.LIVOLO.ieeeAddr,
|
||||
},
|
||||
});
|
||||
|
||||
// Device interview, should call with 'start' first as 'stop' was called
|
||||
await mockZHEvents.deviceInterview({device: devices.LIVOLO, status: "started"});
|
||||
await flushPromises();
|
||||
expect(deviceOnEventSpy).toHaveBeenCalledTimes(6);
|
||||
expect(deviceOnEventSpy).toHaveBeenNthCalledWith(5, {
|
||||
type: "start",
|
||||
data: {
|
||||
device: devices.LIVOLO,
|
||||
options: settings.getDevice(devices.LIVOLO.ieeeAddr),
|
||||
state: {},
|
||||
deviceExposesChanged: expect.any(Function),
|
||||
},
|
||||
});
|
||||
expect(deviceOnEventSpy).toHaveBeenNthCalledWith(6, {
|
||||
type: "deviceInterview",
|
||||
data: {
|
||||
device: devices.LIVOLO,
|
||||
options: settings.getDevice(devices.LIVOLO.ieeeAddr),
|
||||
state: {},
|
||||
deviceExposesChanged: expect.any(Function),
|
||||
status: "started",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("does not block startup on failure", async () => {
|
||||
await controller.removeExtension(controller.getExtension("OnEvent")!);
|
||||
clearOnEventSpies();
|
||||
deviceOnEventSpy.mockImplementationOnce(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 10000));
|
||||
throw new Error("Failed");
|
||||
});
|
||||
await controller.addExtension(new OnEvent(...controller.extensionArgs));
|
||||
|
||||
expect(onEventSpy).toHaveBeenCalledTimes(2);
|
||||
expect(deviceOnEventSpy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// biome-ignore assist/source/organizeImports: import mocks first
|
||||
import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from "vitest";
|
||||
import * as data from "../mocks/data";
|
||||
import {mockLogger} from "../mocks/logger";
|
||||
import {events as mockMQTTEvents, mockMQTTPublishAsync} from "../mocks/mqtt";
|
||||
@@ -6,11 +8,8 @@ import {flushPromises} from "../mocks/utils";
|
||||
import {devices, events as mockZHEvents} from "../mocks/zigbeeHerdsman";
|
||||
|
||||
import path from "node:path";
|
||||
|
||||
import stringify from "json-stable-stringify-without-jsonify";
|
||||
|
||||
import * as zhc from "zigbee-herdsman-converters";
|
||||
|
||||
import {Controller} from "../../lib/controller";
|
||||
import OTAUpdate from "../../lib/extension/otaUpdate";
|
||||
import * as settings from "../../lib/util/settings";
|
||||
@@ -69,7 +68,6 @@ describe("Extension: OTAUpdate", () => {
|
||||
devices.bulb.mockClear();
|
||||
updateSpy.mockClear();
|
||||
isUpdateAvailableSpy.mockClear();
|
||||
// @ts-expect-error private
|
||||
controller.state.clear();
|
||||
});
|
||||
|
||||
@@ -278,50 +276,55 @@ describe("Extension: OTAUpdate", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.each(["check", "check/downgrade", "update", "update/downgrade", "schedule", "schedule/downgrade", "unschedule"])(
|
||||
"refuses to %s when already in progress",
|
||||
async (type) => {
|
||||
if (type.includes("schedule") || type.includes("check")) {
|
||||
isUpdateAvailableSpy.mockImplementationOnce(async () => {
|
||||
return await new Promise((resolve) => {
|
||||
setTimeout(
|
||||
() =>
|
||||
resolve({
|
||||
available: false,
|
||||
currentFileVersion: 1,
|
||||
otaFileVersion: 1,
|
||||
}),
|
||||
99999,
|
||||
);
|
||||
});
|
||||
it.each([
|
||||
"check",
|
||||
"check/downgrade",
|
||||
"update",
|
||||
"update/downgrade",
|
||||
"schedule",
|
||||
"schedule/downgrade",
|
||||
"unschedule",
|
||||
])("refuses to %s when already in progress", async (type) => {
|
||||
if (type.includes("schedule") || type.includes("check")) {
|
||||
isUpdateAvailableSpy.mockImplementationOnce(async () => {
|
||||
return await new Promise((resolve) => {
|
||||
setTimeout(
|
||||
() =>
|
||||
resolve({
|
||||
available: false,
|
||||
currentFileVersion: 1,
|
||||
otaFileVersion: 1,
|
||||
}),
|
||||
99999,
|
||||
);
|
||||
});
|
||||
} else {
|
||||
updateSpy.mockImplementationOnce(async () => {
|
||||
return await new Promise((resolve) => {
|
||||
setTimeout(() => resolve(1), 99999);
|
||||
});
|
||||
});
|
||||
} else {
|
||||
updateSpy.mockImplementationOnce(async () => {
|
||||
return await new Promise((resolve) => {
|
||||
setTimeout(() => resolve(1), 99999);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
mockMQTTEvents.message(`zigbee2mqtt/bridge/request/device/ota_update/${type.includes("schedule") ? "check" : type}`, "bulb");
|
||||
await flushPromises();
|
||||
mockMQTTEvents.message(`zigbee2mqtt/bridge/request/device/ota_update/${type}`, "bulb");
|
||||
await flushPromises();
|
||||
mockMQTTEvents.message(`zigbee2mqtt/bridge/request/device/ota_update/${type.includes("schedule") ? "check" : type}`, "bulb");
|
||||
await flushPromises();
|
||||
mockMQTTEvents.message(`zigbee2mqtt/bridge/request/device/ota_update/${type}`, "bulb");
|
||||
await flushPromises();
|
||||
|
||||
if (type.includes("schedule") || type.includes("check")) {
|
||||
expect(isUpdateAvailableSpy).toHaveBeenCalledTimes(1);
|
||||
} else {
|
||||
expect(updateSpy).toHaveBeenCalledTimes(1);
|
||||
}
|
||||
if (type.includes("schedule") || type.includes("check")) {
|
||||
expect(isUpdateAvailableSpy).toHaveBeenCalledTimes(1);
|
||||
} else {
|
||||
expect(updateSpy).toHaveBeenCalledTimes(1);
|
||||
}
|
||||
|
||||
await vi.runOnlyPendingTimersAsync();
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
`zigbee2mqtt/bridge/response/device/ota_update/${type.replace("/downgrade", "")}`,
|
||||
stringify({data: {}, status: "error", error: `Update or check for update already in progress for 'bulb'`}),
|
||||
{},
|
||||
);
|
||||
},
|
||||
);
|
||||
await vi.runOnlyPendingTimersAsync();
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
`zigbee2mqtt/bridge/response/device/ota_update/${type.replace("/downgrade", "")}`,
|
||||
stringify({data: {}, status: "error", error: `Update or check for update already in progress for 'bulb'`}),
|
||||
{},
|
||||
);
|
||||
});
|
||||
|
||||
it("does not crash when read modelID before/after OTA update fails", async () => {
|
||||
devices.bulb.endpoints[0].read.mockRejectedValueOnce("Failed from").mockRejectedValueOnce("Failed to");
|
||||
@@ -749,12 +752,9 @@ describe("Extension: OTAUpdate", () => {
|
||||
});
|
||||
|
||||
it("clear update state on startup", async () => {
|
||||
// @ts-expect-error private
|
||||
const device = controller.zigbee.resolveEntity(devices.bulb_color.ieeeAddr);
|
||||
// @ts-expect-error private
|
||||
controller.state.set(device, {update: {progress: 100, remaining: 10, state: "updating"}});
|
||||
await resetExtension();
|
||||
// @ts-expect-error private
|
||||
expect(controller.state.get(device)).toStrictEqual({update: {state: "available"}});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// biome-ignore assist/source/organizeImports: import mocks first
|
||||
import {afterAll, beforeAll, beforeEach, describe, expect, it, vi} from "vitest";
|
||||
import * as data from "../mocks/data";
|
||||
import {mockLogger} from "../mocks/logger";
|
||||
import {events as mockMQTTEvents, mockMQTTPublishAsync} from "../mocks/mqtt";
|
||||
@@ -6,9 +8,7 @@ import {flushPromises} from "../mocks/utils";
|
||||
import {devices, groups, events as mockZHEvents} from "../mocks/zigbeeHerdsman";
|
||||
|
||||
import stringify from "json-stable-stringify-without-jsonify";
|
||||
|
||||
import {clearGlobalStore} from "zigbee-herdsman-converters";
|
||||
|
||||
import {Controller} from "../../lib/controller";
|
||||
import {loadTopicGetSetRegex} from "../../lib/extension/publish";
|
||||
import * as settings from "../../lib/util/settings";
|
||||
@@ -42,7 +42,6 @@ describe("Extension: Publish", () => {
|
||||
|
||||
beforeEach(() => {
|
||||
data.writeDefaultConfiguration();
|
||||
// @ts-expect-error private
|
||||
controller.state.clear();
|
||||
settings.reRead();
|
||||
loadTopicGetSetRegex();
|
||||
@@ -240,7 +239,7 @@ describe("Extension: Publish", () => {
|
||||
expect(endpoint.command).toHaveBeenCalledWith(
|
||||
"manuSpecificTuya",
|
||||
"dataRequest",
|
||||
{dpValues: [{data: [1], datatype: 1, dp: 2}], seq: expect.any(Number)},
|
||||
{dpValues: [{data: Buffer.from([1]), datatype: 1, dp: 2}], seq: expect.any(Number)},
|
||||
{disableDefaultResponse: true},
|
||||
);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith("zigbee2mqtt/TS0601_switch", stringify({state_l2: "ON"}), {retain: false, qos: 0});
|
||||
@@ -257,19 +256,19 @@ describe("Extension: Publish", () => {
|
||||
expect(endpoint.command).toHaveBeenCalledWith(
|
||||
"manuSpecificTuya",
|
||||
"dataRequest",
|
||||
{dpValues: [{data: [0], datatype: 4, dp: 1}], seq: expect.any(Number)},
|
||||
{dpValues: [{data: Buffer.from([0]), datatype: 4, dp: 1}], seq: expect.any(Number)},
|
||||
{disableDefaultResponse: true},
|
||||
);
|
||||
expect(endpoint.command).toHaveBeenCalledWith(
|
||||
"manuSpecificTuya",
|
||||
"dataRequest",
|
||||
{dpValues: [{data: [1], datatype: 1, dp: 102}], seq: expect.any(Number)},
|
||||
{dpValues: [{data: Buffer.from([1]), datatype: 1, dp: 102}], seq: expect.any(Number)},
|
||||
{disableDefaultResponse: true},
|
||||
);
|
||||
expect(endpoint.command).toHaveBeenCalledWith(
|
||||
"manuSpecificTuya",
|
||||
"dataRequest",
|
||||
{dpValues: [{data: [0], datatype: 1, dp: 101}], seq: expect.any(Number)},
|
||||
{dpValues: [{data: Buffer.from([0]), datatype: 1, dp: 101}], seq: expect.any(Number)},
|
||||
{disableDefaultResponse: true},
|
||||
);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledWith(
|
||||
@@ -426,7 +425,7 @@ describe("Extension: Publish", () => {
|
||||
expect(group.command).toHaveBeenCalledWith(
|
||||
"manuSpecificTuya",
|
||||
"dataRequest",
|
||||
{dpValues: [{data: [1], datatype: 1, dp: 7}], seq: expect.any(Number)},
|
||||
{dpValues: [{data: Buffer.from([1]), datatype: 1, dp: 7}], seq: expect.any(Number)},
|
||||
{disableDefaultResponse: true},
|
||||
);
|
||||
});
|
||||
@@ -1075,7 +1074,7 @@ describe("Extension: Publish", () => {
|
||||
expect(endpoint.command.mock.calls[0]).toEqual([
|
||||
"lightingColorCtrl",
|
||||
"enhancedMoveToHueAndSaturation",
|
||||
{direction: 0, enhancehue: 45510, saturation: 127, transtime: 0},
|
||||
{enhancehue: 45510, saturation: 127, transtime: 0},
|
||||
{},
|
||||
]);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledTimes(1);
|
||||
@@ -1257,11 +1256,8 @@ describe("Extension: Publish", () => {
|
||||
|
||||
it("Home Assistant: should not set state when color temperature is also set and device is already on", async () => {
|
||||
settings.set(["homeassistant"], {enabled: true});
|
||||
// @ts-expect-error private
|
||||
const device = controller.zigbee.resolveEntity(devices.bulb_color.ieeeAddr)!;
|
||||
// @ts-expect-error private
|
||||
controller.state.remove(devices.bulb_color.ieeeAddr);
|
||||
// @ts-expect-error private
|
||||
controller.state.set(device, {state: "ON"});
|
||||
const endpoint = device.zh.getEndpoint(1)!;
|
||||
const payload = {state: "ON", color_temp: 100};
|
||||
@@ -1276,11 +1272,8 @@ describe("Extension: Publish", () => {
|
||||
|
||||
it("Home Assistant: should set state when color temperature is also set and device is off", async () => {
|
||||
settings.set(["homeassistant"], {enabled: true});
|
||||
// @ts-expect-error private
|
||||
const device = controller.zigbee.resolveEntity(devices.bulb_color.ieeeAddr)!;
|
||||
// @ts-expect-error private
|
||||
controller.state.remove(devices.bulb_color.ieeeAddr);
|
||||
// @ts-expect-error private
|
||||
controller.state.set(device, {state: "OFF"});
|
||||
const endpoint = device.zh.getEndpoint(1)!;
|
||||
const payload = {state: "ON", color_temp: 100};
|
||||
@@ -1299,11 +1292,8 @@ describe("Extension: Publish", () => {
|
||||
|
||||
it("Home Assistant: should not set state when color is also set", async () => {
|
||||
settings.set(["homeassistant"], {enabled: true});
|
||||
// @ts-expect-error private
|
||||
const device = controller.zigbee.resolveEntity(devices.bulb_color.ieeeAddr)!;
|
||||
// @ts-expect-error private
|
||||
controller.state.remove(devices.bulb_color.ieeeAddr);
|
||||
// @ts-expect-error private
|
||||
controller.state.set(device, {state: "ON"});
|
||||
const endpoint = device.zh.getEndpoint(1)!;
|
||||
const payload = {state: "ON", color: {x: 0.41, y: 0.25}};
|
||||
@@ -1452,7 +1442,7 @@ describe("Extension: Publish", () => {
|
||||
await mockMQTTEvents.message("zigbee2mqtt/roller_shutter/set", stringify({state: "OPEN"}));
|
||||
await flushPromises();
|
||||
expect(endpoint.command).toHaveBeenCalledTimes(1);
|
||||
expect(endpoint.command).toHaveBeenCalledWith("genLevelCtrl", "moveToLevelWithOnOff", {level: "255", transtime: 0}, {});
|
||||
expect(endpoint.command).toHaveBeenCalledWith("genLevelCtrl", "moveToLevelWithOnOff", {level: 255, transtime: 0}, {});
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledTimes(1);
|
||||
expect(mockMQTTPublishAsync.mock.calls[0][0]).toStrictEqual("zigbee2mqtt/roller_shutter");
|
||||
expect(JSON.parse(mockMQTTPublishAsync.mock.calls[0][1])).toStrictEqual({position: 100});
|
||||
@@ -1468,7 +1458,7 @@ describe("Extension: Publish", () => {
|
||||
expect(endpoint.command).toHaveBeenCalledWith(
|
||||
"manuSpecificTuya",
|
||||
"dataRequest",
|
||||
{dpValues: [{data: [1], datatype: 1, dp: 3}], seq: expect.any(Number)},
|
||||
{dpValues: [{data: Buffer.from([1]), datatype: 1, dp: 3}], seq: expect.any(Number)},
|
||||
{disableDefaultResponse: true},
|
||||
);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledTimes(1);
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// biome-ignore assist/source/organizeImports: import mocks first
|
||||
import {afterAll, beforeAll, beforeEach, describe, expect, it, vi} from "vitest";
|
||||
import * as data from "../mocks/data";
|
||||
import {mockLogger} from "../mocks/logger";
|
||||
import {events as mockMQTTEvents, mockMQTTPublishAsync} from "../mocks/mqtt";
|
||||
@@ -6,7 +8,6 @@ import {flushPromises} from "../mocks/utils";
|
||||
import {devices, events as mockZHEvents} from "../mocks/zigbeeHerdsman";
|
||||
|
||||
import stringify from "json-stable-stringify-without-jsonify";
|
||||
|
||||
import {Controller} from "../../lib/controller";
|
||||
import * as settings from "../../lib/util/settings";
|
||||
|
||||
@@ -24,7 +25,6 @@ describe("Extension: Receive", () => {
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
// @ts-expect-error private
|
||||
controller.state.clear();
|
||||
data.writeDefaultConfiguration();
|
||||
settings.reRead();
|
||||
@@ -183,10 +183,11 @@ describe("Extension: Receive", () => {
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledTimes(0);
|
||||
vi.runOnlyPendingTimers();
|
||||
await flushPromises();
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledTimes(1);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledTimes(2);
|
||||
expect(mockMQTTPublishAsync.mock.calls[0][0]).toStrictEqual("zigbee2mqtt/weather_sensor");
|
||||
expect(JSON.parse(mockMQTTPublishAsync.mock.calls[0][1])).toStrictEqual({temperature: 0.08, humidity: 0.01, pressure: 2});
|
||||
expect(mockMQTTPublishAsync.mock.calls[0][2]).toStrictEqual({qos: 1, retain: false});
|
||||
expect(mockMQTTPublishAsync.mock.calls[1][0]).toStrictEqual("zigbee2mqtt/bridge/health");
|
||||
});
|
||||
|
||||
it("Should debounce and retain messages when set via device_options", async () => {
|
||||
@@ -229,10 +230,11 @@ describe("Extension: Receive", () => {
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledTimes(0);
|
||||
vi.runOnlyPendingTimers();
|
||||
await flushPromises();
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledTimes(1);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledTimes(2);
|
||||
expect(mockMQTTPublishAsync.mock.calls[0][0]).toStrictEqual("zigbee2mqtt/weather_sensor");
|
||||
expect(JSON.parse(mockMQTTPublishAsync.mock.calls[0][1])).toStrictEqual({temperature: 0.08, humidity: 0.01, pressure: 2});
|
||||
expect(mockMQTTPublishAsync.mock.calls[0][2]).toStrictEqual({qos: 1, retain: true});
|
||||
expect(mockMQTTPublishAsync.mock.calls[1][0]).toStrictEqual("zigbee2mqtt/bridge/health");
|
||||
});
|
||||
|
||||
it("Should debounce messages only with the same payload values for provided debounce_ignore keys", async () => {
|
||||
@@ -281,8 +283,9 @@ describe("Extension: Receive", () => {
|
||||
expect(JSON.parse(mockMQTTPublishAsync.mock.calls[0][1])).toStrictEqual({temperature: 0.08, pressure: 2});
|
||||
vi.runOnlyPendingTimers();
|
||||
await flushPromises();
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledTimes(2);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledTimes(3);
|
||||
expect(JSON.parse(mockMQTTPublishAsync.mock.calls[1][1])).toStrictEqual({temperature: 0.07, pressure: 2, humidity: 0.03});
|
||||
expect(mockMQTTPublishAsync.mock.calls[2][0]).toStrictEqual("zigbee2mqtt/bridge/health");
|
||||
});
|
||||
|
||||
it("Should NOT publish old messages from State cache during debouncing", async () => {
|
||||
@@ -322,9 +325,10 @@ describe("Extension: Receive", () => {
|
||||
vi.runOnlyPendingTimers();
|
||||
|
||||
// Test that only one MQTT is sent out and test its values.
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledTimes(1);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledTimes(1 + 1 /* "bridge/health" */);
|
||||
expect(mockMQTTPublishAsync.mock.calls[0][0]).toStrictEqual("zigbee2mqtt/weather_sensor");
|
||||
expect(JSON.parse(mockMQTTPublishAsync.mock.calls[0][1])).toStrictEqual({temperature: 0.08, humidity: 0.01, pressure: 2});
|
||||
expect(mockMQTTPublishAsync.mock.calls[1][0]).toStrictEqual("zigbee2mqtt/bridge/health");
|
||||
|
||||
// Send another Zigbee message...
|
||||
await mockZHEvents.message({
|
||||
@@ -335,7 +339,6 @@ describe("Extension: Receive", () => {
|
||||
type: "attributeReport",
|
||||
linkquality: 10,
|
||||
});
|
||||
// @ts-expect-error private
|
||||
const realDevice = controller.zigbee.resolveEntity(device);
|
||||
|
||||
// Trigger asynchronous event while device is "debouncing" to trigger Message to be sent out from State cache.
|
||||
@@ -343,12 +346,14 @@ describe("Extension: Receive", () => {
|
||||
vi.runOnlyPendingTimers();
|
||||
|
||||
// Total of 3 messages should have triggered.
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledTimes(3);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledTimes(5);
|
||||
|
||||
expect(mockMQTTPublishAsync.mock.calls[1][0]).toStrictEqual("zigbee2mqtt/bridge/health");
|
||||
// Test that message pushed by asynchronous message contains NEW measurement and not old.
|
||||
expect(JSON.parse(mockMQTTPublishAsync.mock.calls[1][1])).toStrictEqual({temperature: 0.09, humidity: 0.01, pressure: 2});
|
||||
// Test that messages after debouncing contains NEW measurement and not old.
|
||||
expect(JSON.parse(mockMQTTPublishAsync.mock.calls[2][1])).toStrictEqual({temperature: 0.09, humidity: 0.01, pressure: 2});
|
||||
// Test that messages after debouncing contains NEW measurement and not old.
|
||||
expect(JSON.parse(mockMQTTPublishAsync.mock.calls[3][1])).toStrictEqual({temperature: 0.09, humidity: 0.01, pressure: 2});
|
||||
expect(mockMQTTPublishAsync.mock.calls[4][0]).toStrictEqual("zigbee2mqtt/bridge/health");
|
||||
});
|
||||
|
||||
it("Should throttle multiple messages from spamming devices", async () => {
|
||||
@@ -439,9 +444,10 @@ describe("Extension: Receive", () => {
|
||||
await mockMQTTEvents.message("zigbee2mqtt/bulb/set", stringify({state: "ON"}));
|
||||
await flushPromises();
|
||||
vi.runOnlyPendingTimers();
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledTimes(2);
|
||||
expect(mockMQTTPublishAsync).toHaveBeenCalledTimes(2 + 1);
|
||||
expect(JSON.parse(mockMQTTPublishAsync.mock.calls[0][1])).toStrictEqual({state: "ON"});
|
||||
expect(JSON.parse(mockMQTTPublishAsync.mock.calls[1][1])).toStrictEqual({state: "ON"});
|
||||
expect(mockMQTTPublishAsync.mock.calls[2][0]).toStrictEqual("zigbee2mqtt/bridge/health");
|
||||
});
|
||||
|
||||
it("Should handle a zigbee message with 1 precision", async () => {
|
||||
@@ -725,7 +731,7 @@ describe("Extension: Receive", () => {
|
||||
it("Should emit DevicesChanged event when a converter announces changed exposes", async () => {
|
||||
const device = devices["BMCT-SLZ"];
|
||||
const data = {deviceMode: 0};
|
||||
const payload = {data, cluster: "boschSpecific", device, endpoint: device.getEndpoint(1), type: "attributeReport", linkquality: 10};
|
||||
const payload = {data, cluster: "boschEnergyDevice", device, endpoint: device.getEndpoint(1), type: "attributeReport", linkquality: 10};
|
||||
await mockZHEvents.message(payload);
|
||||
expect(mockMQTTPublishAsync.mock.calls[0][0]).toStrictEqual("zigbee2mqtt/bridge/devices");
|
||||
});
|
||||
|
||||
+3
-4
@@ -1,15 +1,14 @@
|
||||
// biome-ignore assist/source/organizeImports: import mocks first
|
||||
import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from "vitest";
|
||||
import * as data from "./mocks/data";
|
||||
|
||||
import type {MockInstance} from "vitest";
|
||||
|
||||
import fs from "node:fs";
|
||||
import {platform} from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import {rimrafSync} from "rimraf";
|
||||
import tmp from "tmp";
|
||||
import type {MockInstance} from "vitest";
|
||||
import Transport from "winston-transport";
|
||||
|
||||
import logger from "../lib/util/logger";
|
||||
import * as settings from "../lib/util/settings";
|
||||
|
||||
|
||||
@@ -26,6 +26,9 @@ export const DEFAULT_CONFIGURATION = {
|
||||
"0x18fc2600000d7ae2": {
|
||||
friendly_name: "bosch_radiator",
|
||||
},
|
||||
"0x18fc2600000d7ae3": {
|
||||
friendly_name: "bosch_rm230z",
|
||||
},
|
||||
"0x000b57fffec6a5b2": {
|
||||
retain: true,
|
||||
friendly_name: "bulb",
|
||||
|
||||
@@ -25,6 +25,13 @@ export const mockMQTTConnectAsync = vi.fn(() => ({
|
||||
events[type] = handler;
|
||||
}),
|
||||
stream: {setMaxListeners: vi.fn()},
|
||||
options: {
|
||||
protocolVersion: 5,
|
||||
protocol: "mqtt",
|
||||
host: "localhost",
|
||||
port: 1883,
|
||||
},
|
||||
queue: [],
|
||||
}));
|
||||
|
||||
vi.mock("mqtt", () => ({
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import {vi} from "vitest";
|
||||
import utils from "../../lib/util/utils";
|
||||
|
||||
const spy = vi.spyOn(utils, "sleep");
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import {vi} from "vitest";
|
||||
import type {DefinitionWithExtend} from "zigbee-herdsman-converters";
|
||||
|
||||
export type EventHandler = (...args: unknown[]) => unknown;
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import type {Mock} from "vitest";
|
||||
import type {AdapterTypes} from "zigbee-herdsman";
|
||||
|
||||
import assert from "node:assert";
|
||||
|
||||
import {type Mock, vi} from "vitest";
|
||||
import type {AdapterTypes} from "zigbee-herdsman";
|
||||
import {Zcl} from "zigbee-herdsman";
|
||||
import {InterviewState} from "zigbee-herdsman/dist/controller/model/device";
|
||||
|
||||
import type {BindingTableEntry, LQITableEntry, RoutingTableEntry} from "zigbee-herdsman/dist/zspec/zdo/definition/tstypes";
|
||||
import {DEFAULT_BIND_GROUP_ID} from "../../lib/util/utils";
|
||||
import type {EventHandler} from "./utils";
|
||||
|
||||
type ZHConfiguredReporting = {
|
||||
@@ -105,6 +104,7 @@ export class Endpoint {
|
||||
unbind: Mock;
|
||||
save: Mock;
|
||||
configureReporting: Mock;
|
||||
readReportingConfig: Mock;
|
||||
meta: Record<string, unknown>;
|
||||
binds: ZHBind[];
|
||||
profileID: number | undefined;
|
||||
@@ -139,6 +139,7 @@ export class Endpoint {
|
||||
this.unbind = vi.fn();
|
||||
this.save = vi.fn();
|
||||
this.configureReporting = vi.fn();
|
||||
this.readReportingConfig = vi.fn();
|
||||
this.meta = meta;
|
||||
this.binds = binds;
|
||||
this.profileID = profileID;
|
||||
@@ -219,6 +220,7 @@ export class Endpoint {
|
||||
this.unbind.mockClear();
|
||||
this.save.mockClear();
|
||||
this.configureReporting.mockClear();
|
||||
this.readReportingConfig.mockClear();
|
||||
this.addToGroup.mockClear();
|
||||
this.removeFromGroup.mockClear();
|
||||
this.getClusterAttributeValue.mockClear();
|
||||
@@ -248,8 +250,10 @@ export class Device {
|
||||
lastSeen: number | undefined;
|
||||
isDeleted: boolean;
|
||||
linkquality?: number;
|
||||
lqi: Mock;
|
||||
routingTable: Mock;
|
||||
lqi: Mock<() => Promise<LQITableEntry[]>>;
|
||||
routingTable: Mock<() => Promise<RoutingTableEntry[]>>;
|
||||
bindingTable: Mock<() => Promise<BindingTableEntry[]>>;
|
||||
clearAllBindings: Mock<() => Promise<void>>;
|
||||
|
||||
constructor(
|
||||
type: string,
|
||||
@@ -286,8 +290,10 @@ export class Device {
|
||||
this.manufacturerName = manufacturerName;
|
||||
this.lastSeen = 1000;
|
||||
this.isDeleted = false;
|
||||
this.lqi = vi.fn(() => ({neighbors: []}));
|
||||
this.routingTable = vi.fn(() => ({table: []}));
|
||||
this.lqi = vi.fn(() => Promise.resolve([] as LQITableEntry[]));
|
||||
this.routingTable = vi.fn(() => Promise.resolve([] as RoutingTableEntry[]));
|
||||
this.bindingTable = vi.fn(() => Promise.resolve([] as BindingTableEntry[]));
|
||||
this.clearAllBindings = vi.fn(() => {});
|
||||
}
|
||||
|
||||
getEndpoint(ID: number): Endpoint | undefined {
|
||||
@@ -303,6 +309,8 @@ export class Device {
|
||||
this.save.mockClear();
|
||||
this.lqi.mockClear();
|
||||
this.routingTable.mockClear();
|
||||
this.bindingTable.mockClear();
|
||||
this.clearAllBindings.mockClear();
|
||||
this.meta = {};
|
||||
|
||||
for (const ep of this.endpoints) {
|
||||
@@ -506,7 +514,7 @@ export const groups = {
|
||||
thermostat_group: new Group(12, [TS0601_thermostat.endpoints[0]]),
|
||||
group_with_switch: new Group(14, [ZNCZ02LM.endpoints[0], bulb_2.endpoints[0]]),
|
||||
gledopto_group: new Group(21, [GLEDOPTO_2ID.endpoints[3]]),
|
||||
default_bind_group: new Group(901, []),
|
||||
default_bind_group: new Group(DEFAULT_BIND_GROUP_ID, []),
|
||||
ha_discovery_group: new Group(9, [bulb_color_2.endpoints[0], bulb_2.endpoints[0], QBKG03LM.endpoints[2]]),
|
||||
hue_twilight_group: new Group(19, [hue_twilight.endpoints[1]]),
|
||||
};
|
||||
@@ -1129,6 +1137,20 @@ export const devices = {
|
||||
"DC Source",
|
||||
"FanBee1",
|
||||
),
|
||||
BTH_RM230Z: new Device(
|
||||
"Router",
|
||||
"0x18fc2600000d7ae3",
|
||||
35902,
|
||||
4617,
|
||||
[new Endpoint(1, [0, 3, 513, 516, 1029, 2821], [10, 25], "0x18fc2600000d7ae3")],
|
||||
InterviewState.Successful,
|
||||
"Mains (single phase)",
|
||||
"RBSH-RTH0-ZB-EU",
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
CUSTOM_CLUSTER_BTHRA,
|
||||
),
|
||||
};
|
||||
|
||||
export const mockController = {
|
||||
@@ -1137,10 +1159,7 @@ export const mockController = {
|
||||
},
|
||||
start: vi.fn((): Promise<AdapterTypes.StartResult> => Promise.resolve("reset")),
|
||||
stop: vi.fn(),
|
||||
touchlinkIdentify: vi.fn(),
|
||||
touchlinkScan: vi.fn(),
|
||||
touchlinkFactoryReset: vi.fn(),
|
||||
touchlinkFactoryResetFirst: vi.fn(),
|
||||
touchlink: {identify: vi.fn(), scan: vi.fn(), factoryReset: vi.fn(), factoryResetFirst: vi.fn()},
|
||||
addInstallCode: vi.fn(),
|
||||
permitJoin: vi.fn(),
|
||||
getPermitJoin: vi.fn((): boolean => false),
|
||||
@@ -1196,6 +1215,9 @@ export const mockController = {
|
||||
groups[`group_${groupID}` as keyof typeof groups] = group;
|
||||
return group;
|
||||
}),
|
||||
sendRaw: vi.fn(async (/*rawPayload: RawPayload, customClusters: CustomClusters = {}*/) =>
|
||||
Promise.resolve([0x00, {nwkAddress: 0x1234, eui64: "", startIndex: 0, assocDevList: []}]),
|
||||
),
|
||||
};
|
||||
|
||||
vi.mock("zigbee-herdsman", async (importOriginal) => ({
|
||||
|
||||
+98
-10
@@ -1,11 +1,11 @@
|
||||
// biome-ignore assist/source/organizeImports: import mocks first
|
||||
import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from "vitest";
|
||||
import * as data from "./mocks/data";
|
||||
|
||||
import {rmSync, writeFileSync} from "node:fs";
|
||||
import {join} from "node:path";
|
||||
import type {IncomingMessage, OutgoingHttpHeader, OutgoingHttpHeaders, RequestListener, Server, ServerResponse} from "node:http";
|
||||
|
||||
import {rmSync} from "node:fs";
|
||||
|
||||
import type {findAllDevices} from "zigbee-herdsman/dist/adapter/adapterDiscovery";
|
||||
|
||||
import {onboard} from "../lib/util/onboarding";
|
||||
import * as settings from "../lib/util/settings";
|
||||
|
||||
@@ -188,10 +188,10 @@ describe("Onboarding", () => {
|
||||
expectWriteMinimal: boolean,
|
||||
expectFailure: boolean,
|
||||
): Promise<[getHtml: string, postHtml: string]> => {
|
||||
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
|
||||
// biome-ignore lint/suspicious/noExplicitAny: ignore
|
||||
const reqDataListener = vi.fn<(chunk: any) => void>();
|
||||
const reqEndListener = vi.fn<() => void>();
|
||||
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
|
||||
// biome-ignore lint/suspicious/noExplicitAny: ignore
|
||||
const resEnd = vi.fn<(chunk: any | (() => void), cb?: () => void) => ServerResponse<IncomingMessage>>(
|
||||
// @ts-expect-error return not used
|
||||
(chunk, cb) => {
|
||||
@@ -293,13 +293,13 @@ describe("Onboarding", () => {
|
||||
}
|
||||
|
||||
const serverUrl = new URL(process.env.Z2M_ONBOARD_URL ?? "http://0.0.0.0:8080");
|
||||
expect(mockHttpListen).toHaveBeenCalledWith(Number.parseInt(serverUrl.port), serverUrl.hostname, expect.any(Function));
|
||||
expect(mockHttpListen).toHaveBeenCalledWith(Number.parseInt(serverUrl.port, 10), serverUrl.hostname, expect.any(Function));
|
||||
|
||||
return [resEnd.mock.calls[0][0], resEnd.mock.calls[1][0]];
|
||||
};
|
||||
|
||||
const runFailure = async (): Promise<string> => {
|
||||
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
|
||||
// biome-ignore lint/suspicious/noExplicitAny: ignore
|
||||
const resEnd = vi.fn<(chunk: any | (() => void), cb?: () => void) => ServerResponse<IncomingMessage>>(
|
||||
// @ts-expect-error return not used
|
||||
(chunk, cb) => {
|
||||
@@ -351,7 +351,7 @@ describe("Onboarding", () => {
|
||||
expect(resEnd).toHaveBeenCalledTimes(2);
|
||||
|
||||
const serverUrl = new URL(process.env.Z2M_ONBOARD_URL ?? "http://0.0.0.0:8080");
|
||||
expect(mockHttpListen).toHaveBeenCalledWith(Number.parseInt(serverUrl.port), serverUrl.hostname, expect.any(Function));
|
||||
expect(mockHttpListen).toHaveBeenCalledWith(Number.parseInt(serverUrl.port, 10), serverUrl.hostname, expect.any(Function));
|
||||
|
||||
return resEnd.mock.calls[0][0];
|
||||
};
|
||||
@@ -753,7 +753,13 @@ describe("Onboarding", () => {
|
||||
});
|
||||
|
||||
it("handles validation failure", async () => {
|
||||
settings.set(["serial", "adapter"], "emberz");
|
||||
const reReadSpy = vi.spyOn(settings, "reRead");
|
||||
|
||||
// set after onboarding server is done to reach bottom code path
|
||||
reReadSpy.mockImplementationOnce(() => {
|
||||
settings.set(["serial", "adapter"], "emberz");
|
||||
settings.reRead();
|
||||
});
|
||||
|
||||
let p;
|
||||
const getHtml = await new Promise<string>((resolve, reject) => {
|
||||
@@ -770,6 +776,88 @@ describe("Onboarding", () => {
|
||||
|
||||
await expect(p).resolves.toStrictEqual(false);
|
||||
expect(getHtml).toContain("adapter must be equal to one of the allowed values");
|
||||
|
||||
reReadSpy.mockRestore();
|
||||
});
|
||||
|
||||
it("handles non-required validation failure before applying envs", async () => {
|
||||
settings.set(["serial"], "/dev/ttyUSB0");
|
||||
|
||||
let p;
|
||||
const getHtml = await new Promise<string>((resolve, reject) => {
|
||||
mockHttpOnListen.mockImplementationOnce(async () => {
|
||||
try {
|
||||
resolve(await runFailure());
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
|
||||
p = onboard();
|
||||
});
|
||||
|
||||
await expect(p).resolves.toStrictEqual(false);
|
||||
expect(getHtml).toContain("serial must be object");
|
||||
});
|
||||
|
||||
it("handles invalid yaml file", async () => {
|
||||
settings.testing.clear();
|
||||
|
||||
const configFile = join(data.mockDir, "configuration.yaml");
|
||||
|
||||
writeFileSync(
|
||||
configFile,
|
||||
`
|
||||
good: 9
|
||||
\t wrong
|
||||
`,
|
||||
);
|
||||
|
||||
let p;
|
||||
const getHtml = await new Promise<string>((resolve, reject) => {
|
||||
mockHttpOnListen.mockImplementationOnce(async () => {
|
||||
try {
|
||||
resolve(await runFailure());
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
|
||||
p = onboard();
|
||||
});
|
||||
|
||||
await expect(p).resolves.toStrictEqual(false);
|
||||
expect(getHtml).toContain("Your configuration file");
|
||||
expect(getHtml).toContain("is invalid");
|
||||
|
||||
data.removeConfiguration();
|
||||
});
|
||||
|
||||
it("handles error while loading yaml file", async () => {
|
||||
settings.testing.clear();
|
||||
|
||||
const configFile = join(data.mockDir, "configuration.yaml");
|
||||
|
||||
writeFileSync(configFile, "badfile");
|
||||
|
||||
let p;
|
||||
const getHtml = await new Promise<string>((resolve, reject) => {
|
||||
mockHttpOnListen.mockImplementationOnce(async () => {
|
||||
try {
|
||||
resolve(await runFailure());
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
|
||||
p = onboard();
|
||||
});
|
||||
|
||||
await expect(p).resolves.toStrictEqual(false);
|
||||
expect(getHtml).toContain("AssertionError");
|
||||
expect(getHtml).toContain("expected to be an object");
|
||||
|
||||
data.removeConfiguration();
|
||||
});
|
||||
|
||||
it("handles creating data path", async () => {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// biome-ignore assist/source/organizeImports: import mocks first
|
||||
import {afterAll, beforeAll, beforeEach, describe, expect, it, vi} from "vitest";
|
||||
import {mockLogger} from "./mocks/logger";
|
||||
|
||||
import {initSdNotify} from "../lib/util/sd-notify";
|
||||
|
||||
+86
-58
@@ -1,8 +1,8 @@
|
||||
// side-effect ensures using mock paths
|
||||
import {beforeEach, describe, expect, it} from "vitest";
|
||||
import "./mocks/data";
|
||||
|
||||
import fs from "node:fs";
|
||||
|
||||
import yaml from "js-yaml";
|
||||
import objectAssignDeep from "object-assign-deep";
|
||||
|
||||
@@ -165,6 +165,43 @@ describe("Settings", () => {
|
||||
writeAndCheck();
|
||||
});
|
||||
|
||||
it("Should apply Home Assistant environment variables", () => {
|
||||
// should be kept in sync with envs in https://github.com/zigbee2mqtt/hassio-zigbee2mqtt/blob/master/common/rootfs/docker-entrypoint.sh
|
||||
process.env.ZIGBEE2MQTT_CONFIG_FRONTEND_ENABLED = "true";
|
||||
process.env.ZIGBEE2MQTT_CONFIG_FRONTEND_PORT = "8099";
|
||||
process.env.ZIGBEE2MQTT_CONFIG_HOMEASSISTANT_ENABLED = "true";
|
||||
process.env.ZIGBEE2MQTT_CONFIG_SERIAL_PORT =
|
||||
"/dev/serial/by-id/usb-ITead_Sonoff_Zigbee_3.0_USB_Dongle_Plus_48be7a7468d8ed11bfea786ff2c613ac-if00-port0";
|
||||
process.env.ZIGBEE2MQTT_CONFIG_MQTT_SERVER = "mqtt://core-mosquitto:1883";
|
||||
process.env.ZIGBEE2MQTT_CONFIG_MQTT_USER = "addons";
|
||||
process.env.ZIGBEE2MQTT_CONFIG_MQTT_PASSWORD = "7RbR4NBSskS8TKG4ugzdRilXw6TPQ4NKFs259j2DxeultOFtl5JwciNZFd6feT5o";
|
||||
|
||||
write(configurationFile, {});
|
||||
|
||||
// @ts-expect-error workaround
|
||||
const expected = objectAssignDeep.noMutate({}, settings.testing.defaults);
|
||||
expected.frontend.enabled = true;
|
||||
expected.frontend.port = 8099;
|
||||
expected.homeassistant.enabled = true;
|
||||
expected.serial.port = "/dev/serial/by-id/usb-ITead_Sonoff_Zigbee_3.0_USB_Dongle_Plus_48be7a7468d8ed11bfea786ff2c613ac-if00-port0";
|
||||
expected.mqtt.server = "mqtt://core-mosquitto:1883";
|
||||
expected.mqtt.user = "addons";
|
||||
expected.mqtt.password = "7RbR4NBSskS8TKG4ugzdRilXw6TPQ4NKFs259j2DxeultOFtl5JwciNZFd6feT5o";
|
||||
expected.devices = {};
|
||||
expected.groups = {};
|
||||
|
||||
const writeAndCheck = (): void => {
|
||||
expect(settings.write()); // trigger writing of ENVs
|
||||
expect(settings.validate()).toStrictEqual([]);
|
||||
expect(settings.get()).toStrictEqual(expected);
|
||||
};
|
||||
|
||||
// Write trice to ensure there are no side effects.
|
||||
writeAndCheck();
|
||||
writeAndCheck();
|
||||
writeAndCheck();
|
||||
});
|
||||
|
||||
it("Should write environment variables as overrides to configuration.yaml, not in the ref file", () => {
|
||||
write(secretFile, {password: "password-in-secret-file"}, false);
|
||||
write(configurationFile, {mqtt: {password: "!secret password", server: "server"}});
|
||||
@@ -275,6 +312,9 @@ describe("Settings", () => {
|
||||
base_topic: "zigbee2mqtt",
|
||||
include_device_information: false,
|
||||
maximum_packet_size: 1048576,
|
||||
keepalive: 60,
|
||||
reject_unauthorized: true,
|
||||
version: 4,
|
||||
force_disable_retain: false,
|
||||
password: "mysecretpassword",
|
||||
server: "my.mqtt.server",
|
||||
@@ -320,6 +360,9 @@ describe("Settings", () => {
|
||||
base_topic: "zigbee2mqtt",
|
||||
include_device_information: false,
|
||||
maximum_packet_size: 1048576,
|
||||
keepalive: 60,
|
||||
reject_unauthorized: true,
|
||||
version: 4,
|
||||
force_disable_retain: false,
|
||||
password: "mysecretpassword",
|
||||
server: "my.mqtt.server",
|
||||
@@ -506,7 +549,7 @@ describe("Settings", () => {
|
||||
it("Should read groups", () => {
|
||||
const content = {
|
||||
groups: {
|
||||
1: {
|
||||
"1": {
|
||||
friendly_name: "123",
|
||||
},
|
||||
},
|
||||
@@ -515,18 +558,17 @@ describe("Settings", () => {
|
||||
write(configurationFile, content);
|
||||
|
||||
const group = settings.getGroup("1");
|
||||
const expected = {
|
||||
|
||||
expect(group).toStrictEqual({
|
||||
ID: 1,
|
||||
friendly_name: "123",
|
||||
};
|
||||
|
||||
expect(group).toStrictEqual(expected);
|
||||
});
|
||||
});
|
||||
|
||||
it("Throw if removing non-existing group", () => {
|
||||
const content = {
|
||||
groups: {
|
||||
1: {
|
||||
"1": {
|
||||
friendly_name: "123",
|
||||
},
|
||||
},
|
||||
@@ -543,7 +585,7 @@ describe("Settings", () => {
|
||||
};
|
||||
|
||||
const contentGroups = {
|
||||
1: {
|
||||
"1": {
|
||||
friendly_name: "123",
|
||||
},
|
||||
};
|
||||
@@ -552,12 +594,11 @@ describe("Settings", () => {
|
||||
write(groupsFile, contentGroups);
|
||||
|
||||
const group = settings.getGroup("1");
|
||||
const expected = {
|
||||
|
||||
expect(group).toStrictEqual({
|
||||
ID: 1,
|
||||
friendly_name: "123",
|
||||
};
|
||||
|
||||
expect(group).toStrictEqual(expected);
|
||||
});
|
||||
});
|
||||
|
||||
it("Combine everything! groups and devices from separate file :)", () => {
|
||||
@@ -567,9 +608,8 @@ describe("Settings", () => {
|
||||
};
|
||||
|
||||
const contentGroups = {
|
||||
1: {
|
||||
"1": {
|
||||
friendly_name: "123",
|
||||
devices: [],
|
||||
},
|
||||
};
|
||||
write(configurationFile, contentConfiguration);
|
||||
@@ -586,44 +626,48 @@ describe("Settings", () => {
|
||||
|
||||
expect(read(configurationFile)).toStrictEqual(expectedConfiguration);
|
||||
|
||||
const expectedDevice = {
|
||||
expect(read(devicesFile)).toStrictEqual({
|
||||
"0x1234": {
|
||||
friendly_name: "0x1234",
|
||||
},
|
||||
};
|
||||
|
||||
expect(read(devicesFile)).toStrictEqual(expectedDevice);
|
||||
});
|
||||
|
||||
const group = settings.getGroup("1");
|
||||
const expectedGroup = {
|
||||
|
||||
expect(group).toStrictEqual({
|
||||
ID: 1,
|
||||
friendly_name: "123",
|
||||
devices: [],
|
||||
};
|
||||
|
||||
expect(group).toStrictEqual(expectedGroup);
|
||||
});
|
||||
|
||||
expect(read(configurationFile)).toStrictEqual(expectedConfiguration);
|
||||
|
||||
const expectedDevice2 = {
|
||||
expect(settings.getDevice("0x1234")).toStrictEqual({
|
||||
ID: "0x1234",
|
||||
friendly_name: "0x1234",
|
||||
};
|
||||
|
||||
expect(settings.getDevice("0x1234")).toStrictEqual(expectedDevice2);
|
||||
});
|
||||
});
|
||||
|
||||
it("Should add groups", () => {
|
||||
write(configurationFile, {});
|
||||
|
||||
settings.addGroup("test123");
|
||||
const expected = {
|
||||
1: {
|
||||
|
||||
expect(settings.get().groups).toStrictEqual({
|
||||
"1": {
|
||||
friendly_name: "test123",
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
expect(settings.get().groups).toStrictEqual(expected);
|
||||
settings.addGroup("test456", "");
|
||||
|
||||
expect(settings.get().groups).toStrictEqual({
|
||||
"1": {
|
||||
friendly_name: "test123",
|
||||
},
|
||||
"2": {
|
||||
friendly_name: "test456",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("Should allow username without password", () => {
|
||||
@@ -637,6 +681,9 @@ describe("Settings", () => {
|
||||
base_topic: "zigbee2mqtt",
|
||||
include_device_information: false,
|
||||
maximum_packet_size: 1048576,
|
||||
keepalive: 60,
|
||||
reject_unauthorized: true,
|
||||
version: 4,
|
||||
force_disable_retain: false,
|
||||
server: "my.mqtt.server",
|
||||
user: "myusername",
|
||||
@@ -650,7 +697,7 @@ describe("Settings", () => {
|
||||
|
||||
settings.addGroup("test123", "123");
|
||||
const expected = {
|
||||
123: {
|
||||
"123": {
|
||||
friendly_name: "test123",
|
||||
},
|
||||
};
|
||||
@@ -682,7 +729,7 @@ describe("Settings", () => {
|
||||
settings.addGroup("test123");
|
||||
}).toThrow(`friendly_name 'test123' is already in use`);
|
||||
const expected = {
|
||||
1: {
|
||||
"1": {
|
||||
friendly_name: "test123",
|
||||
},
|
||||
};
|
||||
@@ -698,7 +745,7 @@ describe("Settings", () => {
|
||||
settings.addGroup("test_id_123", "123");
|
||||
}).toThrow(new Error("Group ID '123' is already in use"));
|
||||
const expected = {
|
||||
123: {
|
||||
"123": {
|
||||
friendly_name: "test123",
|
||||
},
|
||||
};
|
||||
@@ -800,25 +847,6 @@ describe("Settings", () => {
|
||||
expect(settings.get().blocklist).toStrictEqual(["0x123", "0x1234"]);
|
||||
});
|
||||
|
||||
it("Should throw error when yaml file is invalid", () => {
|
||||
fs.writeFileSync(
|
||||
configurationFile,
|
||||
`
|
||||
good: 9
|
||||
\t wrong
|
||||
`,
|
||||
);
|
||||
|
||||
settings.testing.clear();
|
||||
const error = `Your YAML file: '${configurationFile}' is invalid (use https://jsonformatter.org/yaml-validator to find and fix the issue)`;
|
||||
expect(settings.validate()).toEqual(expect.arrayContaining([error]));
|
||||
});
|
||||
|
||||
it("Should throw error when yaml file does not exist", () => {
|
||||
settings.testing.clear();
|
||||
expect(settings.validate()[0]).toContain("ENOENT: no such file or directory, open ");
|
||||
});
|
||||
|
||||
it("Configuration shouldnt be valid when invalid QOS value is used", () => {
|
||||
write(configurationFile, {
|
||||
...minimalConfig,
|
||||
@@ -827,7 +855,7 @@ describe("Settings", () => {
|
||||
|
||||
settings.reRead();
|
||||
|
||||
const error = `QOS for 'myname' not valid, should be 0, 1 or 2 got 3`;
|
||||
const error = "devices/0x0017880104e45519/qos must be equal to one of the allowed values";
|
||||
expect(settings.validate()).toEqual(expect.arrayContaining([error]));
|
||||
});
|
||||
|
||||
@@ -835,7 +863,7 @@ describe("Settings", () => {
|
||||
write(configurationFile, {
|
||||
...minimalConfig,
|
||||
devices: {"0x0017880104e45519": {friendly_name: "myname", retain: false}},
|
||||
groups: {1: {friendly_name: "myname", retain: false}},
|
||||
groups: {"1": {friendly_name: "myname", retain: false}},
|
||||
});
|
||||
|
||||
settings.reRead();
|
||||
@@ -924,7 +952,7 @@ describe("Settings", () => {
|
||||
expect(settings.validate()).toEqual(expect.arrayContaining([error]));
|
||||
});
|
||||
|
||||
it("Configuration shouldnt be valid when duplicate friendly_name are used", async () => {
|
||||
it("Configuration shouldnt be valid when duplicate friendly_name are used", () => {
|
||||
write(configurationFile, {
|
||||
devices: {
|
||||
"0x0017880104e45519": {friendly_name: "myname", retain: false},
|
||||
@@ -939,7 +967,7 @@ describe("Settings", () => {
|
||||
}).toThrowError(`friendly_name 'myname' is already in use`);
|
||||
});
|
||||
|
||||
it("Should throw when removing device which doesnt exist", async () => {
|
||||
it("Should throw when removing device which doesnt exist", () => {
|
||||
write(configurationFile, {
|
||||
devices: {
|
||||
"0x0017880104e45519": {friendly_name: "myname", retain: false},
|
||||
@@ -1019,6 +1047,6 @@ describe("Settings", () => {
|
||||
write(configurationFile, {frontend: {enabled: true}});
|
||||
|
||||
settings.reRead();
|
||||
expect(settings.get().frontend).toStrictEqual({enabled: true, package: "zigbee2mqtt-frontend", port: 8080, base_url: "/"});
|
||||
expect(settings.get().frontend).toStrictEqual({enabled: true, package: "zigbee2mqtt-windfront", port: 8080, base_url: "/"});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
// side-effect ensures using mock paths
|
||||
// biome-ignore assist/source/organizeImports: import mocks first
|
||||
import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it} from "vitest";
|
||||
import * as data from "./mocks/data";
|
||||
|
||||
import {existsSync, readFileSync, rmSync} from "node:fs";
|
||||
|
||||
import objectAssignDeep from "object-assign-deep";
|
||||
|
||||
import mockedData from "../lib/util/data";
|
||||
import * as settings from "../lib/util/settings";
|
||||
import * as settingsMigration from "../lib/util/settingsMigration";
|
||||
|
||||
+1
-2
@@ -2,9 +2,8 @@
|
||||
"extends": "../tsconfig",
|
||||
"include": ["./**/*", "vitest.config.mts"],
|
||||
"compilerOptions": {
|
||||
"types": ["vitest/globals"],
|
||||
"rootDir": "..",
|
||||
"noEmit": true
|
||||
},
|
||||
"references": [{ "path": ".." }]
|
||||
"references": [{"path": ".."}]
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
import {exec} from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import {describe, expect, it, vi} from "vitest";
|
||||
import utils, {assertString} from "../lib/util/utils";
|
||||
|
||||
// keep the implementations, just spy
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import {defineConfig} from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [],
|
||||
test: {
|
||||
globals: true,
|
||||
onConsoleLog(_log: string, _type: "stdout" | "stderr"): boolean | undefined {
|
||||
return false;
|
||||
},
|
||||
|
||||
+2
-2
@@ -3,8 +3,8 @@
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"module": "NodeNext",
|
||||
"esModuleInterop": true,
|
||||
"target": "ES2022",
|
||||
"lib": ["ES2022"],
|
||||
"target": "esnext",
|
||||
"lib": ["esnext"],
|
||||
"strict": true,
|
||||
"noImplicitAny": true,
|
||||
"noImplicitThis": true,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user