zigbee-herdsman 6.0.2 → 6.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (252) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/package.json +9 -3
  3. package/.github/ISSUE_TEMPLATE/config.yml +0 -5
  4. package/.github/dependabot.yml +0 -22
  5. package/.github/workflows/ci.yml +0 -69
  6. package/.github/workflows/release-please.yml +0 -18
  7. package/.github/workflows/stale.yml +0 -20
  8. package/.github/workflows/typedoc.yaml +0 -47
  9. package/.release-please-manifest.json +0 -3
  10. package/.vscode/extensions.json +0 -3
  11. package/.vscode/settings.json +0 -11
  12. package/biome.json +0 -98
  13. package/examples/join-and-log.js +0 -24
  14. package/release-please-config.json +0 -9
  15. package/src/adapter/adapter.ts +0 -189
  16. package/src/adapter/adapterDiscovery.ts +0 -666
  17. package/src/adapter/const.ts +0 -12
  18. package/src/adapter/deconz/adapter/deconzAdapter.ts +0 -877
  19. package/src/adapter/deconz/driver/constants.ts +0 -246
  20. package/src/adapter/deconz/driver/driver.ts +0 -1540
  21. package/src/adapter/deconz/driver/frame.ts +0 -11
  22. package/src/adapter/deconz/driver/frameParser.ts +0 -753
  23. package/src/adapter/deconz/driver/parser.ts +0 -45
  24. package/src/adapter/deconz/driver/writer.ts +0 -22
  25. package/src/adapter/deconz/types.d.ts +0 -13
  26. package/src/adapter/ember/adapter/emberAdapter.ts +0 -2265
  27. package/src/adapter/ember/adapter/endpoints.ts +0 -86
  28. package/src/adapter/ember/adapter/oneWaitress.ts +0 -324
  29. package/src/adapter/ember/adapter/tokensManager.ts +0 -782
  30. package/src/adapter/ember/consts.ts +0 -178
  31. package/src/adapter/ember/enums.ts +0 -1746
  32. package/src/adapter/ember/ezsp/buffalo.ts +0 -1392
  33. package/src/adapter/ember/ezsp/consts.ts +0 -148
  34. package/src/adapter/ember/ezsp/enums.ts +0 -1114
  35. package/src/adapter/ember/ezsp/ezsp.ts +0 -9061
  36. package/src/adapter/ember/ezspError.ts +0 -10
  37. package/src/adapter/ember/types.ts +0 -866
  38. package/src/adapter/ember/uart/ash.ts +0 -1960
  39. package/src/adapter/ember/uart/consts.ts +0 -109
  40. package/src/adapter/ember/uart/enums.ts +0 -192
  41. package/src/adapter/ember/uart/parser.ts +0 -48
  42. package/src/adapter/ember/uart/queues.ts +0 -247
  43. package/src/adapter/ember/uart/writer.ts +0 -53
  44. package/src/adapter/ember/utils/initters.ts +0 -58
  45. package/src/adapter/ember/utils/math.ts +0 -73
  46. package/src/adapter/events.ts +0 -21
  47. package/src/adapter/ezsp/adapter/backup.ts +0 -109
  48. package/src/adapter/ezsp/adapter/ezspAdapter.ts +0 -614
  49. package/src/adapter/ezsp/driver/commands.ts +0 -2497
  50. package/src/adapter/ezsp/driver/consts.ts +0 -11
  51. package/src/adapter/ezsp/driver/driver.ts +0 -1002
  52. package/src/adapter/ezsp/driver/ezsp.ts +0 -802
  53. package/src/adapter/ezsp/driver/frame.ts +0 -101
  54. package/src/adapter/ezsp/driver/index.ts +0 -4
  55. package/src/adapter/ezsp/driver/multicast.ts +0 -78
  56. package/src/adapter/ezsp/driver/parser.ts +0 -81
  57. package/src/adapter/ezsp/driver/types/basic.ts +0 -201
  58. package/src/adapter/ezsp/driver/types/index.ts +0 -239
  59. package/src/adapter/ezsp/driver/types/named.ts +0 -2330
  60. package/src/adapter/ezsp/driver/types/struct.ts +0 -844
  61. package/src/adapter/ezsp/driver/uart.ts +0 -460
  62. package/src/adapter/ezsp/driver/utils/crc16ccitt.ts +0 -44
  63. package/src/adapter/ezsp/driver/utils/index.ts +0 -32
  64. package/src/adapter/ezsp/driver/writer.ts +0 -64
  65. package/src/adapter/index.ts +0 -3
  66. package/src/adapter/serialPort.ts +0 -58
  67. package/src/adapter/socketPortUtils.ts +0 -16
  68. package/src/adapter/tstype.ts +0 -78
  69. package/src/adapter/z-stack/adapter/adapter-backup.ts +0 -519
  70. package/src/adapter/z-stack/adapter/adapter-nv-memory.ts +0 -457
  71. package/src/adapter/z-stack/adapter/endpoints.ts +0 -57
  72. package/src/adapter/z-stack/adapter/manager.ts +0 -543
  73. package/src/adapter/z-stack/adapter/tstype.ts +0 -6
  74. package/src/adapter/z-stack/adapter/zStackAdapter.ts +0 -1190
  75. package/src/adapter/z-stack/constants/af.ts +0 -27
  76. package/src/adapter/z-stack/constants/common.ts +0 -285
  77. package/src/adapter/z-stack/constants/dbg.ts +0 -23
  78. package/src/adapter/z-stack/constants/index.ts +0 -11
  79. package/src/adapter/z-stack/constants/mac.ts +0 -128
  80. package/src/adapter/z-stack/constants/sapi.ts +0 -25
  81. package/src/adapter/z-stack/constants/sys.ts +0 -72
  82. package/src/adapter/z-stack/constants/util.ts +0 -82
  83. package/src/adapter/z-stack/constants/utils.ts +0 -14
  84. package/src/adapter/z-stack/constants/zdo.ts +0 -103
  85. package/src/adapter/z-stack/models/startup-options.ts +0 -13
  86. package/src/adapter/z-stack/structs/entries/address-manager-entry.ts +0 -44
  87. package/src/adapter/z-stack/structs/entries/address-manager-table.ts +0 -19
  88. package/src/adapter/z-stack/structs/entries/aps-link-key-data-entry.ts +0 -12
  89. package/src/adapter/z-stack/structs/entries/aps-link-key-data-table.ts +0 -21
  90. package/src/adapter/z-stack/structs/entries/aps-tc-link-key-entry.ts +0 -19
  91. package/src/adapter/z-stack/structs/entries/aps-tc-link-key-table.ts +0 -21
  92. package/src/adapter/z-stack/structs/entries/channel-list.ts +0 -8
  93. package/src/adapter/z-stack/structs/entries/has-configured.ts +0 -16
  94. package/src/adapter/z-stack/structs/entries/index.ts +0 -16
  95. package/src/adapter/z-stack/structs/entries/nib.ts +0 -66
  96. package/src/adapter/z-stack/structs/entries/nwk-key-descriptor.ts +0 -15
  97. package/src/adapter/z-stack/structs/entries/nwk-key.ts +0 -13
  98. package/src/adapter/z-stack/structs/entries/nwk-pan-id.ts +0 -8
  99. package/src/adapter/z-stack/structs/entries/nwk-sec-material-descriptor-entry.ts +0 -20
  100. package/src/adapter/z-stack/structs/entries/nwk-sec-material-descriptor-table.ts +0 -19
  101. package/src/adapter/z-stack/structs/entries/security-manager-entry.ts +0 -33
  102. package/src/adapter/z-stack/structs/entries/security-manager-table.ts +0 -22
  103. package/src/adapter/z-stack/structs/index.ts +0 -4
  104. package/src/adapter/z-stack/structs/serializable-memory-object.ts +0 -14
  105. package/src/adapter/z-stack/structs/struct.ts +0 -367
  106. package/src/adapter/z-stack/structs/table.ts +0 -198
  107. package/src/adapter/z-stack/unpi/constants.ts +0 -33
  108. package/src/adapter/z-stack/unpi/frame.ts +0 -62
  109. package/src/adapter/z-stack/unpi/index.ts +0 -4
  110. package/src/adapter/z-stack/unpi/parser.ts +0 -56
  111. package/src/adapter/z-stack/unpi/writer.ts +0 -21
  112. package/src/adapter/z-stack/utils/channel-list.ts +0 -40
  113. package/src/adapter/z-stack/utils/index.ts +0 -2
  114. package/src/adapter/z-stack/utils/network-options.ts +0 -26
  115. package/src/adapter/z-stack/znp/buffaloZnp.ts +0 -175
  116. package/src/adapter/z-stack/znp/definition.ts +0 -2713
  117. package/src/adapter/z-stack/znp/index.ts +0 -2
  118. package/src/adapter/z-stack/znp/parameterType.ts +0 -22
  119. package/src/adapter/z-stack/znp/tstype.ts +0 -44
  120. package/src/adapter/z-stack/znp/utils.ts +0 -10
  121. package/src/adapter/z-stack/znp/znp.ts +0 -342
  122. package/src/adapter/z-stack/znp/zpiObject.ts +0 -148
  123. package/src/adapter/zboss/adapter/zbossAdapter.ts +0 -526
  124. package/src/adapter/zboss/commands.ts +0 -1184
  125. package/src/adapter/zboss/consts.ts +0 -9
  126. package/src/adapter/zboss/driver.ts +0 -422
  127. package/src/adapter/zboss/enums.ts +0 -360
  128. package/src/adapter/zboss/frame.ts +0 -227
  129. package/src/adapter/zboss/reader.ts +0 -65
  130. package/src/adapter/zboss/types.ts +0 -0
  131. package/src/adapter/zboss/uart.ts +0 -428
  132. package/src/adapter/zboss/utils.ts +0 -58
  133. package/src/adapter/zboss/writer.ts +0 -49
  134. package/src/adapter/zigate/adapter/patchZdoBuffaloBE.ts +0 -27
  135. package/src/adapter/zigate/adapter/zigateAdapter.ts +0 -618
  136. package/src/adapter/zigate/driver/LICENSE +0 -17
  137. package/src/adapter/zigate/driver/buffaloZiGate.ts +0 -212
  138. package/src/adapter/zigate/driver/commandType.ts +0 -418
  139. package/src/adapter/zigate/driver/constants.ts +0 -150
  140. package/src/adapter/zigate/driver/frame.ts +0 -197
  141. package/src/adapter/zigate/driver/messageType.ts +0 -287
  142. package/src/adapter/zigate/driver/parameterType.ts +0 -32
  143. package/src/adapter/zigate/driver/ziGateObject.ts +0 -146
  144. package/src/adapter/zigate/driver/zigate.ts +0 -423
  145. package/src/adapter/zoh/adapter/utils.ts +0 -27
  146. package/src/adapter/zoh/adapter/zohAdapter.ts +0 -838
  147. package/src/buffalo/buffalo.ts +0 -342
  148. package/src/buffalo/index.ts +0 -1
  149. package/src/controller/controller.ts +0 -1022
  150. package/src/controller/database.ts +0 -124
  151. package/src/controller/events.ts +0 -52
  152. package/src/controller/greenPower.ts +0 -603
  153. package/src/controller/helpers/index.ts +0 -1
  154. package/src/controller/helpers/installCodes.ts +0 -107
  155. package/src/controller/helpers/request.ts +0 -96
  156. package/src/controller/helpers/requestQueue.ts +0 -125
  157. package/src/controller/helpers/zclFrameConverter.ts +0 -47
  158. package/src/controller/helpers/zclTransactionSequenceNumber.ts +0 -19
  159. package/src/controller/index.ts +0 -6
  160. package/src/controller/model/device.ts +0 -1249
  161. package/src/controller/model/endpoint.ts +0 -1105
  162. package/src/controller/model/entity.ts +0 -23
  163. package/src/controller/model/group.ts +0 -424
  164. package/src/controller/model/index.ts +0 -5
  165. package/src/controller/model/zigbeeEntity.ts +0 -30
  166. package/src/controller/touchlink.ts +0 -189
  167. package/src/controller/tstype.ts +0 -274
  168. package/src/index.ts +0 -12
  169. package/src/models/backup-storage-legacy.ts +0 -48
  170. package/src/models/backup-storage-unified.ts +0 -47
  171. package/src/models/backup.ts +0 -37
  172. package/src/models/index.ts +0 -5
  173. package/src/models/network-options.ts +0 -11
  174. package/src/utils/backup.ts +0 -152
  175. package/src/utils/index.ts +0 -5
  176. package/src/utils/logger.ts +0 -20
  177. package/src/utils/patchBigIntSerialization.ts +0 -8
  178. package/src/utils/queue.ts +0 -76
  179. package/src/utils/types.d.ts +0 -3
  180. package/src/utils/utils.ts +0 -19
  181. package/src/utils/wait.ts +0 -5
  182. package/src/utils/waitress.ts +0 -96
  183. package/src/zspec/consts.ts +0 -84
  184. package/src/zspec/enums.ts +0 -22
  185. package/src/zspec/index.ts +0 -3
  186. package/src/zspec/tstypes.ts +0 -18
  187. package/src/zspec/utils.ts +0 -247
  188. package/src/zspec/zcl/buffaloZcl.ts +0 -1220
  189. package/src/zspec/zcl/definition/cluster.ts +0 -5915
  190. package/src/zspec/zcl/definition/clusters-typegen.ts +0 -588
  191. package/src/zspec/zcl/definition/clusters-types.ts +0 -7331
  192. package/src/zspec/zcl/definition/consts.ts +0 -24
  193. package/src/zspec/zcl/definition/enums.ts +0 -203
  194. package/src/zspec/zcl/definition/foundation.ts +0 -329
  195. package/src/zspec/zcl/definition/manufacturerCode.ts +0 -729
  196. package/src/zspec/zcl/definition/status.ts +0 -69
  197. package/src/zspec/zcl/definition/tstype.ts +0 -377
  198. package/src/zspec/zcl/index.ts +0 -11
  199. package/src/zspec/zcl/utils.ts +0 -321
  200. package/src/zspec/zcl/zclFrame.ts +0 -356
  201. package/src/zspec/zcl/zclHeader.ts +0 -102
  202. package/src/zspec/zcl/zclStatusError.ts +0 -10
  203. package/src/zspec/zdo/buffaloZdo.ts +0 -2336
  204. package/src/zspec/zdo/definition/clusters.ts +0 -722
  205. package/src/zspec/zdo/definition/consts.ts +0 -16
  206. package/src/zspec/zdo/definition/enums.ts +0 -99
  207. package/src/zspec/zdo/definition/status.ts +0 -105
  208. package/src/zspec/zdo/definition/tstypes.ts +0 -1062
  209. package/src/zspec/zdo/index.ts +0 -7
  210. package/src/zspec/zdo/utils.ts +0 -76
  211. package/src/zspec/zdo/zdoStatusError.ts +0 -10
  212. package/test/adapter/adapter.test.ts +0 -1062
  213. package/test/adapter/ember/ash.test.ts +0 -337
  214. package/test/adapter/ember/consts.ts +0 -131
  215. package/test/adapter/ember/emberAdapter.test.ts +0 -3449
  216. package/test/adapter/ember/ezsp.test.ts +0 -385
  217. package/test/adapter/ember/ezspBuffalo.test.ts +0 -93
  218. package/test/adapter/ember/ezspError.test.ts +0 -12
  219. package/test/adapter/ember/math.test.ts +0 -206
  220. package/test/adapter/ezsp/frame.test.ts +0 -30
  221. package/test/adapter/ezsp/uart.test.ts +0 -181
  222. package/test/adapter/z-stack/adapter.test.ts +0 -3984
  223. package/test/adapter/z-stack/constants.test.ts +0 -33
  224. package/test/adapter/z-stack/structs.test.ts +0 -115
  225. package/test/adapter/z-stack/unpi.test.ts +0 -213
  226. package/test/adapter/z-stack/znp.test.ts +0 -1284
  227. package/test/adapter/zboss/fixZdoResponse.test.ts +0 -179
  228. package/test/adapter/zigate/patchZdoBuffaloBE.test.ts +0 -81
  229. package/test/adapter/zigate/zdo.test.ts +0 -187
  230. package/test/adapter/zoh/utils.test.ts +0 -36
  231. package/test/adapter/zoh/zohAdapter.test.ts +0 -1307
  232. package/test/benchOptions.ts +0 -14
  233. package/test/buffalo.test.ts +0 -431
  234. package/test/controller.bench.ts +0 -214
  235. package/test/controller.test.ts +0 -8702
  236. package/test/greenpower.test.ts +0 -1408
  237. package/test/mockAdapters.ts +0 -65
  238. package/test/mockDevices.ts +0 -598
  239. package/test/requests.bench.ts +0 -229
  240. package/test/testUtils.ts +0 -20
  241. package/test/tsconfig.json +0 -9
  242. package/test/utils/math.ts +0 -19
  243. package/test/utils.test.ts +0 -279
  244. package/test/vitest.config.mts +0 -26
  245. package/test/zcl.test.ts +0 -2831
  246. package/test/zspec/utils.test.ts +0 -68
  247. package/test/zspec/zcl/buffalo.test.ts +0 -1374
  248. package/test/zspec/zcl/frame.test.ts +0 -960
  249. package/test/zspec/zcl/utils.test.ts +0 -273
  250. package/test/zspec/zdo/buffalo.test.ts +0 -1850
  251. package/test/zspec/zdo/utils.test.ts +0 -241
  252. package/tsconfig.json +0 -24
@@ -1,1249 +0,0 @@
1
- import assert from "node:assert";
2
- import type {Events as AdapterEvents} from "../../adapter";
3
- import type {LQINeighbor, RoutingTableEntry} from "../../adapter/tstype";
4
- import {wait} from "../../utils";
5
- import {logger} from "../../utils/logger";
6
- import * as ZSpec from "../../zspec";
7
- import {BroadcastAddress} from "../../zspec/enums";
8
- import type {Eui64} from "../../zspec/tstypes";
9
- import * as Zcl from "../../zspec/zcl";
10
- import type {TPartialClusterAttributes} from "../../zspec/zcl/definition/clusters-types";
11
- import type {ClusterDefinition, CustomClusters} from "../../zspec/zcl/definition/tstype";
12
- import * as Zdo from "../../zspec/zdo";
13
- import type {ControllerEventMap} from "../controller";
14
- import zclTransactionSequenceNumber from "../helpers/zclTransactionSequenceNumber";
15
- import type {DatabaseEntry, DeviceType, KeyValue} from "../tstype";
16
- import Endpoint from "./endpoint";
17
- import Entity from "./entity";
18
-
19
- /**
20
- * @ignore
21
- */
22
- const OneJanuary2000 = new Date("January 01, 2000 00:00:00 UTC+00:00").getTime();
23
-
24
- const NS = "zh:controller:device";
25
-
26
- const INTERVIEW_GENBASIC_ATTRIBUTES = [
27
- "modelId",
28
- "manufacturerName",
29
- "powerSource",
30
- "zclVersion",
31
- "appVersion",
32
- "stackVersion",
33
- "hwVersion",
34
- "dateCode",
35
- "swBuildId",
36
- ] as const;
37
-
38
- interface Lqi {
39
- neighbors: {
40
- ieeeAddr: string;
41
- networkAddress: number;
42
- linkquality: number;
43
- relationship: number;
44
- depth: number;
45
- }[];
46
- }
47
-
48
- interface RoutingTable {
49
- table: {destinationAddress: number; status: string; nextHop: number}[];
50
- }
51
-
52
- type CustomReadResponse = (frame: Zcl.Frame, endpoint: Endpoint) => boolean;
53
-
54
- export enum InterviewState {
55
- Pending = "PENDING",
56
- InProgress = "IN_PROGRESS",
57
- Successful = "SUCCESSFUL",
58
- Failed = "FAILED",
59
- }
60
-
61
- export class Device extends Entity<ControllerEventMap> {
62
- // biome-ignore lint/style/useNamingConvention: cross-repo impact
63
- private readonly ID: number;
64
- #genBasic: TPartialClusterAttributes<"genBasic"> = {};
65
- private _endpoints: Endpoint[];
66
- private _ieeeAddr: string;
67
- private _interviewState: InterviewState;
68
- private _lastSeen?: number;
69
- private _manufacturerID?: number;
70
- private _networkAddress: number;
71
- private _type: DeviceType;
72
- private _linkquality?: number;
73
- private _skipDefaultResponse: boolean;
74
- private _customReadResponse?: CustomReadResponse;
75
- private _lastDefaultResponseSequenceNumber?: number;
76
- private _checkinInterval?: number;
77
- private _pendingRequestTimeout: number;
78
- private _customClusters: CustomClusters = {};
79
- private _gpSecurityKey?: number[];
80
-
81
- // Getters/setters
82
- get ieeeAddr(): string {
83
- return this._ieeeAddr;
84
- }
85
- set ieeeAddr(ieeeAddr: string) {
86
- this._ieeeAddr = ieeeAddr;
87
- }
88
- get applicationVersion(): number | undefined {
89
- return this.#genBasic.appVersion;
90
- }
91
- set applicationVersion(version: number) {
92
- this.#genBasic.appVersion = version;
93
- }
94
- get endpoints(): Endpoint[] {
95
- return this._endpoints;
96
- }
97
- get interviewState(): InterviewState {
98
- return this._interviewState;
99
- }
100
- get lastSeen(): number | undefined {
101
- return this._lastSeen;
102
- }
103
- get manufacturerID(): number | undefined {
104
- return this._manufacturerID;
105
- }
106
- get isDeleted(): boolean {
107
- return Device.deletedDevices.has(this.ieeeAddr);
108
- }
109
- set type(type: DeviceType) {
110
- this._type = type;
111
- }
112
- get type(): DeviceType {
113
- return this._type;
114
- }
115
- get dateCode(): string | undefined {
116
- return this.#genBasic.dateCode;
117
- }
118
- set dateCode(code: string) {
119
- this.#genBasic.dateCode = code;
120
- }
121
- set hardwareVersion(version: number) {
122
- this.#genBasic.hwVersion = version;
123
- }
124
- get hardwareVersion(): number | undefined {
125
- return this.#genBasic.hwVersion;
126
- }
127
- get manufacturerName(): string | undefined {
128
- return this.#genBasic.manufacturerName;
129
- }
130
- set manufacturerName(name: string | undefined) {
131
- this.#genBasic.manufacturerName = name;
132
- }
133
- set modelID(id: string) {
134
- this.#genBasic.modelId = id;
135
- }
136
- get modelID(): string | undefined {
137
- return this.#genBasic.modelId;
138
- }
139
- get networkAddress(): number {
140
- return this._networkAddress;
141
- }
142
- set networkAddress(networkAddress: number) {
143
- Device.nwkToIeeeCache.delete(this._networkAddress);
144
-
145
- this._networkAddress = networkAddress;
146
-
147
- Device.nwkToIeeeCache.set(this._networkAddress, this.ieeeAddr);
148
-
149
- for (const endpoint of this._endpoints) {
150
- endpoint.deviceNetworkAddress = networkAddress;
151
- }
152
- }
153
- get powerSource(): string | undefined {
154
- return this.#genBasic.powerSource ? Zcl.POWER_SOURCES[this.#genBasic.powerSource] : undefined;
155
- }
156
- set powerSource(source: string | number) {
157
- if (typeof source === "number") {
158
- this.#genBasic.powerSource = source & ~(1 << 7);
159
- } else {
160
- for (const key in Zcl.POWER_SOURCES) {
161
- const val = Zcl.POWER_SOURCES[key];
162
-
163
- if (val === source) {
164
- this.#genBasic.powerSource = Number(key);
165
- break;
166
- }
167
- }
168
- }
169
- }
170
- get softwareBuildID(): string | undefined {
171
- return this.#genBasic.swBuildId;
172
- }
173
- set softwareBuildID(id: string) {
174
- this.#genBasic.swBuildId = id;
175
- }
176
- get stackVersion(): number | undefined {
177
- return this.#genBasic.stackVersion;
178
- }
179
- set stackVersion(version: number) {
180
- this.#genBasic.stackVersion = version;
181
- }
182
- get zclVersion(): number | undefined {
183
- return this.#genBasic.zclVersion;
184
- }
185
- set zclVersion(version: number) {
186
- this.#genBasic.zclVersion = version;
187
- }
188
- get linkquality(): number | undefined {
189
- return this._linkquality;
190
- }
191
- set linkquality(linkquality: number) {
192
- this._linkquality = linkquality;
193
- }
194
- get skipDefaultResponse(): boolean {
195
- return this._skipDefaultResponse;
196
- }
197
- set skipDefaultResponse(skipDefaultResponse: boolean) {
198
- this._skipDefaultResponse = skipDefaultResponse;
199
- }
200
- get customReadResponse(): CustomReadResponse | undefined {
201
- return this._customReadResponse;
202
- }
203
- set customReadResponse(customReadResponse: CustomReadResponse | undefined) {
204
- this._customReadResponse = customReadResponse;
205
- }
206
- get checkinInterval(): number | undefined {
207
- return this._checkinInterval;
208
- }
209
- set checkinInterval(checkinInterval: number | undefined) {
210
- this._checkinInterval = checkinInterval;
211
-
212
- this.resetPendingRequestTimeout();
213
- }
214
- get pendingRequestTimeout(): number {
215
- return this._pendingRequestTimeout;
216
- }
217
- set pendingRequestTimeout(pendingRequestTimeout: number) {
218
- this._pendingRequestTimeout = pendingRequestTimeout;
219
- }
220
- get customClusters(): CustomClusters {
221
- return this._customClusters;
222
- }
223
- get gpSecurityKey(): number[] | undefined {
224
- return this._gpSecurityKey;
225
- }
226
- get genBasic(): TPartialClusterAttributes<"genBasic"> {
227
- return this.#genBasic;
228
- }
229
-
230
- public meta: KeyValue;
231
-
232
- // This lookup contains all devices that are queried from the database, this is to ensure that always
233
- // the same instance is returned.
234
- private static readonly devices: Map<string /* IEEE */, Device> = new Map();
235
- private static loadedFromDatabase = false;
236
- private static readonly deletedDevices: Map<string /* IEEE */, Device> = new Map();
237
- private static readonly nwkToIeeeCache: Map<number /* nwk addr */, string /* IEEE */> = new Map();
238
-
239
- private constructor(
240
- id: number,
241
- type: DeviceType,
242
- ieeeAddr: string,
243
- networkAddress: number,
244
- manufacturerID: number | undefined,
245
- endpoints: Endpoint[],
246
- manufacturerName: string | undefined,
247
- powerSource: string | undefined,
248
- modelID: string | undefined,
249
- applicationVersion: number | undefined,
250
- stackVersion: number | undefined,
251
- zclVersion: number | undefined,
252
- hardwareVersion: number | undefined,
253
- dateCode: string | undefined,
254
- softwareBuildID: string | undefined,
255
- interviewState: InterviewState,
256
- meta: KeyValue,
257
- lastSeen: number | undefined,
258
- checkinInterval: number | undefined,
259
- pendingRequestTimeout: number,
260
- gpSecurityKey: number[] | undefined,
261
- ) {
262
- super();
263
- this.ID = id;
264
- this._type = type;
265
- this._ieeeAddr = ieeeAddr;
266
- this._networkAddress = networkAddress;
267
- this._manufacturerID = manufacturerID;
268
- this._endpoints = endpoints;
269
- this.#genBasic.manufacturerName = manufacturerName;
270
- this.powerSource = powerSource ?? Zcl.PowerSource.Unknown;
271
- this.#genBasic.modelId = modelID;
272
- this.#genBasic.appVersion = applicationVersion;
273
- this.#genBasic.stackVersion = stackVersion;
274
- this.#genBasic.zclVersion = zclVersion;
275
- this.#genBasic.hwVersion = hardwareVersion;
276
- this.#genBasic.dateCode = dateCode;
277
- this.#genBasic.swBuildId = softwareBuildID;
278
- this._interviewState = interviewState;
279
- this._skipDefaultResponse = false;
280
- this.meta = meta;
281
- this._lastSeen = lastSeen;
282
- this._checkinInterval = checkinInterval;
283
- this._pendingRequestTimeout = pendingRequestTimeout;
284
- this._gpSecurityKey = gpSecurityKey;
285
- }
286
-
287
- public createEndpoint(id: number): Endpoint {
288
- if (this.getEndpoint(id)) {
289
- throw new Error(`Device '${this.ieeeAddr}' already has an endpoint '${id}'`);
290
- }
291
-
292
- const endpoint = Endpoint.create(id, undefined, undefined, [], [], this.networkAddress, this.ieeeAddr);
293
- this.endpoints.push(endpoint);
294
- this.save();
295
- return endpoint;
296
- }
297
-
298
- public changeIeeeAddress(ieeeAddr: string): void {
299
- Device.devices.delete(this.ieeeAddr);
300
- this.ieeeAddr = ieeeAddr;
301
- Device.devices.set(this.ieeeAddr, this);
302
- Device.nwkToIeeeCache.set(this.networkAddress, this.ieeeAddr);
303
- for (const ep of this.endpoints) {
304
- ep.deviceIeeeAddress = ieeeAddr;
305
- }
306
-
307
- this.save();
308
- }
309
-
310
- public getEndpoint(id: number): Endpoint | undefined {
311
- return this.endpoints.find((e): boolean => e.ID === id);
312
- }
313
-
314
- // There might be multiple endpoints with same DeviceId but it is not supported and first endpoint is returned
315
- public getEndpointByDeviceType(deviceType: string): Endpoint | undefined {
316
- const deviceID = Zcl.ENDPOINT_DEVICE_TYPE[deviceType];
317
- return this.endpoints.find((d): boolean => d.deviceID === deviceID);
318
- }
319
-
320
- public updateGenBasic(data: TPartialClusterAttributes<"genBasic">): void {
321
- Object.assign(this.#genBasic, data);
322
- }
323
-
324
- public implicitCheckin(): void {
325
- // No need to do anythign in `catch` as `endpoint.sendRequest` already logs failures.
326
- Promise.allSettled(this.endpoints.map((e) => e.sendPendingRequests(false))).catch(() => {});
327
- }
328
-
329
- public updateLastSeen(): void {
330
- this._lastSeen = Date.now();
331
- }
332
-
333
- private resetPendingRequestTimeout(): void {
334
- // pendingRequestTimeout can be changed dynamically at runtime, and it is not persisted.
335
- // Default timeout is one checkin interval in milliseconds.
336
- this._pendingRequestTimeout = (this._checkinInterval ?? 0) * 1000;
337
- }
338
-
339
- private hasPendingRequests(): boolean {
340
- return this.endpoints.find((e) => e.hasPendingRequests()) !== undefined;
341
- }
342
-
343
- public async onZclData(dataPayload: AdapterEvents.ZclPayload, frame: Zcl.Frame, endpoint: Endpoint): Promise<void> {
344
- // Respond to enroll requests
345
- if (frame.header.isSpecific && frame.isCluster("ssIasZone") && frame.isCommand("enrollReq")) {
346
- logger.debug(`IAS - '${this.ieeeAddr}' responding to enroll response`, NS);
347
- const payload = {enrollrspcode: 0, zoneid: 23};
348
- await endpoint.command("ssIasZone", "enrollRsp", payload, {disableDefaultResponse: true});
349
- }
350
-
351
- // Reponse to read requests
352
- if (frame.header.isGlobal && frame.isCommand("read") && !this._customReadResponse?.(frame, endpoint)) {
353
- const time = Math.round((Date.now() - OneJanuary2000) / 1000);
354
- const attributes: {[s: string]: KeyValue} = {
355
- ...endpoint.clusters,
356
- genTime: {
357
- attributes: {
358
- timeStatus: 3, // Time-master + synchronised
359
- time: time,
360
- timeZone: new Date().getTimezoneOffset() * -1 * 60,
361
- localTime: time - new Date().getTimezoneOffset() * 60,
362
- lastSetTime: time,
363
- validUntilTime: time + 24 * 60 * 60, // valid for 24 hours
364
- },
365
- },
366
- };
367
-
368
- if (frame.cluster.name in attributes) {
369
- const response: KeyValue = {};
370
-
371
- for (const entry of frame.payload) {
372
- const name = frame.cluster.getAttribute(entry.attrId)?.name;
373
-
374
- if (name && name in attributes[frame.cluster.name].attributes) {
375
- response[name] = attributes[frame.cluster.name].attributes[name];
376
- }
377
- }
378
-
379
- try {
380
- await endpoint.readResponse(frame.cluster.ID, frame.header.transactionSequenceNumber, response, {
381
- srcEndpoint: dataPayload.destinationEndpoint,
382
- });
383
- } catch (error) {
384
- logger.error(`Read response to ${this.ieeeAddr} failed (${(error as Error).message})`, NS);
385
- }
386
- }
387
- }
388
-
389
- // Handle check-in from sleeping end devices
390
- if (frame.header.isSpecific && frame.isCluster("genPollCtrl") && frame.isCommand("checkin")) {
391
- try {
392
- if (this.hasPendingRequests() || this._checkinInterval === undefined) {
393
- logger.debug(`check-in from ${this.ieeeAddr}: accepting fast-poll`, NS);
394
- await endpoint.command(
395
- frame.cluster.name as "genPollCtrl",
396
- "checkinRsp",
397
- {
398
- startFastPolling: 1,
399
- fastPollTimeout: 0,
400
- },
401
- {sendPolicy: "immediate"},
402
- );
403
-
404
- // This is a good time to read the checkin interval if we haven't stored it previously
405
- if (this._checkinInterval === undefined) {
406
- const pollPeriod = await endpoint.read("genPollCtrl", ["checkinInterval"], {sendPolicy: "immediate"});
407
- this._checkinInterval = pollPeriod.checkinInterval / 4; // convert to seconds
408
- this.resetPendingRequestTimeout();
409
- logger.debug(`Request Queue (${this.ieeeAddr}): default expiration timeout set to ${this.pendingRequestTimeout}`, NS);
410
- }
411
-
412
- await Promise.all(this.endpoints.map(async (e) => await e.sendPendingRequests(true)));
413
- // We *must* end fast-poll when we're done sending things. Otherwise
414
- // we cause undue power-drain.
415
- logger.debug(`check-in from ${this.ieeeAddr}: stopping fast-poll`, NS);
416
- await endpoint.command(frame.cluster.name as "genPollCtrl", "fastPollStop", {}, {sendPolicy: "immediate"});
417
- } else {
418
- logger.debug(`check-in from ${this.ieeeAddr}: declining fast-poll`, NS);
419
- await endpoint.command(
420
- frame.cluster.name as "genPollCtrl",
421
- "checkinRsp",
422
- {
423
- startFastPolling: 0,
424
- fastPollTimeout: 0,
425
- },
426
- {sendPolicy: "immediate"},
427
- );
428
- }
429
- } catch (error) {
430
- logger.error(`Handling of poll check-in from ${this.ieeeAddr} failed (${(error as Error).message})`, NS);
431
- }
432
- }
433
-
434
- // Send a default response if necessary.
435
- const isDefaultResponse = frame.header.isGlobal && frame.command.name === "defaultRsp";
436
- const commandHasResponse = frame.command.response !== undefined;
437
- const disableDefaultResponse = frame.header.frameControl.disableDefaultResponse;
438
- /* v8 ignore next */
439
- const disableTuyaDefaultResponse = endpoint.getDevice().manufacturerName?.startsWith("_TZ") && process.env.DISABLE_TUYA_DEFAULT_RESPONSE;
440
- // Sometimes messages are received twice, prevent responding twice
441
- const alreadyResponded = this._lastDefaultResponseSequenceNumber === frame.header.transactionSequenceNumber;
442
-
443
- if (
444
- this.type !== "GreenPower" &&
445
- !dataPayload.wasBroadcast &&
446
- !disableDefaultResponse &&
447
- !isDefaultResponse &&
448
- !commandHasResponse &&
449
- !this._skipDefaultResponse &&
450
- !alreadyResponded &&
451
- !disableTuyaDefaultResponse
452
- ) {
453
- try {
454
- this._lastDefaultResponseSequenceNumber = frame.header.transactionSequenceNumber;
455
- // In the ZCL it is not documented what the direction of the default response should be
456
- // In https://github.com/Koenkk/zigbee2mqtt/issues/18096 a commandResponse (SERVER_TO_CLIENT)
457
- // is send and the device expects a CLIENT_TO_SERVER back.
458
- // Previously SERVER_TO_CLIENT was always used.
459
- // Therefore for non-global commands we inverse the direction.
460
- const direction = frame.header.isGlobal
461
- ? Zcl.Direction.SERVER_TO_CLIENT
462
- : frame.header.frameControl.direction === Zcl.Direction.CLIENT_TO_SERVER
463
- ? Zcl.Direction.SERVER_TO_CLIENT
464
- : Zcl.Direction.CLIENT_TO_SERVER;
465
-
466
- await endpoint.defaultResponse(frame.command.ID, 0, frame.cluster.ID, frame.header.transactionSequenceNumber, {direction});
467
- } catch (error) {
468
- logger.debug(`Default response to ${this.ieeeAddr} failed (${error})`, NS);
469
- }
470
- }
471
- }
472
-
473
- /*
474
- * CRUD
475
- */
476
-
477
- /**
478
- * Reset runtime lookups.
479
- */
480
- public static resetCache(): void {
481
- Device.devices.clear();
482
- Device.loadedFromDatabase = false;
483
- Device.deletedDevices.clear();
484
- Device.nwkToIeeeCache.clear();
485
- }
486
-
487
- private static fromDatabaseEntry(entry: DatabaseEntry): Device {
488
- const networkAddress = entry.nwkAddr;
489
- const ieeeAddr = entry.ieeeAddr;
490
- const endpoints: Endpoint[] = [];
491
-
492
- for (const id in entry.endpoints) {
493
- endpoints.push(Endpoint.fromDatabaseRecord(entry.endpoints[id], networkAddress, ieeeAddr));
494
- }
495
-
496
- const meta = entry.meta ?? {};
497
-
498
- if (entry.type === "Group") {
499
- throw new Error("Cannot load device from group");
500
- }
501
-
502
- // default: no timeout (messages expire immediately after first send attempt)
503
- let pendingRequestTimeout = 0;
504
- if (endpoints.filter((e): boolean => e.inputClusters.includes(Zcl.Clusters.genPollCtrl.ID)).length > 0) {
505
- // default for devices that support genPollCtrl cluster (RX off when idle): 1 day
506
- pendingRequestTimeout = 86400000;
507
- }
508
- // always load value from database available (modernExtend.quirkCheckinInterval() exists for devices without genPollCtl)
509
- if (entry.checkinInterval !== undefined) {
510
- // if the checkin interval is known, messages expire by default after one checkin interval
511
- pendingRequestTimeout = entry.checkinInterval * 1000; // milliseconds
512
- }
513
- logger.debug(`Request Queue (${ieeeAddr}): default expiration timeout set to ${pendingRequestTimeout}`, NS);
514
-
515
- // Migrate interviewCompleted to interviewState
516
- if (!entry.interviewState) {
517
- entry.interviewState = entry.interviewCompleted ? InterviewState.Successful : InterviewState.Failed;
518
- logger.debug(`Migrated interviewState for '${ieeeAddr}': ${entry.interviewCompleted} -> ${entry.interviewState}`, NS);
519
- }
520
-
521
- return new Device(
522
- entry.id,
523
- entry.type,
524
- ieeeAddr,
525
- networkAddress,
526
- entry.manufId,
527
- endpoints,
528
- entry.manufName,
529
- entry.powerSource,
530
- entry.modelId,
531
- entry.appVersion,
532
- entry.stackVersion,
533
- entry.zclVersion,
534
- entry.hwVersion,
535
- entry.dateCode,
536
- entry.swBuildId,
537
- entry.interviewState,
538
- meta,
539
- entry.lastSeen,
540
- entry.checkinInterval,
541
- pendingRequestTimeout,
542
- entry.gpSecurityKey,
543
- );
544
- }
545
-
546
- private toDatabaseEntry(): DatabaseEntry {
547
- const epList = this.endpoints.map((e): number => e.ID);
548
- const endpoints: KeyValue = {};
549
-
550
- for (const endpoint of this.endpoints) {
551
- endpoints[endpoint.ID] = endpoint.toDatabaseRecord();
552
- }
553
-
554
- return {
555
- id: this.ID,
556
- type: this.type,
557
- ieeeAddr: this.ieeeAddr,
558
- nwkAddr: this.networkAddress,
559
- manufId: this.manufacturerID,
560
- manufName: this.manufacturerName,
561
- powerSource: this.powerSource,
562
- modelId: this.modelID,
563
- epList,
564
- endpoints,
565
- appVersion: this.applicationVersion,
566
- stackVersion: this.stackVersion,
567
- hwVersion: this.hardwareVersion,
568
- dateCode: this.dateCode,
569
- swBuildId: this.softwareBuildID,
570
- zclVersion: this.zclVersion,
571
- /** @deprecated Keep interviewCompleted for backwards compatibility (in case zh gets downgraded) */
572
- interviewCompleted: this.interviewState === InterviewState.Successful,
573
- interviewState: this.interviewState === InterviewState.InProgress ? InterviewState.Pending : this.interviewState,
574
- meta: this.meta,
575
- lastSeen: this.lastSeen,
576
- checkinInterval: this.checkinInterval,
577
- gpSecurityKey: this.gpSecurityKey,
578
- };
579
- }
580
-
581
- public save(writeDatabase = true): void {
582
- Entity.database.update(this.toDatabaseEntry(), writeDatabase);
583
- }
584
-
585
- private static loadFromDatabaseIfNecessary(): void {
586
- if (!Device.loadedFromDatabase) {
587
- for (const entry of Entity.database.getEntriesIterator(["Coordinator", "EndDevice", "Router", "GreenPower", "Unknown"])) {
588
- const device = Device.fromDatabaseEntry(entry);
589
-
590
- Device.devices.set(device.ieeeAddr, device);
591
- Device.nwkToIeeeCache.set(device.networkAddress, device.ieeeAddr);
592
- }
593
-
594
- Device.loadedFromDatabase = true;
595
- }
596
- }
597
-
598
- public static find(ieeeOrNwkAddress: string | number, includeDeleted = false): Device | undefined {
599
- return typeof ieeeOrNwkAddress === "string"
600
- ? Device.byIeeeAddr(ieeeOrNwkAddress, includeDeleted)
601
- : Device.byNetworkAddress(ieeeOrNwkAddress, includeDeleted);
602
- }
603
-
604
- public static byIeeeAddr(ieeeAddr: string, includeDeleted = false): Device | undefined {
605
- Device.loadFromDatabaseIfNecessary();
606
-
607
- return includeDeleted ? (Device.deletedDevices.get(ieeeAddr) ?? Device.devices.get(ieeeAddr)) : Device.devices.get(ieeeAddr);
608
- }
609
-
610
- public static byNetworkAddress(networkAddress: number, includeDeleted = false): Device | undefined {
611
- Device.loadFromDatabaseIfNecessary();
612
-
613
- const ieeeAddr = Device.nwkToIeeeCache.get(networkAddress);
614
-
615
- return ieeeAddr ? Device.byIeeeAddr(ieeeAddr, includeDeleted) : undefined;
616
- }
617
-
618
- public static byType(type: DeviceType): Device[] {
619
- const devices: Device[] = [];
620
-
621
- for (const device of Device.allIterator((d) => d.type === type)) {
622
- devices.push(device);
623
- }
624
-
625
- return devices;
626
- }
627
-
628
- /**
629
- * @deprecated use allIterator()
630
- */
631
- public static all(): Device[] {
632
- Device.loadFromDatabaseIfNecessary();
633
- return Array.from(Device.devices.values());
634
- }
635
-
636
- public static *allIterator(predicate?: (value: Device) => boolean): Generator<Device> {
637
- Device.loadFromDatabaseIfNecessary();
638
-
639
- for (const device of Device.devices.values()) {
640
- if (!predicate || predicate(device)) {
641
- yield device;
642
- }
643
- }
644
- }
645
-
646
- public undelete(): void {
647
- if (Device.deletedDevices.delete(this.ieeeAddr)) {
648
- Device.devices.set(this.ieeeAddr, this);
649
-
650
- Entity.database.insert(this.toDatabaseEntry());
651
- } else {
652
- throw new Error(`Device '${this.ieeeAddr}' is not deleted`);
653
- }
654
- }
655
-
656
- public static create(
657
- type: DeviceType,
658
- ieeeAddr: string,
659
- networkAddress: number,
660
- manufacturerID: number | undefined,
661
- manufacturerName: string | undefined,
662
- powerSource: string | undefined,
663
- modelID: string | undefined,
664
- interviewState: InterviewState,
665
- gpSecurityKey: number[] | undefined,
666
- ): Device {
667
- Device.loadFromDatabaseIfNecessary();
668
-
669
- if (Device.devices.has(ieeeAddr)) {
670
- throw new Error(`Device with IEEE address '${ieeeAddr}' already exists`);
671
- }
672
-
673
- const ID = Entity.database.newID();
674
- const device = new Device(
675
- ID,
676
- type,
677
- ieeeAddr,
678
- networkAddress,
679
- manufacturerID,
680
- [],
681
- manufacturerName,
682
- powerSource,
683
- modelID,
684
- undefined,
685
- undefined,
686
- undefined,
687
- undefined,
688
- undefined,
689
- undefined,
690
- interviewState,
691
- {},
692
- undefined,
693
- undefined,
694
- 0,
695
- gpSecurityKey,
696
- );
697
-
698
- Entity.database.insert(device.toDatabaseEntry());
699
- Device.devices.set(device.ieeeAddr, device);
700
- Device.nwkToIeeeCache.set(device.networkAddress, device.ieeeAddr);
701
- return device;
702
- }
703
-
704
- /*
705
- * Zigbee functions
706
- */
707
-
708
- public async interview(ignoreCache = false): Promise<void> {
709
- if (this.interviewState === InterviewState.InProgress) {
710
- const message = `Interview - interview already in progress for '${this.ieeeAddr}'`;
711
- logger.debug(message, NS);
712
- throw new Error(message);
713
- }
714
-
715
- let err: unknown;
716
- this._interviewState = InterviewState.InProgress;
717
- logger.debug(`Interview - start device '${this.ieeeAddr}'`, NS);
718
-
719
- try {
720
- await this.interviewInternal(ignoreCache);
721
- logger.debug(`Interview - completed for device '${this.ieeeAddr}'`, NS);
722
- this._interviewState = InterviewState.Successful;
723
- } catch (error) {
724
- if (this.interviewQuirks()) {
725
- this._interviewState = InterviewState.Successful;
726
- logger.debug(`Interview - completed for device '${this.ieeeAddr}' because of quirks ('${error}')`, NS);
727
- } else {
728
- this._interviewState = InterviewState.Failed;
729
- logger.debug(`Interview - failed for device '${this.ieeeAddr}' with error '${error}'`, NS);
730
- err = error;
731
- }
732
- } finally {
733
- this.save();
734
- }
735
-
736
- if (err) {
737
- throw err;
738
- }
739
- }
740
-
741
- private interviewQuirks(): boolean {
742
- logger.debug(`Interview - quirks check for '${this.modelID}'-'${this.manufacturerName}'-'${this.type}'`, NS);
743
-
744
- // Tuya devices are typically hard to interview. They also don't require a full interview to work correctly
745
- // e.g. no ias enrolling is required for the devices to work.
746
- // Assume that in case we got both the manufacturerName and modelID the device works correctly.
747
- // https://github.com/Koenkk/zigbee2mqtt/issues/7564:
748
- // Fails during ias enroll due to UNSUPPORTED_ATTRIBUTE
749
- // https://github.com/Koenkk/zigbee2mqtt/issues/4655
750
- // Device does not change zoneState after enroll (event with original gateway)
751
- // modelID is mostly in the form of e.g. TS0202 and manufacturerName like e.g. _TYZB01_xph99wvr
752
- if (
753
- this.manufacturerName === "HOBEIAN" ||
754
- (this.modelID?.match("^TS\\d*$") && (this.manufacturerName?.match("^_TZ.*_.*$") || this.manufacturerName?.match("^_TYZB01_.*$")))
755
- ) {
756
- this.#genBasic.powerSource = this.#genBasic.powerSource || Zcl.PowerSource.Battery;
757
- logger.debug("Interview - quirks matched for Tuya end device", NS);
758
- return true;
759
- }
760
-
761
- // Some devices, e.g. Xiaomi end devices have a different interview procedure, after pairing they
762
- // report it's modelID trough a readResponse. The readResponse is received by the controller and set
763
- // on the device.
764
- const lookup: {
765
- [s: string]: {
766
- type?: DeviceType;
767
- manufacturerID?: number;
768
- manufacturerName?: string;
769
- powerSource?: Zcl.PowerSource;
770
- };
771
- } = {
772
- "^3R.*?Z": {
773
- type: "EndDevice",
774
- powerSource: Zcl.PowerSource.Battery,
775
- },
776
- "lumi..*": {
777
- type: "EndDevice",
778
- manufacturerID: 4151,
779
- manufacturerName: "LUMI",
780
- powerSource: Zcl.PowerSource.Battery,
781
- },
782
- "TERNCY-PP01": {
783
- type: "EndDevice",
784
- manufacturerID: 4648,
785
- manufacturerName: "TERNCY",
786
- powerSource: Zcl.PowerSource.Battery,
787
- },
788
- "3RWS18BZ": {}, // https://github.com/Koenkk/zigbee-herdsman-converters/pull/2710
789
- "MULTI-MECI--EA01": {},
790
- MOT003: {}, // https://github.com/Koenkk/zigbee2mqtt/issues/12471
791
- "C-ZB-SEDC": {}, //candeo device that doesn't follow IAS enrollment process correctly and therefore fails to complete interview
792
- "C-ZB-SEMO": {}, //candeo device that doesn't follow IAS enrollment process correctly and therefore fails to complete interview
793
- "CS-T9C-A0-BG": {}, // iAS enroll fails: https://github.com/Koenkk/zigbee2mqtt/issues/27822
794
- };
795
-
796
- let match: string | undefined;
797
-
798
- for (const key in lookup) {
799
- if (this.modelID?.match(key)) {
800
- match = key;
801
- break;
802
- }
803
- }
804
-
805
- if (match) {
806
- const info = lookup[match];
807
- logger.debug(`Interview procedure failed but got modelID matching '${match}', assuming interview succeeded`, NS);
808
- this._type = this._type === "Unknown" && info.type ? info.type : this._type;
809
- this._manufacturerID = this._manufacturerID || info.manufacturerID;
810
- this.#genBasic.manufacturerName = this.#genBasic.manufacturerName || info.manufacturerName;
811
- this.#genBasic.powerSource = (this.#genBasic.powerSource || info.powerSource) /* v8 ignore next */ ?? Zcl.PowerSource.Unknown;
812
- logger.debug(`Interview - quirks matched on '${match}'`, NS);
813
- return true;
814
- }
815
-
816
- logger.debug("Interview - quirks did not match", NS);
817
- return false;
818
- }
819
-
820
- private async interviewInternal(ignoreCache: boolean): Promise<void> {
821
- const hasNodeDescriptor = (): boolean => this._manufacturerID !== undefined && this._type !== "Unknown";
822
-
823
- if (ignoreCache || !hasNodeDescriptor()) {
824
- for (let attempt = 0; attempt < 6; attempt++) {
825
- try {
826
- await this.updateNodeDescriptor();
827
- break;
828
- } catch (error) {
829
- if (this.interviewQuirks()) {
830
- logger.debug(`Interview - completed for device '${this.ieeeAddr}' because of quirks ('${error}')`, NS);
831
- return;
832
- }
833
-
834
- // Most of the times the first node descriptor query fails and the seconds one succeeds.
835
- logger.debug(`Interview - node descriptor request failed for '${this.ieeeAddr}', attempt ${attempt + 1}`, NS);
836
- }
837
- }
838
- } else {
839
- logger.debug(`Interview - skip node descriptor request for '${this.ieeeAddr}', already got it`, NS);
840
- }
841
-
842
- if (!hasNodeDescriptor()) {
843
- throw new Error(`Interview failed because can not get node descriptor ('${this.ieeeAddr}')`);
844
- }
845
-
846
- if (this.manufacturerID === 4619 && this._type === "EndDevice") {
847
- // Give Tuya end device some time to pair. Otherwise they leave immediately.
848
- // https://github.com/Koenkk/zigbee2mqtt/issues/5814
849
- logger.debug("Interview - Detected Tuya end device, waiting 10 seconds...", NS);
850
- await wait(10000);
851
- } else if (this.manufacturerID === 0 || this.manufacturerID === 4098) {
852
- // Potentially a Tuya device, some sleep fast so make sure to read the modelId and manufacturerName quickly.
853
- // In case the device responds, the endoint and modelID/manufacturerName are set
854
- // in controller.onZclOrRawData()
855
- // https://github.com/Koenkk/zigbee2mqtt/issues/7553
856
- logger.debug("Interview - Detected potential Tuya end device, reading modelID and manufacturerName...", NS);
857
- try {
858
- const endpoint = Endpoint.create(1, undefined, undefined, [], [], this.networkAddress, this.ieeeAddr);
859
- const result = await endpoint.read("genBasic", ["modelId", "manufacturerName"], {sendPolicy: "immediate"});
860
-
861
- this.updateGenBasic(result);
862
- } catch (error) {
863
- logger.debug(`Interview - Tuya read modelID and manufacturerName failed (${error})`, NS);
864
- }
865
- }
866
-
867
- // e.g. Xiaomi Aqara Opple devices fail to respond to the first active endpoints request, therefore try 2 times
868
- // https://github.com/Koenkk/zigbee-herdsman/pull/103
869
- let gotActiveEndpoints = false;
870
-
871
- for (let attempt = 0; attempt < 2; attempt++) {
872
- try {
873
- await this.updateActiveEndpoints();
874
- gotActiveEndpoints = true;
875
- break;
876
- } catch (error) {
877
- logger.debug(`Interview - active endpoints request failed for '${this.ieeeAddr}', attempt ${attempt + 1} (${error})`, NS);
878
- }
879
- }
880
-
881
- if (!gotActiveEndpoints) {
882
- throw new Error(`Interview failed because can not get active endpoints ('${this.ieeeAddr}')`);
883
- }
884
-
885
- logger.debug(`Interview - got active endpoints for device '${this.ieeeAddr}'`, NS);
886
-
887
- const coordinator = Device.byType("Coordinator")[0];
888
-
889
- for (const endpoint of this._endpoints) {
890
- await endpoint.updateSimpleDescriptor();
891
- logger.debug(`Interview - got simple descriptor for endpoint '${endpoint.ID}' device '${this.ieeeAddr}'`, NS);
892
-
893
- // Read attributes
894
- // nice to have but not required for successful pairing as most of the attributes are not mandatory in ZCL specification
895
- if (endpoint.supportsInputCluster("genBasic")) {
896
- for (const key of INTERVIEW_GENBASIC_ATTRIBUTES) {
897
- if (ignoreCache || !this.#genBasic[key]) {
898
- try {
899
- let result: TPartialClusterAttributes<"genBasic">;
900
-
901
- try {
902
- result = await endpoint.read("genBasic", [key], {sendPolicy: "immediate"});
903
- } catch (error) {
904
- // Reading attributes can fail for many reason, e.g. it could be that device rejoins
905
- // while joining like in:
906
- // https://github.com/Koenkk/zigbee-herdsman-converters/issues/2485.
907
- // The modelID and manufacturerName are crucial for device identification, so retry.
908
- if (key === "modelId" || key === "manufacturerName") {
909
- logger.debug(`Interview - first ${key} retrieval attempt failed, retrying after 10 seconds...`, NS);
910
- await wait(10000);
911
- result = await endpoint.read("genBasic", [key], {sendPolicy: "immediate"});
912
- } else {
913
- throw error;
914
- }
915
- }
916
-
917
- this.updateGenBasic(result);
918
- logger.debug(`Interview - got '${key}' for device '${this.ieeeAddr}'`, NS);
919
- } catch (error) {
920
- logger.debug(`Interview - failed to read attribute '${key}' from endpoint '${endpoint.ID}' (${error})`, NS);
921
- }
922
- }
923
- }
924
- }
925
-
926
- // Enroll IAS device
927
- if (endpoint.supportsInputCluster("ssIasZone")) {
928
- logger.debug(`Interview - IAS - enrolling '${this.ieeeAddr}' endpoint '${endpoint.ID}'`, NS);
929
-
930
- const stateBefore = await endpoint.read("ssIasZone", ["iasCieAddr", "zoneState"], {sendPolicy: "immediate"});
931
- logger.debug(`Interview - IAS - before enrolling state: '${JSON.stringify(stateBefore)}'`, NS);
932
-
933
- // Do not enroll when device has already been enrolled
934
- if (stateBefore.zoneState !== 1 || stateBefore.iasCieAddr !== coordinator.ieeeAddr) {
935
- logger.debug("Interview - IAS - not enrolled, enrolling", NS);
936
-
937
- await endpoint.write("ssIasZone", {iasCieAddr: coordinator.ieeeAddr}, {sendPolicy: "immediate"});
938
- logger.debug("Interview - IAS - wrote iasCieAddr", NS);
939
-
940
- // There are 2 enrollment procedures:
941
- // - Auto enroll: coordinator has to send enrollResponse without receiving an enroll request
942
- // this case is handled below.
943
- // - Manual enroll: coordinator replies to enroll request with an enroll response.
944
- // this case in hanled in onZclData().
945
- // https://github.com/Koenkk/zigbee2mqtt/issues/4569#issuecomment-706075676
946
- await wait(500);
947
- logger.debug(`IAS - '${this.ieeeAddr}' sending enroll response (auto enroll)`, NS);
948
- const payload = {enrollrspcode: 0, zoneid: 23};
949
- await endpoint.command("ssIasZone", "enrollRsp", payload, {disableDefaultResponse: true, sendPolicy: "immediate"});
950
-
951
- let enrolled = false;
952
- for (let attempt = 0; attempt < 20; attempt++) {
953
- await wait(500);
954
- const stateAfter = await endpoint.read("ssIasZone", ["iasCieAddr", "zoneState"], {sendPolicy: "immediate"});
955
- logger.debug(`Interview - IAS - after enrolling state (${attempt}): '${JSON.stringify(stateAfter)}'`, NS);
956
- if (stateAfter.zoneState === 1) {
957
- enrolled = true;
958
- break;
959
- }
960
- }
961
-
962
- if (enrolled) {
963
- logger.debug(`Interview - IAS successfully enrolled '${this.ieeeAddr}' endpoint '${endpoint.ID}'`, NS);
964
- } else {
965
- throw new Error(`Interview failed because of failed IAS enroll (zoneState didn't change ('${this.ieeeAddr}')`);
966
- }
967
- } else {
968
- logger.debug("Interview - IAS - already enrolled, skipping enroll", NS);
969
- }
970
- }
971
- }
972
-
973
- // Bind poll control
974
- try {
975
- for (const endpoint of this.endpoints.filter((e): boolean => e.supportsInputCluster("genPollCtrl"))) {
976
- logger.debug(`Interview - Poll control - binding '${this.ieeeAddr}' endpoint '${endpoint.ID}'`, NS);
977
- await endpoint.bind("genPollCtrl", coordinator.endpoints[0]);
978
- const pollPeriod = await endpoint.read("genPollCtrl", ["checkinInterval"], {sendPolicy: "immediate"});
979
- this._checkinInterval = pollPeriod.checkinInterval / 4; // convert to seconds
980
- this.resetPendingRequestTimeout();
981
- }
982
- /* v8 ignore start */
983
- } catch (error) {
984
- logger.debug(`Interview - failed to bind genPollCtrl (${error})`, NS);
985
- }
986
- /* v8 ignore stop */
987
- }
988
-
989
- public async updateNodeDescriptor(): Promise<void> {
990
- const clusterId = Zdo.ClusterId.NODE_DESCRIPTOR_REQUEST;
991
- const zdoPayload = Zdo.Buffalo.buildRequest(Entity.adapter.hasZdoMessageOverhead, clusterId, this.networkAddress);
992
- const response = await Entity.adapter.sendZdo(this.ieeeAddr, this.networkAddress, clusterId, zdoPayload, false);
993
-
994
- if (!Zdo.Buffalo.checkStatus<Zdo.ClusterId.NODE_DESCRIPTOR_RESPONSE>(response)) {
995
- throw new Zdo.StatusError(response[0]);
996
- }
997
-
998
- // TODO: make use of: capabilities.rxOnWhenIdle, maxIncTxSize, maxOutTxSize, serverMask.stackComplianceRevision
999
- const nodeDescriptor = response[1];
1000
- this._manufacturerID = nodeDescriptor.manufacturerCode;
1001
-
1002
- switch (nodeDescriptor.logicalType) {
1003
- case 0x0:
1004
- this._type = "Coordinator";
1005
- break;
1006
- case 0x1:
1007
- this._type = "Router";
1008
- break;
1009
- case 0x2:
1010
- this._type = "EndDevice";
1011
- break;
1012
- }
1013
-
1014
- logger.debug(`Interview - got node descriptor for device '${this.ieeeAddr}'`, NS);
1015
-
1016
- // TODO: define a property on Device for this value (would be good to have it displayed)
1017
- // log for devices older than 1 from current revision
1018
- if (nodeDescriptor.serverMask.stackComplianceRevision < ZSpec.ZIGBEE_REVISION - 1) {
1019
- // always 0 before revision 21 where field was added
1020
- const rev = nodeDescriptor.serverMask.stackComplianceRevision < 21 ? "pre-21" : nodeDescriptor.serverMask.stackComplianceRevision;
1021
-
1022
- logger.info(
1023
- `Device '${this.ieeeAddr}' is only compliant to revision '${rev}' of the ZigBee specification (current revision: ${ZSpec.ZIGBEE_REVISION}).`,
1024
- NS,
1025
- );
1026
- }
1027
- }
1028
-
1029
- public async updateActiveEndpoints(): Promise<void> {
1030
- const clusterId = Zdo.ClusterId.ACTIVE_ENDPOINTS_REQUEST;
1031
- const zdoPayload = Zdo.Buffalo.buildRequest(Entity.adapter.hasZdoMessageOverhead, clusterId, this.networkAddress);
1032
-
1033
- const response = await Entity.adapter.sendZdo(this.ieeeAddr, this.networkAddress, clusterId, zdoPayload, false);
1034
-
1035
- if (!Zdo.Buffalo.checkStatus<Zdo.ClusterId.ACTIVE_ENDPOINTS_RESPONSE>(response)) {
1036
- throw new Zdo.StatusError(response[0]);
1037
- }
1038
-
1039
- const activeEndpoints = response[1];
1040
-
1041
- // Make sure that the endpoint are sorted.
1042
- activeEndpoints.endpointList.sort((a, b) => a - b);
1043
- for (const endpoint of activeEndpoints.endpointList) {
1044
- // Some devices, e.g. TERNCY return endpoint 0 in the active endpoints request.
1045
- // This is not a valid endpoint number according to the ZCL, requesting a simple descriptor will result
1046
- // into an error. Therefore we filter it, more info: https://github.com/Koenkk/zigbee-herdsman/issues/82
1047
- if (endpoint !== 0 && !this.getEndpoint(endpoint)) {
1048
- this._endpoints.push(Endpoint.create(endpoint, undefined, undefined, [], [], this.networkAddress, this.ieeeAddr));
1049
- }
1050
- }
1051
-
1052
- // Remove disappeared endpoints (can happen with e.g. custom devices).
1053
- this._endpoints = this._endpoints.filter((e) => activeEndpoints.endpointList.includes(e.ID));
1054
- }
1055
-
1056
- /**
1057
- * Request device to advertise its network address.
1058
- * Note: This does not actually update the device property (if needed), as this is already done with `zdoResponse` event in Controller.
1059
- */
1060
- public async requestNetworkAddress(): Promise<void> {
1061
- const clusterId = Zdo.ClusterId.NETWORK_ADDRESS_REQUEST;
1062
- const zdoPayload = Zdo.Buffalo.buildRequest(Entity.adapter.hasZdoMessageOverhead, clusterId, this.ieeeAddr as Eui64, false, 0);
1063
-
1064
- await Entity.adapter.sendZdo(this.ieeeAddr, ZSpec.BroadcastAddress.RX_ON_WHEN_IDLE, clusterId, zdoPayload, true);
1065
- }
1066
-
1067
- public async removeFromNetwork(): Promise<void> {
1068
- if (this._type === "GreenPower") {
1069
- const payload = {
1070
- options: 0x002550,
1071
- srcID: Number(this.ieeeAddr),
1072
- };
1073
- const frame = Zcl.Frame.create(
1074
- Zcl.FrameType.SPECIFIC,
1075
- Zcl.Direction.SERVER_TO_CLIENT,
1076
- true,
1077
- undefined,
1078
- zclTransactionSequenceNumber.next(),
1079
- "pairing",
1080
- 33,
1081
- payload,
1082
- this.customClusters,
1083
- );
1084
-
1085
- await Entity.adapter.sendZclFrameToAll(242, frame, 242, BroadcastAddress.RX_ON_WHEN_IDLE);
1086
- } else {
1087
- const clusterId = Zdo.ClusterId.LEAVE_REQUEST;
1088
- const zdoPayload = Zdo.Buffalo.buildRequest(
1089
- Entity.adapter.hasZdoMessageOverhead,
1090
- clusterId,
1091
- this.ieeeAddr as Eui64,
1092
- Zdo.LeaveRequestFlags.WITHOUT_REJOIN,
1093
- );
1094
- const response = await Entity.adapter.sendZdo(this.ieeeAddr, this.networkAddress, clusterId, zdoPayload, false);
1095
-
1096
- if (!Zdo.Buffalo.checkStatus<Zdo.ClusterId.LEAVE_RESPONSE>(response)) {
1097
- throw new Zdo.StatusError(response[0]);
1098
- }
1099
- }
1100
-
1101
- this.removeFromDatabase();
1102
- }
1103
-
1104
- public removeFromDatabase(): void {
1105
- Device.loadFromDatabaseIfNecessary();
1106
-
1107
- for (const endpoint of this.endpoints) {
1108
- endpoint.removeFromAllGroupsDatabase();
1109
- }
1110
-
1111
- if (Entity.database.has(this.ID)) {
1112
- Entity.database.remove(this.ID);
1113
- }
1114
-
1115
- Device.deletedDevices.set(this.ieeeAddr, this);
1116
- Device.devices.delete(this.ieeeAddr);
1117
-
1118
- // Clear all data in case device joins again
1119
- // Green power devices are never interviewed, keep existing interview state.
1120
- this._interviewState = this.type === "GreenPower" ? this._interviewState : InterviewState.Pending;
1121
- this.meta = {};
1122
- const newEndpoints: Endpoint[] = [];
1123
- for (const endpoint of this.endpoints) {
1124
- newEndpoints.push(
1125
- Endpoint.create(
1126
- endpoint.ID,
1127
- endpoint.profileID,
1128
- endpoint.deviceID,
1129
- endpoint.inputClusters,
1130
- endpoint.outputClusters,
1131
- this.networkAddress,
1132
- this.ieeeAddr,
1133
- ),
1134
- );
1135
- }
1136
- this._endpoints = newEndpoints;
1137
- }
1138
-
1139
- public async lqi(): Promise<Lqi> {
1140
- const clusterId = Zdo.ClusterId.LQI_TABLE_REQUEST;
1141
- // TODO return Zdo.LQITableEntry directly (requires updates in other repos)
1142
- const neighbors: LQINeighbor[] = [];
1143
- const request = async (startIndex: number): Promise<[tableEntries: number, entryCount: number]> => {
1144
- const zdoPayload = Zdo.Buffalo.buildRequest(Entity.adapter.hasZdoMessageOverhead, clusterId, startIndex);
1145
- const response = await Entity.adapter.sendZdo(this.ieeeAddr, this.networkAddress, clusterId, zdoPayload, false);
1146
-
1147
- if (!Zdo.Buffalo.checkStatus<Zdo.ClusterId.LQI_TABLE_RESPONSE>(response)) {
1148
- throw new Zdo.StatusError(response[0]);
1149
- }
1150
-
1151
- const result = response[1];
1152
-
1153
- for (const entry of result.entryList) {
1154
- neighbors.push({
1155
- ieeeAddr: entry.eui64,
1156
- networkAddress: entry.nwkAddress,
1157
- linkquality: entry.lqi,
1158
- relationship: entry.relationship,
1159
- depth: entry.depth,
1160
- });
1161
- }
1162
-
1163
- return [result.neighborTableEntries, result.entryList.length];
1164
- };
1165
-
1166
- let [tableEntries, entryCount] = await request(0);
1167
-
1168
- const size = tableEntries;
1169
- let nextStartIndex = entryCount;
1170
-
1171
- while (neighbors.length < size) {
1172
- [tableEntries, entryCount] = await request(nextStartIndex);
1173
-
1174
- nextStartIndex += entryCount;
1175
- }
1176
-
1177
- return {neighbors};
1178
- }
1179
-
1180
- public async routingTable(): Promise<RoutingTable> {
1181
- const clusterId = Zdo.ClusterId.ROUTING_TABLE_REQUEST;
1182
- // TODO return Zdo.RoutingTableEntry directly (requires updates in other repos)
1183
- const table: RoutingTableEntry[] = [];
1184
- const request = async (startIndex: number): Promise<[tableEntries: number, entryCount: number]> => {
1185
- const zdoPayload = Zdo.Buffalo.buildRequest(Entity.adapter.hasZdoMessageOverhead, clusterId, startIndex);
1186
- const response = await Entity.adapter.sendZdo(this.ieeeAddr, this.networkAddress, clusterId, zdoPayload, false);
1187
-
1188
- if (!Zdo.Buffalo.checkStatus<Zdo.ClusterId.ROUTING_TABLE_RESPONSE>(response)) {
1189
- throw new Zdo.StatusError(response[0]);
1190
- }
1191
-
1192
- const result = response[1];
1193
-
1194
- for (const entry of result.entryList) {
1195
- table.push({
1196
- destinationAddress: entry.destinationAddress,
1197
- status: entry.status,
1198
- nextHop: entry.nextHopAddress,
1199
- });
1200
- }
1201
-
1202
- return [result.routingTableEntries, result.entryList.length];
1203
- };
1204
-
1205
- let [tableEntries, entryCount] = await request(0);
1206
-
1207
- const size = tableEntries;
1208
- let nextStartIndex = entryCount;
1209
-
1210
- while (table.length < size) {
1211
- [tableEntries, entryCount] = await request(nextStartIndex);
1212
-
1213
- nextStartIndex += entryCount;
1214
- }
1215
-
1216
- return {table};
1217
- }
1218
-
1219
- public async ping(disableRecovery = true): Promise<void> {
1220
- // Zigbee does not have an official pinging mechanism. Use a read request
1221
- // of a mandatory basic cluster attribute to keep it as lightweight as
1222
- // possible.
1223
- const endpoint = this.endpoints.find((ep) => ep.inputClusters.includes(0)) ?? this.endpoints[0];
1224
- await endpoint.read("genBasic", ["zclVersion"], {disableRecovery});
1225
- }
1226
-
1227
- public addCustomCluster(name: string, cluster: ClusterDefinition): void {
1228
- assert(
1229
- ![Zcl.Clusters.touchlink.ID, Zcl.Clusters.greenPower.ID].includes(cluster.ID),
1230
- "Overriding of greenPower or touchlink cluster is not supported",
1231
- );
1232
- if (Zcl.Utils.isClusterName(name)) {
1233
- const existingCluster = Zcl.Clusters[name];
1234
-
1235
- // Extend existing cluster
1236
- assert(existingCluster.ID === cluster.ID, `Custom cluster ID (${cluster.ID}) should match existing cluster ID (${existingCluster.ID})`);
1237
- cluster = {
1238
- ID: cluster.ID,
1239
- manufacturerCode: cluster.manufacturerCode,
1240
- attributes: {...existingCluster.attributes, ...cluster.attributes},
1241
- commands: {...existingCluster.commands, ...cluster.commands},
1242
- commandsResponse: {...existingCluster.commandsResponse, ...cluster.commandsResponse},
1243
- };
1244
- }
1245
- this._customClusters[name] = cluster;
1246
- }
1247
- }
1248
-
1249
- export default Device;