zigbee-herdsman 6.0.1 → 6.0.3

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 (260) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/adapter/ezsp/driver/uart.js +1 -1
  3. package/dist/adapter/ezsp/driver/uart.js.map +1 -1
  4. package/dist/adapter/z-stack/adapter/zStackAdapter.js +4 -4
  5. package/dist/adapter/z-stack/adapter/zStackAdapter.js.map +1 -1
  6. package/dist/adapter/zigate/adapter/zigateAdapter.js +4 -4
  7. package/dist/adapter/zigate/adapter/zigateAdapter.js.map +1 -1
  8. package/dist/controller/model/device.d.ts.map +1 -1
  9. package/dist/controller/model/device.js +1 -0
  10. package/dist/controller/model/device.js.map +1 -1
  11. package/package.json +14 -6
  12. package/.github/ISSUE_TEMPLATE/config.yml +0 -5
  13. package/.github/dependabot.yml +0 -22
  14. package/.github/workflows/ci.yml +0 -64
  15. package/.github/workflows/release-please.yml +0 -18
  16. package/.github/workflows/stale.yml +0 -20
  17. package/.github/workflows/typedoc.yaml +0 -47
  18. package/.release-please-manifest.json +0 -3
  19. package/.vscode/extensions.json +0 -3
  20. package/.vscode/settings.json +0 -11
  21. package/biome.json +0 -98
  22. package/examples/join-and-log.js +0 -24
  23. package/release-please-config.json +0 -9
  24. package/src/adapter/adapter.ts +0 -189
  25. package/src/adapter/adapterDiscovery.ts +0 -666
  26. package/src/adapter/const.ts +0 -12
  27. package/src/adapter/deconz/adapter/deconzAdapter.ts +0 -877
  28. package/src/adapter/deconz/driver/constants.ts +0 -246
  29. package/src/adapter/deconz/driver/driver.ts +0 -1540
  30. package/src/adapter/deconz/driver/frame.ts +0 -11
  31. package/src/adapter/deconz/driver/frameParser.ts +0 -753
  32. package/src/adapter/deconz/driver/parser.ts +0 -45
  33. package/src/adapter/deconz/driver/writer.ts +0 -22
  34. package/src/adapter/deconz/types.d.ts +0 -13
  35. package/src/adapter/ember/adapter/emberAdapter.ts +0 -2265
  36. package/src/adapter/ember/adapter/endpoints.ts +0 -86
  37. package/src/adapter/ember/adapter/oneWaitress.ts +0 -324
  38. package/src/adapter/ember/adapter/tokensManager.ts +0 -782
  39. package/src/adapter/ember/consts.ts +0 -178
  40. package/src/adapter/ember/enums.ts +0 -1746
  41. package/src/adapter/ember/ezsp/buffalo.ts +0 -1392
  42. package/src/adapter/ember/ezsp/consts.ts +0 -148
  43. package/src/adapter/ember/ezsp/enums.ts +0 -1114
  44. package/src/adapter/ember/ezsp/ezsp.ts +0 -9061
  45. package/src/adapter/ember/ezspError.ts +0 -10
  46. package/src/adapter/ember/types.ts +0 -866
  47. package/src/adapter/ember/uart/ash.ts +0 -1960
  48. package/src/adapter/ember/uart/consts.ts +0 -109
  49. package/src/adapter/ember/uart/enums.ts +0 -192
  50. package/src/adapter/ember/uart/parser.ts +0 -48
  51. package/src/adapter/ember/uart/queues.ts +0 -247
  52. package/src/adapter/ember/uart/writer.ts +0 -53
  53. package/src/adapter/ember/utils/initters.ts +0 -58
  54. package/src/adapter/ember/utils/math.ts +0 -73
  55. package/src/adapter/events.ts +0 -21
  56. package/src/adapter/ezsp/adapter/backup.ts +0 -109
  57. package/src/adapter/ezsp/adapter/ezspAdapter.ts +0 -614
  58. package/src/adapter/ezsp/driver/commands.ts +0 -2497
  59. package/src/adapter/ezsp/driver/consts.ts +0 -11
  60. package/src/adapter/ezsp/driver/driver.ts +0 -1002
  61. package/src/adapter/ezsp/driver/ezsp.ts +0 -802
  62. package/src/adapter/ezsp/driver/frame.ts +0 -101
  63. package/src/adapter/ezsp/driver/index.ts +0 -4
  64. package/src/adapter/ezsp/driver/multicast.ts +0 -78
  65. package/src/adapter/ezsp/driver/parser.ts +0 -81
  66. package/src/adapter/ezsp/driver/types/basic.ts +0 -201
  67. package/src/adapter/ezsp/driver/types/index.ts +0 -239
  68. package/src/adapter/ezsp/driver/types/named.ts +0 -2330
  69. package/src/adapter/ezsp/driver/types/struct.ts +0 -844
  70. package/src/adapter/ezsp/driver/uart.ts +0 -460
  71. package/src/adapter/ezsp/driver/utils/crc16ccitt.ts +0 -44
  72. package/src/adapter/ezsp/driver/utils/index.ts +0 -32
  73. package/src/adapter/ezsp/driver/writer.ts +0 -64
  74. package/src/adapter/index.ts +0 -3
  75. package/src/adapter/serialPort.ts +0 -58
  76. package/src/adapter/socketPortUtils.ts +0 -16
  77. package/src/adapter/tstype.ts +0 -78
  78. package/src/adapter/z-stack/adapter/adapter-backup.ts +0 -519
  79. package/src/adapter/z-stack/adapter/adapter-nv-memory.ts +0 -457
  80. package/src/adapter/z-stack/adapter/endpoints.ts +0 -57
  81. package/src/adapter/z-stack/adapter/manager.ts +0 -543
  82. package/src/adapter/z-stack/adapter/tstype.ts +0 -6
  83. package/src/adapter/z-stack/adapter/zStackAdapter.ts +0 -1190
  84. package/src/adapter/z-stack/constants/af.ts +0 -27
  85. package/src/adapter/z-stack/constants/common.ts +0 -285
  86. package/src/adapter/z-stack/constants/dbg.ts +0 -23
  87. package/src/adapter/z-stack/constants/index.ts +0 -11
  88. package/src/adapter/z-stack/constants/mac.ts +0 -128
  89. package/src/adapter/z-stack/constants/sapi.ts +0 -25
  90. package/src/adapter/z-stack/constants/sys.ts +0 -72
  91. package/src/adapter/z-stack/constants/util.ts +0 -82
  92. package/src/adapter/z-stack/constants/utils.ts +0 -14
  93. package/src/adapter/z-stack/constants/zdo.ts +0 -103
  94. package/src/adapter/z-stack/models/startup-options.ts +0 -13
  95. package/src/adapter/z-stack/structs/entries/address-manager-entry.ts +0 -44
  96. package/src/adapter/z-stack/structs/entries/address-manager-table.ts +0 -19
  97. package/src/adapter/z-stack/structs/entries/aps-link-key-data-entry.ts +0 -12
  98. package/src/adapter/z-stack/structs/entries/aps-link-key-data-table.ts +0 -21
  99. package/src/adapter/z-stack/structs/entries/aps-tc-link-key-entry.ts +0 -19
  100. package/src/adapter/z-stack/structs/entries/aps-tc-link-key-table.ts +0 -21
  101. package/src/adapter/z-stack/structs/entries/channel-list.ts +0 -8
  102. package/src/adapter/z-stack/structs/entries/has-configured.ts +0 -16
  103. package/src/adapter/z-stack/structs/entries/index.ts +0 -16
  104. package/src/adapter/z-stack/structs/entries/nib.ts +0 -66
  105. package/src/adapter/z-stack/structs/entries/nwk-key-descriptor.ts +0 -15
  106. package/src/adapter/z-stack/structs/entries/nwk-key.ts +0 -13
  107. package/src/adapter/z-stack/structs/entries/nwk-pan-id.ts +0 -8
  108. package/src/adapter/z-stack/structs/entries/nwk-sec-material-descriptor-entry.ts +0 -20
  109. package/src/adapter/z-stack/structs/entries/nwk-sec-material-descriptor-table.ts +0 -19
  110. package/src/adapter/z-stack/structs/entries/security-manager-entry.ts +0 -33
  111. package/src/adapter/z-stack/structs/entries/security-manager-table.ts +0 -22
  112. package/src/adapter/z-stack/structs/index.ts +0 -4
  113. package/src/adapter/z-stack/structs/serializable-memory-object.ts +0 -14
  114. package/src/adapter/z-stack/structs/struct.ts +0 -367
  115. package/src/adapter/z-stack/structs/table.ts +0 -198
  116. package/src/adapter/z-stack/unpi/constants.ts +0 -33
  117. package/src/adapter/z-stack/unpi/frame.ts +0 -62
  118. package/src/adapter/z-stack/unpi/index.ts +0 -4
  119. package/src/adapter/z-stack/unpi/parser.ts +0 -56
  120. package/src/adapter/z-stack/unpi/writer.ts +0 -21
  121. package/src/adapter/z-stack/utils/channel-list.ts +0 -40
  122. package/src/adapter/z-stack/utils/index.ts +0 -2
  123. package/src/adapter/z-stack/utils/network-options.ts +0 -26
  124. package/src/adapter/z-stack/znp/buffaloZnp.ts +0 -175
  125. package/src/adapter/z-stack/znp/definition.ts +0 -2713
  126. package/src/adapter/z-stack/znp/index.ts +0 -2
  127. package/src/adapter/z-stack/znp/parameterType.ts +0 -22
  128. package/src/adapter/z-stack/znp/tstype.ts +0 -44
  129. package/src/adapter/z-stack/znp/utils.ts +0 -10
  130. package/src/adapter/z-stack/znp/znp.ts +0 -342
  131. package/src/adapter/z-stack/znp/zpiObject.ts +0 -148
  132. package/src/adapter/zboss/adapter/zbossAdapter.ts +0 -526
  133. package/src/adapter/zboss/commands.ts +0 -1184
  134. package/src/adapter/zboss/consts.ts +0 -9
  135. package/src/adapter/zboss/driver.ts +0 -422
  136. package/src/adapter/zboss/enums.ts +0 -360
  137. package/src/adapter/zboss/frame.ts +0 -227
  138. package/src/adapter/zboss/reader.ts +0 -65
  139. package/src/adapter/zboss/types.ts +0 -0
  140. package/src/adapter/zboss/uart.ts +0 -428
  141. package/src/adapter/zboss/utils.ts +0 -58
  142. package/src/adapter/zboss/writer.ts +0 -49
  143. package/src/adapter/zigate/adapter/patchZdoBuffaloBE.ts +0 -27
  144. package/src/adapter/zigate/adapter/zigateAdapter.ts +0 -618
  145. package/src/adapter/zigate/driver/LICENSE +0 -17
  146. package/src/adapter/zigate/driver/buffaloZiGate.ts +0 -212
  147. package/src/adapter/zigate/driver/commandType.ts +0 -418
  148. package/src/adapter/zigate/driver/constants.ts +0 -150
  149. package/src/adapter/zigate/driver/frame.ts +0 -197
  150. package/src/adapter/zigate/driver/messageType.ts +0 -287
  151. package/src/adapter/zigate/driver/parameterType.ts +0 -32
  152. package/src/adapter/zigate/driver/ziGateObject.ts +0 -146
  153. package/src/adapter/zigate/driver/zigate.ts +0 -423
  154. package/src/adapter/zoh/adapter/utils.ts +0 -27
  155. package/src/adapter/zoh/adapter/zohAdapter.ts +0 -838
  156. package/src/buffalo/buffalo.ts +0 -342
  157. package/src/buffalo/index.ts +0 -1
  158. package/src/controller/controller.ts +0 -1022
  159. package/src/controller/database.ts +0 -124
  160. package/src/controller/events.ts +0 -52
  161. package/src/controller/greenPower.ts +0 -603
  162. package/src/controller/helpers/index.ts +0 -1
  163. package/src/controller/helpers/installCodes.ts +0 -107
  164. package/src/controller/helpers/request.ts +0 -96
  165. package/src/controller/helpers/requestQueue.ts +0 -125
  166. package/src/controller/helpers/zclFrameConverter.ts +0 -47
  167. package/src/controller/helpers/zclTransactionSequenceNumber.ts +0 -19
  168. package/src/controller/index.ts +0 -6
  169. package/src/controller/model/device.ts +0 -1248
  170. package/src/controller/model/endpoint.ts +0 -1105
  171. package/src/controller/model/entity.ts +0 -23
  172. package/src/controller/model/group.ts +0 -424
  173. package/src/controller/model/index.ts +0 -5
  174. package/src/controller/model/zigbeeEntity.ts +0 -30
  175. package/src/controller/touchlink.ts +0 -189
  176. package/src/controller/tstype.ts +0 -274
  177. package/src/index.ts +0 -12
  178. package/src/models/backup-storage-legacy.ts +0 -48
  179. package/src/models/backup-storage-unified.ts +0 -47
  180. package/src/models/backup.ts +0 -37
  181. package/src/models/index.ts +0 -5
  182. package/src/models/network-options.ts +0 -11
  183. package/src/utils/backup.ts +0 -152
  184. package/src/utils/index.ts +0 -5
  185. package/src/utils/logger.ts +0 -20
  186. package/src/utils/patchBigIntSerialization.ts +0 -8
  187. package/src/utils/queue.ts +0 -76
  188. package/src/utils/types.d.ts +0 -3
  189. package/src/utils/utils.ts +0 -19
  190. package/src/utils/wait.ts +0 -5
  191. package/src/utils/waitress.ts +0 -96
  192. package/src/zspec/consts.ts +0 -84
  193. package/src/zspec/enums.ts +0 -22
  194. package/src/zspec/index.ts +0 -3
  195. package/src/zspec/tstypes.ts +0 -18
  196. package/src/zspec/utils.ts +0 -247
  197. package/src/zspec/zcl/buffaloZcl.ts +0 -1220
  198. package/src/zspec/zcl/definition/cluster.ts +0 -5915
  199. package/src/zspec/zcl/definition/clusters-typegen.ts +0 -588
  200. package/src/zspec/zcl/definition/clusters-types.ts +0 -7331
  201. package/src/zspec/zcl/definition/consts.ts +0 -24
  202. package/src/zspec/zcl/definition/enums.ts +0 -203
  203. package/src/zspec/zcl/definition/foundation.ts +0 -329
  204. package/src/zspec/zcl/definition/manufacturerCode.ts +0 -729
  205. package/src/zspec/zcl/definition/status.ts +0 -69
  206. package/src/zspec/zcl/definition/tstype.ts +0 -377
  207. package/src/zspec/zcl/index.ts +0 -11
  208. package/src/zspec/zcl/utils.ts +0 -321
  209. package/src/zspec/zcl/zclFrame.ts +0 -356
  210. package/src/zspec/zcl/zclHeader.ts +0 -102
  211. package/src/zspec/zcl/zclStatusError.ts +0 -10
  212. package/src/zspec/zdo/buffaloZdo.ts +0 -2336
  213. package/src/zspec/zdo/definition/clusters.ts +0 -722
  214. package/src/zspec/zdo/definition/consts.ts +0 -16
  215. package/src/zspec/zdo/definition/enums.ts +0 -99
  216. package/src/zspec/zdo/definition/status.ts +0 -105
  217. package/src/zspec/zdo/definition/tstypes.ts +0 -1062
  218. package/src/zspec/zdo/index.ts +0 -7
  219. package/src/zspec/zdo/utils.ts +0 -76
  220. package/src/zspec/zdo/zdoStatusError.ts +0 -10
  221. package/test/adapter/adapter.test.ts +0 -1062
  222. package/test/adapter/ember/ash.test.ts +0 -337
  223. package/test/adapter/ember/consts.ts +0 -131
  224. package/test/adapter/ember/emberAdapter.test.ts +0 -3449
  225. package/test/adapter/ember/ezsp.test.ts +0 -385
  226. package/test/adapter/ember/ezspBuffalo.test.ts +0 -93
  227. package/test/adapter/ember/ezspError.test.ts +0 -12
  228. package/test/adapter/ember/math.test.ts +0 -206
  229. package/test/adapter/ezsp/frame.test.ts +0 -30
  230. package/test/adapter/ezsp/uart.test.ts +0 -181
  231. package/test/adapter/z-stack/adapter.test.ts +0 -3984
  232. package/test/adapter/z-stack/constants.test.ts +0 -33
  233. package/test/adapter/z-stack/structs.test.ts +0 -115
  234. package/test/adapter/z-stack/unpi.test.ts +0 -213
  235. package/test/adapter/z-stack/znp.test.ts +0 -1284
  236. package/test/adapter/zboss/fixZdoResponse.test.ts +0 -179
  237. package/test/adapter/zigate/patchZdoBuffaloBE.test.ts +0 -81
  238. package/test/adapter/zigate/zdo.test.ts +0 -187
  239. package/test/adapter/zoh/utils.test.ts +0 -36
  240. package/test/adapter/zoh/zohAdapter.test.ts +0 -1307
  241. package/test/buffalo.test.ts +0 -431
  242. package/test/controller.bench.ts +0 -193
  243. package/test/controller.test.ts +0 -8702
  244. package/test/greenpower.test.ts +0 -1408
  245. package/test/mockAdapters.ts +0 -65
  246. package/test/mockDevices.ts +0 -598
  247. package/test/requests.bench.ts +0 -206
  248. package/test/testUtils.ts +0 -20
  249. package/test/tsconfig.json +0 -9
  250. package/test/utils/math.ts +0 -19
  251. package/test/utils.test.ts +0 -279
  252. package/test/vitest.config.mts +0 -27
  253. package/test/zcl.test.ts +0 -2831
  254. package/test/zspec/utils.test.ts +0 -68
  255. package/test/zspec/zcl/buffalo.test.ts +0 -1374
  256. package/test/zspec/zcl/frame.test.ts +0 -960
  257. package/test/zspec/zcl/utils.test.ts +0 -273
  258. package/test/zspec/zdo/buffalo.test.ts +0 -1850
  259. package/test/zspec/zdo/utils.test.ts +0 -241
  260. package/tsconfig.json +0 -24
@@ -1,1248 +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
- };
794
-
795
- let match: string | undefined;
796
-
797
- for (const key in lookup) {
798
- if (this.modelID?.match(key)) {
799
- match = key;
800
- break;
801
- }
802
- }
803
-
804
- if (match) {
805
- const info = lookup[match];
806
- logger.debug(`Interview procedure failed but got modelID matching '${match}', assuming interview succeeded`, NS);
807
- this._type = this._type === "Unknown" && info.type ? info.type : this._type;
808
- this._manufacturerID = this._manufacturerID || info.manufacturerID;
809
- this.#genBasic.manufacturerName = this.#genBasic.manufacturerName || info.manufacturerName;
810
- this.#genBasic.powerSource = (this.#genBasic.powerSource || info.powerSource) /* v8 ignore next */ ?? Zcl.PowerSource.Unknown;
811
- logger.debug(`Interview - quirks matched on '${match}'`, NS);
812
- return true;
813
- }
814
-
815
- logger.debug("Interview - quirks did not match", NS);
816
- return false;
817
- }
818
-
819
- private async interviewInternal(ignoreCache: boolean): Promise<void> {
820
- const hasNodeDescriptor = (): boolean => this._manufacturerID !== undefined && this._type !== "Unknown";
821
-
822
- if (ignoreCache || !hasNodeDescriptor()) {
823
- for (let attempt = 0; attempt < 6; attempt++) {
824
- try {
825
- await this.updateNodeDescriptor();
826
- break;
827
- } catch (error) {
828
- if (this.interviewQuirks()) {
829
- logger.debug(`Interview - completed for device '${this.ieeeAddr}' because of quirks ('${error}')`, NS);
830
- return;
831
- }
832
-
833
- // Most of the times the first node descriptor query fails and the seconds one succeeds.
834
- logger.debug(`Interview - node descriptor request failed for '${this.ieeeAddr}', attempt ${attempt + 1}`, NS);
835
- }
836
- }
837
- } else {
838
- logger.debug(`Interview - skip node descriptor request for '${this.ieeeAddr}', already got it`, NS);
839
- }
840
-
841
- if (!hasNodeDescriptor()) {
842
- throw new Error(`Interview failed because can not get node descriptor ('${this.ieeeAddr}')`);
843
- }
844
-
845
- if (this.manufacturerID === 4619 && this._type === "EndDevice") {
846
- // Give Tuya end device some time to pair. Otherwise they leave immediately.
847
- // https://github.com/Koenkk/zigbee2mqtt/issues/5814
848
- logger.debug("Interview - Detected Tuya end device, waiting 10 seconds...", NS);
849
- await wait(10000);
850
- } else if (this.manufacturerID === 0 || this.manufacturerID === 4098) {
851
- // Potentially a Tuya device, some sleep fast so make sure to read the modelId and manufacturerName quickly.
852
- // In case the device responds, the endoint and modelID/manufacturerName are set
853
- // in controller.onZclOrRawData()
854
- // https://github.com/Koenkk/zigbee2mqtt/issues/7553
855
- logger.debug("Interview - Detected potential Tuya end device, reading modelID and manufacturerName...", NS);
856
- try {
857
- const endpoint = Endpoint.create(1, undefined, undefined, [], [], this.networkAddress, this.ieeeAddr);
858
- const result = await endpoint.read("genBasic", ["modelId", "manufacturerName"], {sendPolicy: "immediate"});
859
-
860
- this.updateGenBasic(result);
861
- } catch (error) {
862
- logger.debug(`Interview - Tuya read modelID and manufacturerName failed (${error})`, NS);
863
- }
864
- }
865
-
866
- // e.g. Xiaomi Aqara Opple devices fail to respond to the first active endpoints request, therefore try 2 times
867
- // https://github.com/Koenkk/zigbee-herdsman/pull/103
868
- let gotActiveEndpoints = false;
869
-
870
- for (let attempt = 0; attempt < 2; attempt++) {
871
- try {
872
- await this.updateActiveEndpoints();
873
- gotActiveEndpoints = true;
874
- break;
875
- } catch (error) {
876
- logger.debug(`Interview - active endpoints request failed for '${this.ieeeAddr}', attempt ${attempt + 1} (${error})`, NS);
877
- }
878
- }
879
-
880
- if (!gotActiveEndpoints) {
881
- throw new Error(`Interview failed because can not get active endpoints ('${this.ieeeAddr}')`);
882
- }
883
-
884
- logger.debug(`Interview - got active endpoints for device '${this.ieeeAddr}'`, NS);
885
-
886
- const coordinator = Device.byType("Coordinator")[0];
887
-
888
- for (const endpoint of this._endpoints) {
889
- await endpoint.updateSimpleDescriptor();
890
- logger.debug(`Interview - got simple descriptor for endpoint '${endpoint.ID}' device '${this.ieeeAddr}'`, NS);
891
-
892
- // Read attributes
893
- // nice to have but not required for successful pairing as most of the attributes are not mandatory in ZCL specification
894
- if (endpoint.supportsInputCluster("genBasic")) {
895
- for (const key of INTERVIEW_GENBASIC_ATTRIBUTES) {
896
- if (ignoreCache || !this.#genBasic[key]) {
897
- try {
898
- let result: TPartialClusterAttributes<"genBasic">;
899
-
900
- try {
901
- result = await endpoint.read("genBasic", [key], {sendPolicy: "immediate"});
902
- } catch (error) {
903
- // Reading attributes can fail for many reason, e.g. it could be that device rejoins
904
- // while joining like in:
905
- // https://github.com/Koenkk/zigbee-herdsman-converters/issues/2485.
906
- // The modelID and manufacturerName are crucial for device identification, so retry.
907
- if (key === "modelId" || key === "manufacturerName") {
908
- logger.debug(`Interview - first ${key} retrieval attempt failed, retrying after 10 seconds...`, NS);
909
- await wait(10000);
910
- result = await endpoint.read("genBasic", [key], {sendPolicy: "immediate"});
911
- } else {
912
- throw error;
913
- }
914
- }
915
-
916
- this.updateGenBasic(result);
917
- logger.debug(`Interview - got '${key}' for device '${this.ieeeAddr}'`, NS);
918
- } catch (error) {
919
- logger.debug(`Interview - failed to read attribute '${key}' from endpoint '${endpoint.ID}' (${error})`, NS);
920
- }
921
- }
922
- }
923
- }
924
-
925
- // Enroll IAS device
926
- if (endpoint.supportsInputCluster("ssIasZone")) {
927
- logger.debug(`Interview - IAS - enrolling '${this.ieeeAddr}' endpoint '${endpoint.ID}'`, NS);
928
-
929
- const stateBefore = await endpoint.read("ssIasZone", ["iasCieAddr", "zoneState"], {sendPolicy: "immediate"});
930
- logger.debug(`Interview - IAS - before enrolling state: '${JSON.stringify(stateBefore)}'`, NS);
931
-
932
- // Do not enroll when device has already been enrolled
933
- if (stateBefore.zoneState !== 1 || stateBefore.iasCieAddr !== coordinator.ieeeAddr) {
934
- logger.debug("Interview - IAS - not enrolled, enrolling", NS);
935
-
936
- await endpoint.write("ssIasZone", {iasCieAddr: coordinator.ieeeAddr}, {sendPolicy: "immediate"});
937
- logger.debug("Interview - IAS - wrote iasCieAddr", NS);
938
-
939
- // There are 2 enrollment procedures:
940
- // - Auto enroll: coordinator has to send enrollResponse without receiving an enroll request
941
- // this case is handled below.
942
- // - Manual enroll: coordinator replies to enroll request with an enroll response.
943
- // this case in hanled in onZclData().
944
- // https://github.com/Koenkk/zigbee2mqtt/issues/4569#issuecomment-706075676
945
- await wait(500);
946
- logger.debug(`IAS - '${this.ieeeAddr}' sending enroll response (auto enroll)`, NS);
947
- const payload = {enrollrspcode: 0, zoneid: 23};
948
- await endpoint.command("ssIasZone", "enrollRsp", payload, {disableDefaultResponse: true, sendPolicy: "immediate"});
949
-
950
- let enrolled = false;
951
- for (let attempt = 0; attempt < 20; attempt++) {
952
- await wait(500);
953
- const stateAfter = await endpoint.read("ssIasZone", ["iasCieAddr", "zoneState"], {sendPolicy: "immediate"});
954
- logger.debug(`Interview - IAS - after enrolling state (${attempt}): '${JSON.stringify(stateAfter)}'`, NS);
955
- if (stateAfter.zoneState === 1) {
956
- enrolled = true;
957
- break;
958
- }
959
- }
960
-
961
- if (enrolled) {
962
- logger.debug(`Interview - IAS successfully enrolled '${this.ieeeAddr}' endpoint '${endpoint.ID}'`, NS);
963
- } else {
964
- throw new Error(`Interview failed because of failed IAS enroll (zoneState didn't change ('${this.ieeeAddr}')`);
965
- }
966
- } else {
967
- logger.debug("Interview - IAS - already enrolled, skipping enroll", NS);
968
- }
969
- }
970
- }
971
-
972
- // Bind poll control
973
- try {
974
- for (const endpoint of this.endpoints.filter((e): boolean => e.supportsInputCluster("genPollCtrl"))) {
975
- logger.debug(`Interview - Poll control - binding '${this.ieeeAddr}' endpoint '${endpoint.ID}'`, NS);
976
- await endpoint.bind("genPollCtrl", coordinator.endpoints[0]);
977
- const pollPeriod = await endpoint.read("genPollCtrl", ["checkinInterval"], {sendPolicy: "immediate"});
978
- this._checkinInterval = pollPeriod.checkinInterval / 4; // convert to seconds
979
- this.resetPendingRequestTimeout();
980
- }
981
- /* v8 ignore start */
982
- } catch (error) {
983
- logger.debug(`Interview - failed to bind genPollCtrl (${error})`, NS);
984
- }
985
- /* v8 ignore stop */
986
- }
987
-
988
- public async updateNodeDescriptor(): Promise<void> {
989
- const clusterId = Zdo.ClusterId.NODE_DESCRIPTOR_REQUEST;
990
- const zdoPayload = Zdo.Buffalo.buildRequest(Entity.adapter.hasZdoMessageOverhead, clusterId, this.networkAddress);
991
- const response = await Entity.adapter.sendZdo(this.ieeeAddr, this.networkAddress, clusterId, zdoPayload, false);
992
-
993
- if (!Zdo.Buffalo.checkStatus<Zdo.ClusterId.NODE_DESCRIPTOR_RESPONSE>(response)) {
994
- throw new Zdo.StatusError(response[0]);
995
- }
996
-
997
- // TODO: make use of: capabilities.rxOnWhenIdle, maxIncTxSize, maxOutTxSize, serverMask.stackComplianceRevision
998
- const nodeDescriptor = response[1];
999
- this._manufacturerID = nodeDescriptor.manufacturerCode;
1000
-
1001
- switch (nodeDescriptor.logicalType) {
1002
- case 0x0:
1003
- this._type = "Coordinator";
1004
- break;
1005
- case 0x1:
1006
- this._type = "Router";
1007
- break;
1008
- case 0x2:
1009
- this._type = "EndDevice";
1010
- break;
1011
- }
1012
-
1013
- logger.debug(`Interview - got node descriptor for device '${this.ieeeAddr}'`, NS);
1014
-
1015
- // TODO: define a property on Device for this value (would be good to have it displayed)
1016
- // log for devices older than 1 from current revision
1017
- if (nodeDescriptor.serverMask.stackComplianceRevision < ZSpec.ZIGBEE_REVISION - 1) {
1018
- // always 0 before revision 21 where field was added
1019
- const rev = nodeDescriptor.serverMask.stackComplianceRevision < 21 ? "pre-21" : nodeDescriptor.serverMask.stackComplianceRevision;
1020
-
1021
- logger.info(
1022
- `Device '${this.ieeeAddr}' is only compliant to revision '${rev}' of the ZigBee specification (current revision: ${ZSpec.ZIGBEE_REVISION}).`,
1023
- NS,
1024
- );
1025
- }
1026
- }
1027
-
1028
- public async updateActiveEndpoints(): Promise<void> {
1029
- const clusterId = Zdo.ClusterId.ACTIVE_ENDPOINTS_REQUEST;
1030
- const zdoPayload = Zdo.Buffalo.buildRequest(Entity.adapter.hasZdoMessageOverhead, clusterId, this.networkAddress);
1031
-
1032
- const response = await Entity.adapter.sendZdo(this.ieeeAddr, this.networkAddress, clusterId, zdoPayload, false);
1033
-
1034
- if (!Zdo.Buffalo.checkStatus<Zdo.ClusterId.ACTIVE_ENDPOINTS_RESPONSE>(response)) {
1035
- throw new Zdo.StatusError(response[0]);
1036
- }
1037
-
1038
- const activeEndpoints = response[1];
1039
-
1040
- // Make sure that the endpoint are sorted.
1041
- activeEndpoints.endpointList.sort((a, b) => a - b);
1042
- for (const endpoint of activeEndpoints.endpointList) {
1043
- // Some devices, e.g. TERNCY return endpoint 0 in the active endpoints request.
1044
- // This is not a valid endpoint number according to the ZCL, requesting a simple descriptor will result
1045
- // into an error. Therefore we filter it, more info: https://github.com/Koenkk/zigbee-herdsman/issues/82
1046
- if (endpoint !== 0 && !this.getEndpoint(endpoint)) {
1047
- this._endpoints.push(Endpoint.create(endpoint, undefined, undefined, [], [], this.networkAddress, this.ieeeAddr));
1048
- }
1049
- }
1050
-
1051
- // Remove disappeared endpoints (can happen with e.g. custom devices).
1052
- this._endpoints = this._endpoints.filter((e) => activeEndpoints.endpointList.includes(e.ID));
1053
- }
1054
-
1055
- /**
1056
- * Request device to advertise its network address.
1057
- * Note: This does not actually update the device property (if needed), as this is already done with `zdoResponse` event in Controller.
1058
- */
1059
- public async requestNetworkAddress(): Promise<void> {
1060
- const clusterId = Zdo.ClusterId.NETWORK_ADDRESS_REQUEST;
1061
- const zdoPayload = Zdo.Buffalo.buildRequest(Entity.adapter.hasZdoMessageOverhead, clusterId, this.ieeeAddr as Eui64, false, 0);
1062
-
1063
- await Entity.adapter.sendZdo(this.ieeeAddr, ZSpec.BroadcastAddress.RX_ON_WHEN_IDLE, clusterId, zdoPayload, true);
1064
- }
1065
-
1066
- public async removeFromNetwork(): Promise<void> {
1067
- if (this._type === "GreenPower") {
1068
- const payload = {
1069
- options: 0x002550,
1070
- srcID: Number(this.ieeeAddr),
1071
- };
1072
- const frame = Zcl.Frame.create(
1073
- Zcl.FrameType.SPECIFIC,
1074
- Zcl.Direction.SERVER_TO_CLIENT,
1075
- true,
1076
- undefined,
1077
- zclTransactionSequenceNumber.next(),
1078
- "pairing",
1079
- 33,
1080
- payload,
1081
- this.customClusters,
1082
- );
1083
-
1084
- await Entity.adapter.sendZclFrameToAll(242, frame, 242, BroadcastAddress.RX_ON_WHEN_IDLE);
1085
- } else {
1086
- const clusterId = Zdo.ClusterId.LEAVE_REQUEST;
1087
- const zdoPayload = Zdo.Buffalo.buildRequest(
1088
- Entity.adapter.hasZdoMessageOverhead,
1089
- clusterId,
1090
- this.ieeeAddr as Eui64,
1091
- Zdo.LeaveRequestFlags.WITHOUT_REJOIN,
1092
- );
1093
- const response = await Entity.adapter.sendZdo(this.ieeeAddr, this.networkAddress, clusterId, zdoPayload, false);
1094
-
1095
- if (!Zdo.Buffalo.checkStatus<Zdo.ClusterId.LEAVE_RESPONSE>(response)) {
1096
- throw new Zdo.StatusError(response[0]);
1097
- }
1098
- }
1099
-
1100
- this.removeFromDatabase();
1101
- }
1102
-
1103
- public removeFromDatabase(): void {
1104
- Device.loadFromDatabaseIfNecessary();
1105
-
1106
- for (const endpoint of this.endpoints) {
1107
- endpoint.removeFromAllGroupsDatabase();
1108
- }
1109
-
1110
- if (Entity.database.has(this.ID)) {
1111
- Entity.database.remove(this.ID);
1112
- }
1113
-
1114
- Device.deletedDevices.set(this.ieeeAddr, this);
1115
- Device.devices.delete(this.ieeeAddr);
1116
-
1117
- // Clear all data in case device joins again
1118
- // Green power devices are never interviewed, keep existing interview state.
1119
- this._interviewState = this.type === "GreenPower" ? this._interviewState : InterviewState.Pending;
1120
- this.meta = {};
1121
- const newEndpoints: Endpoint[] = [];
1122
- for (const endpoint of this.endpoints) {
1123
- newEndpoints.push(
1124
- Endpoint.create(
1125
- endpoint.ID,
1126
- endpoint.profileID,
1127
- endpoint.deviceID,
1128
- endpoint.inputClusters,
1129
- endpoint.outputClusters,
1130
- this.networkAddress,
1131
- this.ieeeAddr,
1132
- ),
1133
- );
1134
- }
1135
- this._endpoints = newEndpoints;
1136
- }
1137
-
1138
- public async lqi(): Promise<Lqi> {
1139
- const clusterId = Zdo.ClusterId.LQI_TABLE_REQUEST;
1140
- // TODO return Zdo.LQITableEntry directly (requires updates in other repos)
1141
- const neighbors: LQINeighbor[] = [];
1142
- const request = async (startIndex: number): Promise<[tableEntries: number, entryCount: number]> => {
1143
- const zdoPayload = Zdo.Buffalo.buildRequest(Entity.adapter.hasZdoMessageOverhead, clusterId, startIndex);
1144
- const response = await Entity.adapter.sendZdo(this.ieeeAddr, this.networkAddress, clusterId, zdoPayload, false);
1145
-
1146
- if (!Zdo.Buffalo.checkStatus<Zdo.ClusterId.LQI_TABLE_RESPONSE>(response)) {
1147
- throw new Zdo.StatusError(response[0]);
1148
- }
1149
-
1150
- const result = response[1];
1151
-
1152
- for (const entry of result.entryList) {
1153
- neighbors.push({
1154
- ieeeAddr: entry.eui64,
1155
- networkAddress: entry.nwkAddress,
1156
- linkquality: entry.lqi,
1157
- relationship: entry.relationship,
1158
- depth: entry.depth,
1159
- });
1160
- }
1161
-
1162
- return [result.neighborTableEntries, result.entryList.length];
1163
- };
1164
-
1165
- let [tableEntries, entryCount] = await request(0);
1166
-
1167
- const size = tableEntries;
1168
- let nextStartIndex = entryCount;
1169
-
1170
- while (neighbors.length < size) {
1171
- [tableEntries, entryCount] = await request(nextStartIndex);
1172
-
1173
- nextStartIndex += entryCount;
1174
- }
1175
-
1176
- return {neighbors};
1177
- }
1178
-
1179
- public async routingTable(): Promise<RoutingTable> {
1180
- const clusterId = Zdo.ClusterId.ROUTING_TABLE_REQUEST;
1181
- // TODO return Zdo.RoutingTableEntry directly (requires updates in other repos)
1182
- const table: RoutingTableEntry[] = [];
1183
- const request = async (startIndex: number): Promise<[tableEntries: number, entryCount: number]> => {
1184
- const zdoPayload = Zdo.Buffalo.buildRequest(Entity.adapter.hasZdoMessageOverhead, clusterId, startIndex);
1185
- const response = await Entity.adapter.sendZdo(this.ieeeAddr, this.networkAddress, clusterId, zdoPayload, false);
1186
-
1187
- if (!Zdo.Buffalo.checkStatus<Zdo.ClusterId.ROUTING_TABLE_RESPONSE>(response)) {
1188
- throw new Zdo.StatusError(response[0]);
1189
- }
1190
-
1191
- const result = response[1];
1192
-
1193
- for (const entry of result.entryList) {
1194
- table.push({
1195
- destinationAddress: entry.destinationAddress,
1196
- status: entry.status,
1197
- nextHop: entry.nextHopAddress,
1198
- });
1199
- }
1200
-
1201
- return [result.routingTableEntries, result.entryList.length];
1202
- };
1203
-
1204
- let [tableEntries, entryCount] = await request(0);
1205
-
1206
- const size = tableEntries;
1207
- let nextStartIndex = entryCount;
1208
-
1209
- while (table.length < size) {
1210
- [tableEntries, entryCount] = await request(nextStartIndex);
1211
-
1212
- nextStartIndex += entryCount;
1213
- }
1214
-
1215
- return {table};
1216
- }
1217
-
1218
- public async ping(disableRecovery = true): Promise<void> {
1219
- // Zigbee does not have an official pinging mechanism. Use a read request
1220
- // of a mandatory basic cluster attribute to keep it as lightweight as
1221
- // possible.
1222
- const endpoint = this.endpoints.find((ep) => ep.inputClusters.includes(0)) ?? this.endpoints[0];
1223
- await endpoint.read("genBasic", ["zclVersion"], {disableRecovery});
1224
- }
1225
-
1226
- public addCustomCluster(name: string, cluster: ClusterDefinition): void {
1227
- assert(
1228
- ![Zcl.Clusters.touchlink.ID, Zcl.Clusters.greenPower.ID].includes(cluster.ID),
1229
- "Overriding of greenPower or touchlink cluster is not supported",
1230
- );
1231
- if (Zcl.Utils.isClusterName(name)) {
1232
- const existingCluster = Zcl.Clusters[name];
1233
-
1234
- // Extend existing cluster
1235
- assert(existingCluster.ID === cluster.ID, `Custom cluster ID (${cluster.ID}) should match existing cluster ID (${existingCluster.ID})`);
1236
- cluster = {
1237
- ID: cluster.ID,
1238
- manufacturerCode: cluster.manufacturerCode,
1239
- attributes: {...existingCluster.attributes, ...cluster.attributes},
1240
- commands: {...existingCluster.commands, ...cluster.commands},
1241
- commandsResponse: {...existingCluster.commandsResponse, ...cluster.commandsResponse},
1242
- };
1243
- }
1244
- this._customClusters[name] = cluster;
1245
- }
1246
- }
1247
-
1248
- export default Device;