@willieee802/zigbee-herdsman 0.49.0 → 0.49.1

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 (114) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +38 -0
  3. package/biome.json +1 -1
  4. package/dist/adapter/adapter.d.ts.map +1 -0
  5. package/dist/adapter/adapterDiscovery.d.ts.map +1 -0
  6. package/dist/adapter/const.d.ts.map +1 -0
  7. package/dist/adapter/deconz/adapter/deconzAdapter.d.ts.map +1 -0
  8. package/dist/adapter/ember/adapter/emberAdapter.d.ts.map +1 -0
  9. package/dist/adapter/ember/adapter/endpoints.d.ts.map +1 -0
  10. package/dist/adapter/ember/adapter/oneWaitress.d.ts.map +1 -0
  11. package/dist/adapter/ember/adapter/tokensManager.d.ts.map +1 -0
  12. package/dist/adapter/ember/ezsp/ezsp.d.ts.map +1 -0
  13. package/dist/adapter/ember/utils/initters.d.ts.map +1 -0
  14. package/dist/adapter/events.d.ts.map +1 -0
  15. package/dist/adapter/ezsp/adapter/backup.d.ts.map +1 -0
  16. package/dist/adapter/ezsp/adapter/ezspAdapter.d.ts.map +1 -0
  17. package/dist/adapter/ezsp/driver/driver.d.ts.map +1 -0
  18. package/dist/adapter/ezsp/driver/index.d.ts.map +1 -0
  19. package/dist/adapter/ezsp/driver/multicast.d.ts.map +1 -0
  20. package/dist/adapter/index.d.ts.map +1 -0
  21. package/dist/adapter/z-stack/adapter/endpoints.d.ts.map +1 -0
  22. package/dist/adapter/z-stack/adapter/manager.d.ts.map +1 -0
  23. package/dist/adapter/z-stack/adapter/zStackAdapter.d.ts.map +1 -0
  24. package/dist/adapter/z-stack/models/startup-options.d.ts.map +1 -0
  25. package/dist/adapter/zboss/adapter/zbossAdapter.d.ts.map +1 -0
  26. package/dist/adapter/zboss/driver.d.ts.map +1 -0
  27. package/dist/adapter/zboss/frame.d.ts.map +1 -0
  28. package/dist/adapter/zboss/frame.js +200 -0
  29. package/dist/adapter/zboss/frame.js.map +1 -0
  30. package/dist/adapter/zboss/uart.d.ts.map +1 -0
  31. package/dist/adapter/zigate/adapter/zigateAdapter.d.ts.map +1 -0
  32. package/dist/adapter/zigate/driver/buffaloZiGate.d.ts.map +1 -0
  33. package/dist/adapter/zigate/driver/buffaloZiGate.js +198 -0
  34. package/dist/adapter/zigate/driver/buffaloZiGate.js.map +1 -0
  35. package/dist/adapter/zigate/driver/ziGateObject.d.ts.map +1 -0
  36. package/dist/adapter/zigate/driver/zigate.d.ts.map +1 -0
  37. package/dist/adapter/zoh/adapter/zohAdapter.d.ts.map +1 -0
  38. package/dist/controller/controller.d.ts.map +1 -0
  39. package/dist/controller/controller.js +874 -0
  40. package/dist/controller/controller.js.map +1 -0
  41. package/dist/controller/database.d.ts.map +1 -0
  42. package/dist/controller/events.d.ts.map +1 -0
  43. package/dist/controller/events.js +3 -0
  44. package/dist/controller/events.js.map +1 -0
  45. package/dist/controller/greenPower.d.ts.map +1 -0
  46. package/dist/controller/greenPower.js +425 -0
  47. package/dist/controller/greenPower.js.map +1 -0
  48. package/dist/controller/helpers/index.d.ts.map +1 -0
  49. package/dist/controller/helpers/ota.d.ts.map +1 -0
  50. package/dist/controller/helpers/ota.js +467 -0
  51. package/dist/controller/helpers/ota.js.map +1 -0
  52. package/dist/controller/helpers/request.d.ts.map +1 -0
  53. package/dist/controller/helpers/requestQueue.d.ts.map +1 -0
  54. package/dist/controller/helpers/zclFrameConverter.d.ts.map +1 -0
  55. package/dist/controller/helpers/zclFrameConverter.js +84 -0
  56. package/dist/controller/helpers/zclFrameConverter.js.map +1 -0
  57. package/dist/controller/index.d.ts.map +1 -0
  58. package/dist/controller/model/device.d.ts.map +1 -0
  59. package/dist/controller/model/device.js +1396 -0
  60. package/dist/controller/model/device.js.map +1 -0
  61. package/dist/controller/model/endpoint.d.ts.map +1 -0
  62. package/dist/controller/model/endpoint.js +822 -0
  63. package/dist/controller/model/endpoint.js.map +1 -0
  64. package/dist/controller/model/entity.d.ts.map +1 -0
  65. package/dist/controller/model/group.d.ts.map +1 -0
  66. package/dist/controller/model/group.js +343 -0
  67. package/dist/controller/model/group.js.map +1 -0
  68. package/dist/controller/model/index.d.ts.map +1 -0
  69. package/dist/controller/model/zigbeeEntity.d.ts.map +1 -0
  70. package/dist/controller/touchlink.d.ts.map +1 -0
  71. package/dist/controller/tstype.d.ts.map +1 -0
  72. package/dist/controller/tstype.js +3 -0
  73. package/dist/controller/tstype.js.map +1 -0
  74. package/dist/index.d.ts.map +1 -0
  75. package/dist/utils/timeService.d.ts.map +1 -0
  76. package/dist/utils/timeService.js +127 -0
  77. package/dist/utils/timeService.js.map +1 -0
  78. package/dist/zspec/zcl/buffaloZcl.d.ts.map +1 -0
  79. package/dist/zspec/zcl/buffaloZcl.js +969 -0
  80. package/dist/zspec/zcl/buffaloZcl.js.map +1 -0
  81. package/dist/zspec/zcl/definition/cluster.d.ts.map +1 -0
  82. package/dist/zspec/zcl/definition/cluster.js +7507 -0
  83. package/dist/zspec/zcl/definition/cluster.js.map +1 -0
  84. package/dist/zspec/zcl/definition/clusters-types.d.ts +8135 -0
  85. package/dist/zspec/zcl/definition/clusters-types.d.ts.map +1 -0
  86. package/dist/zspec/zcl/definition/clusters-types.js +3 -0
  87. package/dist/zspec/zcl/definition/clusters-types.js.map +1 -0
  88. package/dist/zspec/zcl/definition/foundation.d.ts.map +1 -0
  89. package/dist/zspec/zcl/definition/foundation.js +312 -0
  90. package/dist/zspec/zcl/definition/foundation.js.map +1 -0
  91. package/dist/zspec/zcl/definition/tstype.d.ts +273 -0
  92. package/dist/zspec/zcl/definition/tstype.d.ts.map +1 -0
  93. package/dist/zspec/zcl/definition/tstype.js +3 -0
  94. package/dist/zspec/zcl/definition/tstype.js.map +1 -0
  95. package/dist/zspec/zcl/index.d.ts.map +1 -0
  96. package/dist/zspec/zcl/index.js +57 -0
  97. package/dist/zspec/zcl/index.js.map +1 -0
  98. package/dist/zspec/zcl/utils.d.ts.map +1 -0
  99. package/dist/zspec/zcl/utils.js +419 -0
  100. package/dist/zspec/zcl/utils.js.map +1 -0
  101. package/dist/zspec/zcl/zclFrame.d.ts.map +1 -0
  102. package/dist/zspec/zcl/zclFrame.js +328 -0
  103. package/dist/zspec/zcl/zclFrame.js.map +1 -0
  104. package/dist/zspec/zcl/zclHeader.d.ts.map +1 -0
  105. package/dist/zspec/zcl/zclHeader.js +88 -0
  106. package/dist/zspec/zcl/zclHeader.js.map +1 -0
  107. package/package.json +90 -83
  108. package/src/controller/helpers/ota.ts +5 -2
  109. package/src/zspec/zcl/definition/cluster.ts +3 -294
  110. package/src/zspec/zcl/definition/clusters-types.ts +6 -355
  111. package/src/zspec/zcl/definition/tstype.ts +0 -14
  112. package/src/zspec/zcl/utils.ts +14 -31
  113. package/test/controller.test.ts +16 -8
  114. package/test/zcl.test.ts +36 -7
@@ -0,0 +1,1396 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.Device = exports.InterviewState = void 0;
40
+ const node_assert_1 = __importDefault(require("node:assert"));
41
+ const utils_1 = require("../../utils");
42
+ const logger_1 = require("../../utils/logger");
43
+ const timeService = __importStar(require("../../utils/timeService"));
44
+ const ZSpec = __importStar(require("../../zspec"));
45
+ const enums_1 = require("../../zspec/enums");
46
+ const Zcl = __importStar(require("../../zspec/zcl"));
47
+ const Zdo = __importStar(require("../../zspec/zdo"));
48
+ const ota_1 = require("../helpers/ota");
49
+ const zclTransactionSequenceNumber_1 = __importDefault(require("../helpers/zclTransactionSequenceNumber"));
50
+ const endpoint_1 = __importDefault(require("./endpoint"));
51
+ const entity_1 = __importDefault(require("./entity"));
52
+ const NS = "zh:controller:device";
53
+ const INTERVIEW_GENBASIC_ATTRIBUTES = [
54
+ "modelId",
55
+ "manufacturerName",
56
+ "powerSource",
57
+ "zclVersion",
58
+ "appVersion",
59
+ "stackVersion",
60
+ "hwVersion",
61
+ "dateCode",
62
+ "swBuildId",
63
+ ];
64
+ var InterviewState;
65
+ (function (InterviewState) {
66
+ InterviewState["Pending"] = "PENDING";
67
+ InterviewState["InProgress"] = "IN_PROGRESS";
68
+ InterviewState["Successful"] = "SUCCESSFUL";
69
+ InterviewState["Failed"] = "FAILED";
70
+ })(InterviewState || (exports.InterviewState = InterviewState = {}));
71
+ class Device extends entity_1.default {
72
+ databaseID;
73
+ // biome-ignore lint/style/useNamingConvention: cross-repo impact
74
+ ID;
75
+ #genBasic = {};
76
+ _endpoints;
77
+ _ieeeAddr;
78
+ _interviewState;
79
+ _lastSeen;
80
+ _manufacturerID;
81
+ _networkAddress;
82
+ _type;
83
+ _linkquality;
84
+ _skipDefaultResponse;
85
+ _customReadResponse;
86
+ _lastDefaultResponseSequenceNumber;
87
+ _checkinInterval;
88
+ _pendingRequestTimeout;
89
+ _customClusters = {};
90
+ _gpSecurityKey;
91
+ #scheduledOta;
92
+ #otaInProgress = false;
93
+ // Getters/setters
94
+ get ieeeAddr() {
95
+ return this._ieeeAddr;
96
+ }
97
+ set ieeeAddr(ieeeAddr) {
98
+ this._ieeeAddr = ieeeAddr;
99
+ }
100
+ get applicationVersion() {
101
+ return this.#genBasic.appVersion;
102
+ }
103
+ set applicationVersion(version) {
104
+ this.#genBasic.appVersion = version;
105
+ }
106
+ get endpoints() {
107
+ return this._endpoints;
108
+ }
109
+ get interviewState() {
110
+ return this._interviewState;
111
+ }
112
+ get lastSeen() {
113
+ return this._lastSeen;
114
+ }
115
+ get manufacturerID() {
116
+ return this._manufacturerID;
117
+ }
118
+ get isDeleted() {
119
+ return Device.deletedDevices.get(this.databaseID)?.has(this.ieeeAddr) ?? false;
120
+ }
121
+ set type(type) {
122
+ this._type = type;
123
+ }
124
+ get type() {
125
+ return this._type;
126
+ }
127
+ get dateCode() {
128
+ return this.#genBasic.dateCode;
129
+ }
130
+ set dateCode(code) {
131
+ this.#genBasic.dateCode = code;
132
+ }
133
+ set hardwareVersion(version) {
134
+ this.#genBasic.hwVersion = version;
135
+ }
136
+ get hardwareVersion() {
137
+ return this.#genBasic.hwVersion;
138
+ }
139
+ get manufacturerName() {
140
+ return this.#genBasic.manufacturerName;
141
+ }
142
+ set manufacturerName(name) {
143
+ this.#genBasic.manufacturerName = name;
144
+ }
145
+ set modelID(id) {
146
+ this.#genBasic.modelId = id;
147
+ }
148
+ get modelID() {
149
+ return this.#genBasic.modelId;
150
+ }
151
+ get networkAddress() {
152
+ return this._networkAddress;
153
+ }
154
+ set networkAddress(networkAddress) {
155
+ Device.nwkToIeeeCache.get(this.databaseID)?.delete(this._networkAddress);
156
+ this._networkAddress = networkAddress;
157
+ Device.nwkToIeeeCache.get(this.databaseID)?.set(this._networkAddress, this.ieeeAddr);
158
+ for (const endpoint of this._endpoints) {
159
+ endpoint.deviceNetworkAddress = networkAddress;
160
+ }
161
+ }
162
+ get powerSource() {
163
+ return this.#genBasic.powerSource ? Zcl.POWER_SOURCES[this.#genBasic.powerSource] : undefined;
164
+ }
165
+ set powerSource(source) {
166
+ if (typeof source === "number") {
167
+ this.#genBasic.powerSource = source & ~(1 << 7);
168
+ }
169
+ else {
170
+ for (const key in Zcl.POWER_SOURCES) {
171
+ const val = Zcl.POWER_SOURCES[key];
172
+ if (val === source) {
173
+ this.#genBasic.powerSource = Number(key);
174
+ break;
175
+ }
176
+ }
177
+ }
178
+ }
179
+ get softwareBuildID() {
180
+ return this.#genBasic.swBuildId;
181
+ }
182
+ set softwareBuildID(id) {
183
+ this.#genBasic.swBuildId = id;
184
+ }
185
+ get stackVersion() {
186
+ return this.#genBasic.stackVersion;
187
+ }
188
+ set stackVersion(version) {
189
+ this.#genBasic.stackVersion = version;
190
+ }
191
+ get zclVersion() {
192
+ return this.#genBasic.zclVersion;
193
+ }
194
+ set zclVersion(version) {
195
+ this.#genBasic.zclVersion = version;
196
+ }
197
+ get linkquality() {
198
+ return this._linkquality;
199
+ }
200
+ set linkquality(linkquality) {
201
+ this._linkquality = linkquality;
202
+ }
203
+ get skipDefaultResponse() {
204
+ return this._skipDefaultResponse;
205
+ }
206
+ set skipDefaultResponse(skipDefaultResponse) {
207
+ this._skipDefaultResponse = skipDefaultResponse;
208
+ }
209
+ get customReadResponse() {
210
+ return this._customReadResponse;
211
+ }
212
+ set customReadResponse(customReadResponse) {
213
+ this._customReadResponse = customReadResponse;
214
+ }
215
+ get checkinInterval() {
216
+ return this._checkinInterval;
217
+ }
218
+ set checkinInterval(checkinInterval) {
219
+ this._checkinInterval = checkinInterval;
220
+ this.resetPendingRequestTimeout();
221
+ }
222
+ get pendingRequestTimeout() {
223
+ return this._pendingRequestTimeout;
224
+ }
225
+ set pendingRequestTimeout(pendingRequestTimeout) {
226
+ this._pendingRequestTimeout = pendingRequestTimeout;
227
+ }
228
+ get customClusters() {
229
+ return this._customClusters;
230
+ }
231
+ get gpSecurityKey() {
232
+ return this._gpSecurityKey;
233
+ }
234
+ get genBasic() {
235
+ return this.#genBasic;
236
+ }
237
+ get scheduledOta() {
238
+ return this.#scheduledOta;
239
+ }
240
+ get otaInProgress() {
241
+ return this.#otaInProgress;
242
+ }
243
+ meta;
244
+ // This lookup contains all devices that are queried from the database, this is to ensure that always
245
+ // the same instance is returned.
246
+ static devices = new Map();
247
+ static loadedFromDatabase = false;
248
+ static deletedDevices = new Map();
249
+ static nwkToIeeeCache = new Map();
250
+ constructor(databaseID, id, type, ieeeAddr, networkAddress, manufacturerID, endpoints, manufacturerName, powerSource, modelID, applicationVersion, stackVersion, zclVersion, hardwareVersion, dateCode, softwareBuildID, interviewState, meta, lastSeen, checkinInterval, pendingRequestTimeout, gpSecurityKey, scheduledOta) {
251
+ super();
252
+ this.databaseID = databaseID;
253
+ this.ID = id;
254
+ this._type = type;
255
+ this._ieeeAddr = ieeeAddr;
256
+ this._networkAddress = networkAddress;
257
+ this._manufacturerID = manufacturerID;
258
+ this._endpoints = endpoints;
259
+ this.#genBasic.manufacturerName = manufacturerName;
260
+ this.powerSource = powerSource ?? Zcl.PowerSource.Unknown;
261
+ this.#genBasic.modelId = modelID;
262
+ this.#genBasic.appVersion = applicationVersion;
263
+ this.#genBasic.stackVersion = stackVersion;
264
+ this.#genBasic.zclVersion = zclVersion;
265
+ this.#genBasic.hwVersion = hardwareVersion;
266
+ this.#genBasic.dateCode = dateCode;
267
+ this.#genBasic.swBuildId = softwareBuildID;
268
+ this._interviewState = interviewState;
269
+ this._skipDefaultResponse = false;
270
+ this.meta = meta;
271
+ this._lastSeen = lastSeen;
272
+ this._checkinInterval = checkinInterval;
273
+ this._pendingRequestTimeout = pendingRequestTimeout;
274
+ this._gpSecurityKey = gpSecurityKey;
275
+ this.#scheduledOta = scheduledOta;
276
+ }
277
+ createEndpoint(id) {
278
+ if (this.getEndpoint(id)) {
279
+ throw new Error(`Device '${this.ieeeAddr}' already has an endpoint '${id}'`);
280
+ }
281
+ const endpoint = endpoint_1.default.create(this.databaseID, id, undefined, undefined, [], [], this.networkAddress, this.ieeeAddr);
282
+ this.endpoints.push(endpoint);
283
+ this.save();
284
+ return endpoint;
285
+ }
286
+ changeIeeeAddress(ieeeAddr) {
287
+ Device.devices.get(this.databaseID)?.delete(this.ieeeAddr);
288
+ this.ieeeAddr = ieeeAddr;
289
+ Device.devices.get(this.databaseID)?.set(this.ieeeAddr, this);
290
+ Device.nwkToIeeeCache.get(this.databaseID)?.set(this.networkAddress, this.ieeeAddr);
291
+ for (const ep of this.endpoints) {
292
+ ep.deviceIeeeAddress = ieeeAddr;
293
+ }
294
+ this.save();
295
+ }
296
+ getEndpoint(id) {
297
+ return this.endpoints.find((e) => e.ID === id);
298
+ }
299
+ // There might be multiple endpoints with same DeviceId but it is not supported and first endpoint is returned
300
+ getEndpointByDeviceType(deviceType) {
301
+ const deviceID = Zcl.ENDPOINT_DEVICE_TYPE[deviceType];
302
+ return this.endpoints.find((d) => d.deviceID === deviceID);
303
+ }
304
+ updateGenBasic(data) {
305
+ Object.assign(this.#genBasic, data);
306
+ }
307
+ implicitCheckin() {
308
+ // No need to do anythign in `catch` as `endpoint.sendRequest` already logs failures.
309
+ Promise.allSettled(this.endpoints.map((e) => e.sendPendingRequests(false))).catch(() => { });
310
+ }
311
+ updateLastSeen() {
312
+ this._lastSeen = Date.now();
313
+ }
314
+ resetPendingRequestTimeout() {
315
+ // pendingRequestTimeout can be changed dynamically at runtime, and it is not persisted.
316
+ // Default timeout is one checkin interval in milliseconds.
317
+ this._pendingRequestTimeout = (this._checkinInterval ?? 0) * 1000;
318
+ }
319
+ hasPendingRequests() {
320
+ return this.endpoints.find((e) => e.hasPendingRequests()) !== undefined;
321
+ }
322
+ async onZclData(dataPayload, frame, endpoint) {
323
+ if (!Device.devices.get(this.databaseID)?.has(this.ieeeAddr)) {
324
+ // prevent race conditions where device gets deleted during processing
325
+ return;
326
+ }
327
+ if (frame.header.isGlobal) {
328
+ // Response to read requests
329
+ if (frame.command.name === "read" && !this._customReadResponse?.(frame, endpoint)) {
330
+ const attributes = {
331
+ ...endpoint.clusters,
332
+ };
333
+ const isTimeReadRequest = dataPayload.clusterID === Zcl.Clusters.genTime.ID;
334
+ if (isTimeReadRequest) {
335
+ attributes.genTime = {
336
+ attributes: timeService.getTimeClusterAttributes(),
337
+ };
338
+ }
339
+ if (frame.cluster.name in attributes) {
340
+ const response = {};
341
+ for (const entry of frame.payload) {
342
+ const name = frame.cluster.getAttribute(entry.attrId)?.name;
343
+ if (name && name in attributes[frame.cluster.name].attributes) {
344
+ response[name] = attributes[frame.cluster.name].attributes[name];
345
+ }
346
+ }
347
+ try {
348
+ await endpoint.readResponse(frame.cluster.ID, frame.header.transactionSequenceNumber, response, {
349
+ srcEndpoint: dataPayload.destinationEndpoint,
350
+ });
351
+ }
352
+ catch (error) {
353
+ logger_1.logger.error(`Read response to ${this.ieeeAddr} failed (${error.message})`, NS);
354
+ }
355
+ }
356
+ }
357
+ }
358
+ else if (frame.header.isSpecific) {
359
+ switch (frame.cluster.name) {
360
+ case "ssIasZone": {
361
+ if (frame.command.name === "enrollReq") {
362
+ // Respond to enroll requests
363
+ logger_1.logger.debug(`IAS - '${this.ieeeAddr}' responding to enroll response`, NS);
364
+ await endpoint.command("ssIasZone", "enrollRsp", { enrollrspcode: 0, zoneid: 23 }, { disableDefaultResponse: true });
365
+ }
366
+ break;
367
+ }
368
+ case "genPollCtrl": {
369
+ if (frame.command.name === "checkin") {
370
+ // Handle check-in from sleeping end devices
371
+ try {
372
+ if (this.hasPendingRequests() || this._checkinInterval === undefined) {
373
+ logger_1.logger.debug(`check-in from ${this.ieeeAddr}: accepting fast-poll`, NS);
374
+ await endpoint.command(frame.cluster.name, "checkinRsp", {
375
+ startFastPolling: 1,
376
+ fastPollTimeout: 0,
377
+ }, { sendPolicy: "immediate" });
378
+ // This is a good time to read the checkin interval if we haven't stored it previously
379
+ if (this._checkinInterval === undefined) {
380
+ const pollPeriod = await endpoint.read("genPollCtrl", ["checkinInterval"], { sendPolicy: "immediate" });
381
+ this._checkinInterval = pollPeriod.checkinInterval / 4; // convert to seconds
382
+ this.resetPendingRequestTimeout();
383
+ logger_1.logger.debug(`Request Queue (${this.ieeeAddr}): default expiration timeout set to ${this.pendingRequestTimeout}`, NS);
384
+ }
385
+ await Promise.all(this.endpoints.map(async (e) => await e.sendPendingRequests(true)));
386
+ // We *must* end fast-poll when we're done sending things. Otherwise
387
+ // we cause undue power-drain.
388
+ logger_1.logger.debug(`check-in from ${this.ieeeAddr}: stopping fast-poll`, NS);
389
+ await endpoint.command(frame.cluster.name, "fastPollStop", {}, { sendPolicy: "immediate" });
390
+ }
391
+ else {
392
+ logger_1.logger.debug(`check-in from ${this.ieeeAddr}: declining fast-poll`, NS);
393
+ await endpoint.command(frame.cluster.name, "checkinRsp", {
394
+ startFastPolling: 0,
395
+ fastPollTimeout: 0,
396
+ }, { sendPolicy: "immediate" });
397
+ }
398
+ }
399
+ catch (error) {
400
+ logger_1.logger.error(`Handling of poll check-in from ${this.ieeeAddr} failed (${error.message})`, NS);
401
+ }
402
+ }
403
+ break;
404
+ }
405
+ }
406
+ }
407
+ // Send a default response if necessary.
408
+ const isDefaultResponse = frame.header.isGlobal && frame.command.name === "defaultRsp";
409
+ const commandHasResponse = frame.command.response !== undefined;
410
+ const disableDefaultResponse = frame.header.frameControl.disableDefaultResponse;
411
+ /* v8 ignore next */
412
+ const disableTuyaDefaultResponse = this.manufacturerName?.startsWith("_TZ") && process.env.DISABLE_TUYA_DEFAULT_RESPONSE;
413
+ // Sometimes messages are received twice, prevent responding twice
414
+ const alreadyResponded = this._lastDefaultResponseSequenceNumber === frame.header.transactionSequenceNumber;
415
+ if (this.type !== "GreenPower" &&
416
+ !dataPayload.wasBroadcast &&
417
+ !disableDefaultResponse &&
418
+ !isDefaultResponse &&
419
+ !commandHasResponse &&
420
+ !this._skipDefaultResponse &&
421
+ !alreadyResponded &&
422
+ !disableTuyaDefaultResponse) {
423
+ try {
424
+ this._lastDefaultResponseSequenceNumber = frame.header.transactionSequenceNumber;
425
+ // In the ZCL it is not documented what the direction of the default response should be
426
+ // In https://github.com/Koenkk/zigbee2mqtt/issues/18096 a commandResponse (SERVER_TO_CLIENT)
427
+ // is send and the device expects a CLIENT_TO_SERVER back.
428
+ // Previously SERVER_TO_CLIENT was always used.
429
+ // Therefore for non-global commands we inverse the direction.
430
+ const direction = frame.header.isGlobal
431
+ ? Zcl.Direction.SERVER_TO_CLIENT
432
+ : frame.header.frameControl.direction === Zcl.Direction.CLIENT_TO_SERVER
433
+ ? Zcl.Direction.SERVER_TO_CLIENT
434
+ : Zcl.Direction.CLIENT_TO_SERVER;
435
+ await endpoint.defaultResponse(frame.command.ID, 0, frame.cluster.ID, frame.header.transactionSequenceNumber, { direction });
436
+ }
437
+ catch (error) {
438
+ logger_1.logger.debug(`Default response to ${this.ieeeAddr} failed (${error})`, NS);
439
+ }
440
+ }
441
+ }
442
+ /*
443
+ * CRUD
444
+ */
445
+ /**
446
+ * Reset runtime lookups.
447
+ */
448
+ static resetCache() {
449
+ Device.devices.clear();
450
+ Device.loadedFromDatabase = false;
451
+ Device.deletedDevices.clear();
452
+ Device.nwkToIeeeCache.clear();
453
+ }
454
+ static fromDatabaseEntry(entry, databaseID) {
455
+ const networkAddress = entry.nwkAddr;
456
+ const ieeeAddr = entry.ieeeAddr;
457
+ const endpoints = [];
458
+ for (const id in entry.endpoints) {
459
+ endpoints.push(endpoint_1.default.fromDatabaseRecord(entry.endpoints[id], networkAddress, ieeeAddr, databaseID));
460
+ }
461
+ const meta = entry.meta ?? {};
462
+ if (entry.type === "Group") {
463
+ throw new Error("Cannot load device from group");
464
+ }
465
+ // default: no timeout (messages expire immediately after first send attempt)
466
+ let pendingRequestTimeout = 0;
467
+ if (endpoints.filter((e) => e.inputClusters.includes(Zcl.Clusters.genPollCtrl.ID)).length > 0) {
468
+ // default for devices that support genPollCtrl cluster (RX off when idle): 1 day
469
+ pendingRequestTimeout = 86400000;
470
+ }
471
+ // always load value from database available (modernExtend.quirkCheckinInterval() exists for devices without genPollCtl)
472
+ if (entry.checkinInterval !== undefined) {
473
+ // if the checkin interval is known, messages expire by default after one checkin interval
474
+ pendingRequestTimeout = entry.checkinInterval * 1000; // milliseconds
475
+ }
476
+ logger_1.logger.debug(`Request Queue (${ieeeAddr}): default expiration timeout set to ${pendingRequestTimeout}`, NS);
477
+ // Migrate interviewCompleted to interviewState
478
+ if (!entry.interviewState) {
479
+ entry.interviewState = entry.interviewCompleted ? InterviewState.Successful : InterviewState.Failed;
480
+ logger_1.logger.debug(`Migrated interviewState for '${ieeeAddr}': ${entry.interviewCompleted} -> ${entry.interviewState}`, NS);
481
+ }
482
+ return new Device(databaseID, entry.id, entry.type, ieeeAddr, networkAddress, entry.manufId, endpoints, entry.manufName, entry.powerSource, entry.modelId, entry.appVersion, entry.stackVersion, entry.zclVersion, entry.hwVersion, entry.dateCode, entry.swBuildId, entry.interviewState, meta, entry.lastSeen, entry.checkinInterval, pendingRequestTimeout, entry.gpSecurityKey, entry.scheduledOta);
483
+ }
484
+ toDatabaseEntry() {
485
+ const epList = this.endpoints.map((e) => e.ID);
486
+ const endpoints = {};
487
+ for (const endpoint of this.endpoints) {
488
+ endpoints[endpoint.ID] = endpoint.toDatabaseRecord();
489
+ }
490
+ return {
491
+ id: this.ID,
492
+ type: this.type,
493
+ ieeeAddr: this.ieeeAddr,
494
+ nwkAddr: this.networkAddress,
495
+ manufId: this.manufacturerID,
496
+ manufName: this.manufacturerName,
497
+ powerSource: this.powerSource,
498
+ modelId: this.modelID,
499
+ epList,
500
+ endpoints,
501
+ appVersion: this.applicationVersion,
502
+ stackVersion: this.stackVersion,
503
+ hwVersion: this.hardwareVersion,
504
+ dateCode: this.dateCode,
505
+ swBuildId: this.softwareBuildID,
506
+ zclVersion: this.zclVersion,
507
+ /** @deprecated Keep interviewCompleted for backwards compatibility (in case zh gets downgraded) */
508
+ interviewCompleted: this.interviewState === InterviewState.Successful,
509
+ interviewState: this.interviewState === InterviewState.InProgress ? InterviewState.Pending : this.interviewState,
510
+ meta: this.meta,
511
+ lastSeen: this.lastSeen,
512
+ checkinInterval: this.checkinInterval,
513
+ gpSecurityKey: this.gpSecurityKey,
514
+ scheduledOta: this.scheduledOta,
515
+ };
516
+ }
517
+ save(writeDatabase = true) {
518
+ entity_1.default.getDatabaseByID(this.databaseID)?.update(this.toDatabaseEntry(), writeDatabase);
519
+ }
520
+ static loadFromDatabaseIfNecessary() {
521
+ if (!Device.loadedFromDatabase) {
522
+ entity_1.default.databases.forEach(database => {
523
+ if (!Device.devices.has(database.id)) {
524
+ Device.devices.set(database.id, new Map());
525
+ Device.deletedDevices.set(database.id, new Map());
526
+ Device.nwkToIeeeCache.set(database.id, new Map());
527
+ const entries = database.getEntriesIterator(['Coordinator', 'EndDevice', 'Router', 'GreenPower', 'Unknown']);
528
+ for (const entry of entries) {
529
+ const device = Device.fromDatabaseEntry(entry, database.id);
530
+ Device.devices.get(database.id).set(device.ieeeAddr, device);
531
+ Device.nwkToIeeeCache.get(database.id).set(device.networkAddress, device.ieeeAddr);
532
+ }
533
+ }
534
+ });
535
+ Device.loadedFromDatabase = true;
536
+ }
537
+ }
538
+ static find(databaseID, ieeeOrNwkAddress, includeDeleted = false) {
539
+ return typeof ieeeOrNwkAddress === "string"
540
+ ? Device.byIeeeAddr(databaseID, ieeeOrNwkAddress, includeDeleted)
541
+ : Device.byNetworkAddress(databaseID, ieeeOrNwkAddress, includeDeleted);
542
+ }
543
+ static byIeeeAddr(databaseID, ieeeAddr, includeDeleted = false) {
544
+ Device.loadFromDatabaseIfNecessary();
545
+ const device = Device.devices.get(databaseID)?.get(ieeeAddr);
546
+ return includeDeleted ? (Device.deletedDevices.get(databaseID)?.get(ieeeAddr) ?? device) : device;
547
+ }
548
+ static byNetworkAddress(databaseID, networkAddress, includeDeleted = false) {
549
+ Device.loadFromDatabaseIfNecessary();
550
+ const ieeeAddr = Device.nwkToIeeeCache.get(databaseID)?.get(networkAddress);
551
+ return ieeeAddr ? Device.byIeeeAddr(databaseID, ieeeAddr, includeDeleted) : undefined;
552
+ }
553
+ static byType(databaseID, type) {
554
+ return Device.allByDatabaseID(databaseID).filter(d => d.type === type);
555
+ }
556
+ static allByDatabaseID(databaseID) {
557
+ Device.loadFromDatabaseIfNecessary();
558
+ return Array.from(Device.devices.get(databaseID)?.values() ?? []);
559
+ }
560
+ /** Check if a device is explicitly deleted */
561
+ static isDeletedByIeeeAddr(databaseID, ieeeAddr) {
562
+ Device.loadFromDatabaseIfNecessary();
563
+ return Device.deletedDevices.get(databaseID)?.has(ieeeAddr) ?? false;
564
+ }
565
+ /** Check if a device is explicitly deleted */
566
+ static isDeletedByNetworkAddress(databaseID, networkAddress) {
567
+ Device.loadFromDatabaseIfNecessary();
568
+ const ieeeAddr = Device.nwkToIeeeCache.get(databaseID)?.get(networkAddress);
569
+ return ieeeAddr ? Device.deletedDevices.get(databaseID)?.has(ieeeAddr) ?? false : false;
570
+ }
571
+ // public static all(): Device[] {
572
+ // Device.loadFromDatabaseIfNecessary();
573
+ // return Array.from(Device.devices.values());
574
+ // }
575
+ static *allIterator(databaseID, predicate) {
576
+ Device.loadFromDatabaseIfNecessary();
577
+ for (const device of Device.allByDatabaseID(databaseID)) {
578
+ if (!predicate || predicate(device)) {
579
+ yield device;
580
+ }
581
+ }
582
+ }
583
+ undelete() {
584
+ if (Device.deletedDevices.get(this.databaseID)?.delete(this.ieeeAddr)) {
585
+ Device.devices.get(this.databaseID)?.set(this.ieeeAddr, this);
586
+ entity_1.default.getDatabaseByID(this.databaseID)?.insert(this.toDatabaseEntry());
587
+ }
588
+ else {
589
+ throw new Error(`Device '${this.ieeeAddr}' is not deleted`);
590
+ }
591
+ }
592
+ static create(type, ieeeAddr, networkAddress, manufacturerID, manufacturerName, powerSource, modelID, interviewState, gpSecurityKey, databaseID) {
593
+ Device.loadFromDatabaseIfNecessary();
594
+ if (Device.devices.get(databaseID)?.has(ieeeAddr)) {
595
+ throw new Error(`Device with IEEE address '${ieeeAddr}' already exists`);
596
+ }
597
+ const database = entity_1.default.getDatabaseByID(databaseID);
598
+ if (!database) {
599
+ throw new Error(`Database with ID '${databaseID}' not found`);
600
+ }
601
+ const ID = database.newID();
602
+ const device = new Device(databaseID, ID, type, ieeeAddr, networkAddress, manufacturerID, [], manufacturerName, powerSource, modelID, undefined, undefined, undefined, undefined, undefined, undefined, interviewState, {}, undefined, undefined, 0, gpSecurityKey, undefined);
603
+ database.insert(device.toDatabaseEntry());
604
+ Device.devices.get(databaseID)?.set(device.ieeeAddr, device);
605
+ Device.nwkToIeeeCache.get(databaseID)?.set(device.networkAddress, device.ieeeAddr);
606
+ return device;
607
+ }
608
+ /*
609
+ * Zigbee functions
610
+ */
611
+ async interview(ignoreCache = false) {
612
+ if (this.interviewState === InterviewState.InProgress) {
613
+ const message = `Interview - interview already in progress for '${this.ieeeAddr}'`;
614
+ logger_1.logger.debug(message, NS);
615
+ throw new Error(message);
616
+ }
617
+ let err;
618
+ this._interviewState = InterviewState.InProgress;
619
+ logger_1.logger.debug(`Interview - start device '${this.ieeeAddr}'`, NS);
620
+ try {
621
+ await this.interviewInternal(ignoreCache);
622
+ logger_1.logger.debug(`Interview - completed for device '${this.ieeeAddr}'`, NS);
623
+ this._interviewState = InterviewState.Successful;
624
+ }
625
+ catch (error) {
626
+ if (this.interviewQuirks()) {
627
+ this._interviewState = InterviewState.Successful;
628
+ logger_1.logger.debug(`Interview - completed for device '${this.ieeeAddr}' because of quirks ('${error}')`, NS);
629
+ }
630
+ else {
631
+ this._interviewState = InterviewState.Failed;
632
+ logger_1.logger.debug(`Interview - failed for device '${this.ieeeAddr}' with error '${error}'`, NS);
633
+ err = error;
634
+ }
635
+ }
636
+ finally {
637
+ this.save();
638
+ }
639
+ if (err) {
640
+ throw err;
641
+ }
642
+ }
643
+ interviewQuirks() {
644
+ logger_1.logger.debug(`Interview - quirks check for '${this.modelID}'-'${this.manufacturerName}'-'${this.type}'`, NS);
645
+ // Tuya devices are typically hard to interview. They also don't require a full interview to work correctly
646
+ // e.g. no ias enrolling is required for the devices to work.
647
+ // Assume that in case we got both the manufacturerName and modelID the device works correctly.
648
+ // https://github.com/Koenkk/zigbee2mqtt/issues/7564:
649
+ // Fails during ias enroll due to UNSUPPORTED_ATTRIBUTE
650
+ // https://github.com/Koenkk/zigbee2mqtt/issues/4655
651
+ // Device does not change zoneState after enroll (event with original gateway)
652
+ // modelID is mostly in the form of e.g. TS0202 and manufacturerName like e.g. _TYZB01_xph99wvr
653
+ if (this.manufacturerName === "HOBEIAN" ||
654
+ (this.modelID?.match("^TS\\d*$") && (this.manufacturerName?.match("^_TZ.*_.*$") || this.manufacturerName?.match("^_TYZB01_.*$")))) {
655
+ this.#genBasic.powerSource = this.#genBasic.powerSource || Zcl.PowerSource.Battery;
656
+ logger_1.logger.debug("Interview - quirks matched for Tuya end device", NS);
657
+ return true;
658
+ }
659
+ // Some devices, e.g. Xiaomi end devices have a different interview procedure, after pairing they
660
+ // report it's modelID trough a readResponse. The readResponse is received by the controller and set
661
+ // on the device.
662
+ const lookup = {
663
+ "^3R.*?Z": {
664
+ type: "EndDevice",
665
+ powerSource: Zcl.PowerSource.Battery,
666
+ },
667
+ "lumi..*": {
668
+ type: "EndDevice",
669
+ manufacturerID: 4151,
670
+ manufacturerName: "LUMI",
671
+ powerSource: Zcl.PowerSource.Battery,
672
+ },
673
+ "TERNCY-PP01": {
674
+ type: "EndDevice",
675
+ manufacturerID: 4648,
676
+ manufacturerName: "TERNCY",
677
+ powerSource: Zcl.PowerSource.Battery,
678
+ },
679
+ "3RWS18BZ": {}, // https://github.com/Koenkk/zigbee-herdsman-converters/pull/2710
680
+ "MULTI-MECI--EA01": {},
681
+ MOT003: {}, // https://github.com/Koenkk/zigbee2mqtt/issues/12471
682
+ "C-ZB-SEDC": {}, //candeo device that doesn't follow IAS enrollment process correctly and therefore fails to complete interview
683
+ "C-ZB-SEMO": {}, //candeo device that doesn't follow IAS enrollment process correctly and therefore fails to complete interview
684
+ "CS-T9C-A0-BG": {}, // iAS enroll fails: https://github.com/Koenkk/zigbee2mqtt/issues/27822
685
+ "SNZB-01": {}, // iAS enroll fails: https://github.com/Koenkk/zigbee2mqtt/issues/29474
686
+ };
687
+ let match;
688
+ for (const key in lookup) {
689
+ if (this.modelID?.match(key)) {
690
+ match = key;
691
+ break;
692
+ }
693
+ }
694
+ if (match) {
695
+ const info = lookup[match];
696
+ logger_1.logger.debug(`Interview procedure failed but got modelID matching '${match}', assuming interview succeeded`, NS);
697
+ this._type = this._type === "Unknown" && info.type ? info.type : this._type;
698
+ this._manufacturerID = this._manufacturerID || info.manufacturerID;
699
+ this.#genBasic.manufacturerName = this.#genBasic.manufacturerName || info.manufacturerName;
700
+ this.#genBasic.powerSource = (this.#genBasic.powerSource || info.powerSource) /* v8 ignore next */ ?? Zcl.PowerSource.Unknown;
701
+ logger_1.logger.debug(`Interview - quirks matched on '${match}'`, NS);
702
+ return true;
703
+ }
704
+ logger_1.logger.debug("Interview - quirks did not match", NS);
705
+ return false;
706
+ }
707
+ async interviewInternal(ignoreCache) {
708
+ const hasNodeDescriptor = () => this._manufacturerID !== undefined && this._type !== "Unknown";
709
+ if (ignoreCache || !hasNodeDescriptor()) {
710
+ for (let attempt = 0; attempt < 6; attempt++) {
711
+ try {
712
+ await this.updateNodeDescriptor();
713
+ break;
714
+ }
715
+ catch (error) {
716
+ if (this.interviewQuirks()) {
717
+ logger_1.logger.debug(`Interview - completed for device '${this.ieeeAddr}' because of quirks ('${error}')`, NS);
718
+ return;
719
+ }
720
+ // Most of the times the first node descriptor query fails and the seconds one succeeds.
721
+ logger_1.logger.debug(`Interview - node descriptor request failed for '${this.ieeeAddr}', attempt ${attempt + 1}`, NS);
722
+ }
723
+ }
724
+ }
725
+ else {
726
+ logger_1.logger.debug(`Interview - skip node descriptor request for '${this.ieeeAddr}', already got it`, NS);
727
+ }
728
+ if (!hasNodeDescriptor()) {
729
+ throw new Error(`Interview failed because can not get node descriptor ('${this.ieeeAddr}')`);
730
+ }
731
+ if (this.manufacturerID === 4619 && this._type === "EndDevice") {
732
+ // Give Tuya end device some time to pair. Otherwise they leave immediately.
733
+ // https://github.com/Koenkk/zigbee2mqtt/issues/5814
734
+ logger_1.logger.debug("Interview - Detected Tuya end device, waiting 10 seconds...", NS);
735
+ await (0, utils_1.wait)(10000);
736
+ }
737
+ else if (this.manufacturerID === 0 || this.manufacturerID === 4098) {
738
+ // Potentially a Tuya device, some sleep fast so make sure to read the modelId and manufacturerName quickly.
739
+ // In case the device responds, the endoint and modelID/manufacturerName are set
740
+ // in controller.onZclOrRawData()
741
+ // https://github.com/Koenkk/zigbee2mqtt/issues/7553
742
+ logger_1.logger.debug("Interview - Detected potential Tuya end device, reading modelID and manufacturerName...", NS);
743
+ try {
744
+ const endpoint = endpoint_1.default.create(this.databaseID, 1, undefined, undefined, [], [], this.networkAddress, this.ieeeAddr);
745
+ const result = await endpoint.read("genBasic", ["modelId", "manufacturerName"], { sendPolicy: "immediate" });
746
+ this.updateGenBasic(result);
747
+ }
748
+ catch (error) {
749
+ logger_1.logger.debug(`Interview - Tuya read modelID and manufacturerName failed (${error})`, NS);
750
+ }
751
+ }
752
+ // e.g. Xiaomi Aqara Opple devices fail to respond to the first active endpoints request, therefore try 2 times
753
+ // https://github.com/Koenkk/zigbee-herdsman/pull/103
754
+ let gotActiveEndpoints = false;
755
+ for (let attempt = 0; attempt < 2; attempt++) {
756
+ try {
757
+ await this.updateActiveEndpoints();
758
+ gotActiveEndpoints = true;
759
+ break;
760
+ }
761
+ catch (error) {
762
+ logger_1.logger.debug(`Interview - active endpoints request failed for '${this.ieeeAddr}', attempt ${attempt + 1} (${error})`, NS);
763
+ }
764
+ }
765
+ if (!gotActiveEndpoints) {
766
+ throw new Error(`Interview failed because can not get active endpoints ('${this.ieeeAddr}')`);
767
+ }
768
+ logger_1.logger.debug(`Interview - got active endpoints for device '${this.ieeeAddr}'`, NS);
769
+ const coordinator = Device.byType(this.databaseID, "Coordinator")[0];
770
+ for (const endpoint of this._endpoints) {
771
+ await endpoint.updateSimpleDescriptor();
772
+ logger_1.logger.debug(`Interview - got simple descriptor for endpoint '${endpoint.ID}' device '${this.ieeeAddr}'`, NS);
773
+ // Read attributes
774
+ // nice to have but not required for successful pairing as most of the attributes are not mandatory in ZCL specification
775
+ if (endpoint.supportsInputCluster("genBasic")) {
776
+ for (const key of INTERVIEW_GENBASIC_ATTRIBUTES) {
777
+ if (ignoreCache || !this.#genBasic[key]) {
778
+ try {
779
+ let result;
780
+ try {
781
+ result = await endpoint.read("genBasic", [key], { sendPolicy: "immediate" });
782
+ }
783
+ catch (error) {
784
+ // Reading attributes can fail for many reason, e.g. it could be that device rejoins
785
+ // while joining like in:
786
+ // https://github.com/Koenkk/zigbee-herdsman-converters/issues/2485.
787
+ // The modelID and manufacturerName are crucial for device identification, so retry.
788
+ if (key === "modelId" || key === "manufacturerName") {
789
+ logger_1.logger.debug(`Interview - first ${key} retrieval attempt failed, retrying after 10 seconds...`, NS);
790
+ await (0, utils_1.wait)(10000);
791
+ result = await endpoint.read("genBasic", [key], { sendPolicy: "immediate" });
792
+ }
793
+ else {
794
+ throw error;
795
+ }
796
+ }
797
+ this.updateGenBasic(result);
798
+ logger_1.logger.debug(`Interview - got '${key}' for device '${this.ieeeAddr}'`, NS);
799
+ }
800
+ catch (error) {
801
+ logger_1.logger.debug(`Interview - failed to read attribute '${key}' from endpoint '${endpoint.ID}' (${error})`, NS);
802
+ }
803
+ }
804
+ }
805
+ }
806
+ // Enroll IAS device
807
+ if (endpoint.supportsInputCluster("ssIasZone")) {
808
+ logger_1.logger.debug(`Interview - IAS - enrolling '${this.ieeeAddr}' endpoint '${endpoint.ID}'`, NS);
809
+ const stateBefore = await endpoint.read("ssIasZone", ["iasCieAddr", "zoneState"], { sendPolicy: "immediate" });
810
+ logger_1.logger.debug(() => `Interview - IAS - before enrolling state: '${JSON.stringify(stateBefore)}'`, NS);
811
+ // Do not enroll when device has already been enrolled
812
+ if (stateBefore.zoneState !== 1 || stateBefore.iasCieAddr !== coordinator.ieeeAddr) {
813
+ logger_1.logger.debug("Interview - IAS - not enrolled, enrolling", NS);
814
+ await endpoint.write("ssIasZone", { iasCieAddr: coordinator.ieeeAddr }, { disableDefaultResponse: true, sendPolicy: "immediate" });
815
+ logger_1.logger.debug("Interview - IAS - wrote iasCieAddr", NS);
816
+ // There are 2 enrollment procedures:
817
+ // - Auto enroll: coordinator has to send enrollResponse without receiving an enroll request
818
+ // this case is handled below.
819
+ // - Manual enroll: coordinator replies to enroll request with an enroll response.
820
+ // this case in hanled in onZclData().
821
+ // https://github.com/Koenkk/zigbee2mqtt/issues/4569#issuecomment-706075676
822
+ await (0, utils_1.wait)(500);
823
+ logger_1.logger.debug(`IAS - '${this.ieeeAddr}' sending enroll response (auto enroll)`, NS);
824
+ const payload = { enrollrspcode: 0, zoneid: 23 };
825
+ await endpoint.command("ssIasZone", "enrollRsp", payload, { disableDefaultResponse: true, sendPolicy: "immediate" });
826
+ let enrolled = false;
827
+ for (let attempt = 0; attempt < 20; attempt++) {
828
+ await (0, utils_1.wait)(500);
829
+ const stateAfter = await endpoint.read("ssIasZone", ["iasCieAddr", "zoneState"], { sendPolicy: "immediate" });
830
+ logger_1.logger.debug(() => `Interview - IAS - after enrolling state (${attempt}): '${JSON.stringify(stateAfter)}'`, NS);
831
+ if (stateAfter.zoneState === 1) {
832
+ enrolled = true;
833
+ break;
834
+ }
835
+ }
836
+ if (enrolled) {
837
+ logger_1.logger.debug(`Interview - IAS successfully enrolled '${this.ieeeAddr}' endpoint '${endpoint.ID}'`, NS);
838
+ }
839
+ else {
840
+ throw new Error(`Interview failed because of failed IAS enroll (zoneState didn't change ('${this.ieeeAddr}')`);
841
+ }
842
+ }
843
+ else {
844
+ logger_1.logger.debug("Interview - IAS - already enrolled, skipping enroll", NS);
845
+ }
846
+ }
847
+ }
848
+ // Bind poll control
849
+ try {
850
+ for (const endpoint of this.endpoints.filter((e) => e.supportsInputCluster("genPollCtrl"))) {
851
+ logger_1.logger.debug(`Interview - Poll control - binding '${this.ieeeAddr}' endpoint '${endpoint.ID}'`, NS);
852
+ await endpoint.bind("genPollCtrl", coordinator.endpoints[0]);
853
+ const pollPeriod = await endpoint.read("genPollCtrl", ["checkinInterval"], { sendPolicy: "immediate" });
854
+ this._checkinInterval = pollPeriod.checkinInterval / 4; // convert to seconds
855
+ this.resetPendingRequestTimeout();
856
+ }
857
+ /* v8 ignore start */
858
+ }
859
+ catch (error) {
860
+ logger_1.logger.debug(`Interview - failed to bind genPollCtrl (${error})`, NS);
861
+ }
862
+ /* v8 ignore stop */
863
+ }
864
+ async updateNodeDescriptor() {
865
+ const clusterId = Zdo.ClusterId.NODE_DESCRIPTOR_REQUEST;
866
+ const adapter = entity_1.default.getAdapterByID(this.databaseID);
867
+ if (!adapter) {
868
+ throw new Error(`No adapter found for database ID ${this.databaseID}`);
869
+ }
870
+ const zdoPayload = Zdo.Buffalo.buildRequest(adapter.hasZdoMessageOverhead, clusterId, this.networkAddress);
871
+ const response = await adapter.sendZdo(this.ieeeAddr, this.networkAddress, clusterId, zdoPayload, false);
872
+ if (!Zdo.Buffalo.checkStatus(response)) {
873
+ throw new Zdo.StatusError(response[0]);
874
+ }
875
+ // TODO: make use of: capabilities.rxOnWhenIdle, maxIncTxSize, maxOutTxSize, serverMask.stackComplianceRevision
876
+ const nodeDescriptor = response[1];
877
+ this._manufacturerID = nodeDescriptor.manufacturerCode;
878
+ switch (nodeDescriptor.logicalType) {
879
+ case 0x0:
880
+ this._type = "Coordinator";
881
+ break;
882
+ case 0x1:
883
+ this._type = "Router";
884
+ break;
885
+ case 0x2:
886
+ this._type = "EndDevice";
887
+ break;
888
+ }
889
+ logger_1.logger.debug(`Interview - got node descriptor for device '${this.ieeeAddr}'`, NS);
890
+ // TODO: define a property on Device for this value (would be good to have it displayed)
891
+ // log for devices older than 1 from current revision
892
+ if (nodeDescriptor.serverMask.stackComplianceRevision < ZSpec.ZIGBEE_REVISION - 1) {
893
+ // always 0 before revision 21 where field was added
894
+ const rev = nodeDescriptor.serverMask.stackComplianceRevision < 21 ? "pre-21" : nodeDescriptor.serverMask.stackComplianceRevision;
895
+ logger_1.logger.info(`Device '${this.ieeeAddr}' is only compliant to revision '${rev}' of the Zigbee specification (current revision: ${ZSpec.ZIGBEE_REVISION}).`, NS);
896
+ }
897
+ }
898
+ async updateActiveEndpoints() {
899
+ const adapter = entity_1.default.getAdapterByID(this.databaseID);
900
+ if (!adapter) {
901
+ throw new Error(`No adapter found for database ID ${this.databaseID}`);
902
+ }
903
+ const clusterId = Zdo.ClusterId.ACTIVE_ENDPOINTS_REQUEST;
904
+ const zdoPayload = Zdo.Buffalo.buildRequest(adapter.hasZdoMessageOverhead, clusterId, this.networkAddress);
905
+ const response = await adapter.sendZdo(this.ieeeAddr, this.networkAddress, clusterId, zdoPayload, false);
906
+ if (!Zdo.Buffalo.checkStatus(response)) {
907
+ throw new Zdo.StatusError(response[0]);
908
+ }
909
+ const activeEndpoints = response[1];
910
+ // Make sure that the endpoint are sorted.
911
+ activeEndpoints.endpointList.sort((a, b) => a - b);
912
+ for (const endpoint of activeEndpoints.endpointList) {
913
+ // Some devices, e.g. TERNCY return endpoint 0 in the active endpoints request.
914
+ // This is not a valid endpoint number according to the ZCL, requesting a simple descriptor will result
915
+ // into an error. Therefore we filter it, more info: https://github.com/Koenkk/zigbee-herdsman/issues/82
916
+ if (endpoint !== 0 && !this.getEndpoint(endpoint)) {
917
+ this._endpoints.push(endpoint_1.default.create(this.databaseID, endpoint, undefined, undefined, [], [], this.networkAddress, this.ieeeAddr));
918
+ }
919
+ }
920
+ // Remove disappeared endpoints (can happen with e.g. custom devices).
921
+ this._endpoints = this._endpoints.filter((e) => activeEndpoints.endpointList.includes(e.ID));
922
+ }
923
+ /**
924
+ * Request device to advertise its network address.
925
+ * Note: This does not actually update the device property (if needed), as this is already done with `zdoResponse` event in Controller.
926
+ */
927
+ async requestNetworkAddress() {
928
+ const clusterId = Zdo.ClusterId.NETWORK_ADDRESS_REQUEST;
929
+ const adapter = entity_1.default.getAdapterByID(this.databaseID);
930
+ if (!adapter) {
931
+ throw new Error(`No adapter found for database ID ${this.databaseID}`);
932
+ }
933
+ const zdoPayload = Zdo.Buffalo.buildRequest(adapter.hasZdoMessageOverhead, clusterId, this.ieeeAddr, false, 0);
934
+ await adapter.sendZdo(this.ieeeAddr, ZSpec.BroadcastAddress.RX_ON_WHEN_IDLE, clusterId, zdoPayload, true);
935
+ }
936
+ async removeFromNetwork() {
937
+ const adapter = entity_1.default.getAdapterByID(this.databaseID);
938
+ if (!adapter) {
939
+ throw new Error(`No adapter found for database ID ${this.databaseID}`);
940
+ }
941
+ if (this._type === "GreenPower") {
942
+ const payload = {
943
+ options: 0x002550,
944
+ srcID: Number(this.ieeeAddr),
945
+ };
946
+ const frame = Zcl.Frame.create(Zcl.FrameType.SPECIFIC, Zcl.Direction.SERVER_TO_CLIENT, true, undefined, zclTransactionSequenceNumber_1.default.next(), "pairing", 33, payload, this.customClusters);
947
+ await adapter.sendZclFrameToAll(242, frame, 242, enums_1.BroadcastAddress.RX_ON_WHEN_IDLE);
948
+ }
949
+ else {
950
+ const clusterId = Zdo.ClusterId.LEAVE_REQUEST;
951
+ const zdoPayload = Zdo.Buffalo.buildRequest(adapter.hasZdoMessageOverhead, clusterId, this.ieeeAddr, Zdo.LeaveRequestFlags.WITHOUT_REJOIN);
952
+ const response = await adapter.sendZdo(this.ieeeAddr, this.networkAddress, clusterId, zdoPayload, false);
953
+ if (!Zdo.Buffalo.checkStatus(response)) {
954
+ throw new Zdo.StatusError(response[0]);
955
+ }
956
+ }
957
+ this.removeFromDatabase();
958
+ }
959
+ removeFromDatabase() {
960
+ Device.loadFromDatabaseIfNecessary();
961
+ for (const endpoint of this.endpoints) {
962
+ endpoint.removeFromAllGroupsDatabase();
963
+ }
964
+ const database = entity_1.default.getDatabaseByID(this.databaseID);
965
+ if (database?.has(this.ID)) {
966
+ database.remove(this.ID);
967
+ }
968
+ Device.deletedDevices.get(this.databaseID)?.set(this.ieeeAddr, this);
969
+ Device.devices.get(this.databaseID)?.delete(this.ieeeAddr);
970
+ // Clear all data in case device joins again
971
+ // Green power devices are never interviewed, keep existing interview state.
972
+ this._interviewState = this.type === "GreenPower" ? this._interviewState : InterviewState.Pending;
973
+ this.meta = {};
974
+ const newEndpoints = [];
975
+ for (const endpoint of this.endpoints) {
976
+ newEndpoints.push(endpoint_1.default.create(this.databaseID, endpoint.ID, endpoint.profileID, endpoint.deviceID, endpoint.inputClusters, endpoint.outputClusters, this.networkAddress, this.ieeeAddr));
977
+ }
978
+ this._endpoints = newEndpoints;
979
+ }
980
+ async lqi() {
981
+ const adapter = entity_1.default.getAdapterByID(this.databaseID);
982
+ if (!adapter) {
983
+ throw new Error(`No adapter found for database ID ${this.databaseID}`);
984
+ }
985
+ const clusterId = Zdo.ClusterId.LQI_TABLE_REQUEST;
986
+ const table = [];
987
+ const request = async (startIndex) => {
988
+ const zdoPayload = Zdo.Buffalo.buildRequest(adapter.hasZdoMessageOverhead, clusterId, startIndex);
989
+ const response = await adapter.sendZdo(this.ieeeAddr, this.networkAddress, clusterId, zdoPayload, false);
990
+ if (!Zdo.Buffalo.checkStatus(response)) {
991
+ throw new Zdo.StatusError(response[0]);
992
+ }
993
+ const result = response[1];
994
+ table.push(...result.entryList);
995
+ return [result.neighborTableEntries, result.entryList.length];
996
+ };
997
+ let [tableEntries, entryCount] = await request(0);
998
+ const size = tableEntries;
999
+ let nextStartIndex = entryCount;
1000
+ while (table.length < size) {
1001
+ [tableEntries, entryCount] = await request(nextStartIndex);
1002
+ nextStartIndex += entryCount;
1003
+ }
1004
+ return table;
1005
+ }
1006
+ async routingTable() {
1007
+ const adapter = entity_1.default.getAdapterByID(this.databaseID);
1008
+ if (!adapter) {
1009
+ throw new Error(`No adapter found for database ID ${this.databaseID}`);
1010
+ }
1011
+ const clusterId = Zdo.ClusterId.ROUTING_TABLE_REQUEST;
1012
+ const table = [];
1013
+ const request = async (startIndex) => {
1014
+ const zdoPayload = Zdo.Buffalo.buildRequest(adapter.hasZdoMessageOverhead, clusterId, startIndex);
1015
+ const response = await adapter.sendZdo(this.ieeeAddr, this.networkAddress, clusterId, zdoPayload, false);
1016
+ if (!Zdo.Buffalo.checkStatus(response)) {
1017
+ throw new Zdo.StatusError(response[0]);
1018
+ }
1019
+ const result = response[1];
1020
+ table.push(...result.entryList);
1021
+ return [result.routingTableEntries, result.entryList.length];
1022
+ };
1023
+ let [tableEntries, entryCount] = await request(0);
1024
+ const size = tableEntries;
1025
+ let nextStartIndex = entryCount;
1026
+ while (table.length < size) {
1027
+ [tableEntries, entryCount] = await request(nextStartIndex);
1028
+ nextStartIndex += entryCount;
1029
+ }
1030
+ return table;
1031
+ }
1032
+ async bindingTable() {
1033
+ const adapter = entity_1.default.getAdapterByID(this.databaseID);
1034
+ if (!adapter) {
1035
+ throw new Error(`No adapter found for database ID ${this.databaseID}`);
1036
+ }
1037
+ const clusterId = Zdo.ClusterId.BINDING_TABLE_REQUEST;
1038
+ const table = [];
1039
+ const request = async (startIndex) => {
1040
+ const zdoPayload = Zdo.Buffalo.buildRequest(adapter.hasZdoMessageOverhead, clusterId, startIndex);
1041
+ const response = await adapter.sendZdo(this.ieeeAddr, this.networkAddress, clusterId, zdoPayload, false);
1042
+ if (!Zdo.Buffalo.checkStatus(response)) {
1043
+ throw new Zdo.StatusError(response[0]);
1044
+ }
1045
+ const result = response[1];
1046
+ table.push(...result.entryList);
1047
+ return [result.bindingTableEntries, result.entryList.length];
1048
+ };
1049
+ let [tableEntries, entryCount] = await request(0);
1050
+ const size = tableEntries;
1051
+ let nextStartIndex = entryCount;
1052
+ while (table.length < size) {
1053
+ [tableEntries, entryCount] = await request(nextStartIndex);
1054
+ nextStartIndex += entryCount;
1055
+ }
1056
+ for (const ep of this._endpoints) {
1057
+ const newBinds = [];
1058
+ for (const entry of table) {
1059
+ if (entry.sourceEui64 !== this.ieeeAddr || entry.sourceEndpoint !== ep.ID) {
1060
+ continue;
1061
+ }
1062
+ if (entry.destAddrMode === 0x01) {
1063
+ newBinds.push({ type: "group", cluster: entry.clusterId, groupID: entry.dest });
1064
+ }
1065
+ else {
1066
+ newBinds.push({
1067
+ type: "endpoint",
1068
+ cluster: entry.clusterId,
1069
+ deviceIeeeAddress: entry.dest,
1070
+ endpointID: entry.destEndpoint,
1071
+ });
1072
+ }
1073
+ }
1074
+ ep.saveBindings(newBinds);
1075
+ }
1076
+ return table;
1077
+ }
1078
+ /**
1079
+ * Clear all the bindings of a device.
1080
+ * Support of this command is optional (only mandatory if device has a binding table).
1081
+ * @param eui64List list of bind entries to match and clear. Send `["0xffffffffffffffff"]` to clear all.
1082
+ */
1083
+ async clearAllBindings(eui64List) {
1084
+ const adapter = entity_1.default.getAdapterByID(this.databaseID);
1085
+ if (!adapter) {
1086
+ throw new Error(`No adapter found for database ID ${this.databaseID}`);
1087
+ }
1088
+ const clusterId = Zdo.ClusterId.CLEAR_ALL_BINDINGS_REQUEST;
1089
+ const zdoPayload = Zdo.Buffalo.buildRequest(adapter.hasZdoMessageOverhead, clusterId, { eui64List });
1090
+ const response = await adapter.sendZdo(this.ieeeAddr, this.networkAddress, clusterId, zdoPayload, false);
1091
+ if (!Zdo.Buffalo.checkStatus(response)) {
1092
+ throw new Zdo.StatusError(response[0]);
1093
+ }
1094
+ if ((eui64List.length === 1 && eui64List[0].toLowerCase() === ZSpec.BLANK_EUI64) ||
1095
+ eui64List.some((eui64) => eui64.toLowerCase() === this.ieeeAddr)) {
1096
+ for (const ep of this._endpoints) {
1097
+ ep.clearBindings();
1098
+ }
1099
+ }
1100
+ }
1101
+ async ping(disableRecovery = true) {
1102
+ // Zigbee does not have an official pinging mechanism. Use a read request
1103
+ // of a mandatory basic cluster attribute to keep it as lightweight as
1104
+ // possible.
1105
+ const endpoint = this.endpoints.find((ep) => ep.inputClusters.includes(0)) ?? this.endpoints[0];
1106
+ await endpoint.read("genBasic", ["zclVersion"], { disableRecovery, sendPolicy: "immediate" });
1107
+ }
1108
+ addCustomCluster(name, cluster) {
1109
+ (0, node_assert_1.default)(![Zcl.Clusters.touchlink.ID, Zcl.Clusters.greenPower.ID].includes(cluster.ID), "Overriding of greenPower or touchlink cluster is not supported");
1110
+ if (Zcl.Utils.isClusterName(name)) {
1111
+ const existingCluster = this._customClusters[name] ?? Zcl.Clusters[name];
1112
+ // Extend existing cluster
1113
+ (0, node_assert_1.default)(existingCluster.ID === cluster.ID, `Custom cluster ID (${cluster.ID}) should match existing cluster ID (${existingCluster.ID})`);
1114
+ cluster = {
1115
+ ID: cluster.ID,
1116
+ manufacturerCode: cluster.manufacturerCode,
1117
+ attributes: { ...existingCluster.attributes, ...cluster.attributes },
1118
+ commands: { ...existingCluster.commands, ...cluster.commands },
1119
+ commandsResponse: { ...existingCluster.commandsResponse, ...cluster.commandsResponse },
1120
+ };
1121
+ }
1122
+ this._customClusters[name] = cluster;
1123
+ }
1124
+ #waitForOtaCommand(endpointId, commandId, transactionSequenceNumber, timeout) {
1125
+ const adapter = entity_1.default.getAdapterByID(this.databaseID);
1126
+ if (!adapter) {
1127
+ throw new Error(`No adapter found for database ID ${this.databaseID}`);
1128
+ }
1129
+ const waiter = adapter.waitFor(this.networkAddress, endpointId, Zcl.FrameType.SPECIFIC, Zcl.Direction.CLIENT_TO_SERVER, transactionSequenceNumber, Zcl.Clusters.genOta.ID, commandId, timeout);
1130
+ const promise = new Promise((resolve, reject) => {
1131
+ waiter.promise.then((payload) => {
1132
+ try {
1133
+ const frame = Zcl.Frame.fromBuffer(payload.clusterID, payload.header, payload.data, this.customClusters);
1134
+ resolve(frame);
1135
+ }
1136
+ catch (error) {
1137
+ reject(error);
1138
+ }
1139
+ }, (error) => reject(error));
1140
+ });
1141
+ return { promise, cancel: waiter.cancel };
1142
+ }
1143
+ async findMatchingOtaImage(source, current, extraMetas) {
1144
+ logger_1.logger.debug(() => `Getting image metadata for ${this.ieeeAddr}...`, NS);
1145
+ const images = await (0, ota_1.getOtaIndex)(source);
1146
+ // NOTE: Officially an image can be determined with a combination of manufacturerCode and imageType.
1147
+ // However several manufacturers do not follow the spec properly.
1148
+ // The index provides the needed extra metadata to prevent mismatches.
1149
+ // e.g. Tuya must match on manufacturerName, Gledopto on modelId...
1150
+ return images.find((i) => i.imageType === current.imageType &&
1151
+ i.manufacturerCode === current.manufacturerCode &&
1152
+ (i.minFileVersion === undefined || current.fileVersion >= i.minFileVersion) &&
1153
+ (i.maxFileVersion === undefined || current.fileVersion <= i.maxFileVersion) &&
1154
+ // let extra metas override the match from this.modelID, same for manufacturerName
1155
+ (!i.modelId || i.modelId === this.modelID || i.modelId === extraMetas.modelId) &&
1156
+ (!i.manufacturerName ||
1157
+ // biome-ignore lint/style/noNonNullAssertion: ignored using `--suppress`
1158
+ i.manufacturerName.includes(this.manufacturerName) ||
1159
+ // biome-ignore lint/style/noNonNullAssertion: ignored using `--suppress`
1160
+ i.manufacturerName.includes(extraMetas.manufacturerName)) &&
1161
+ (!extraMetas.otaHeaderString || i.otaHeaderString === extraMetas.otaHeaderString) &&
1162
+ (i.hardwareVersionMin === undefined ||
1163
+ (current.hardwareVersion !== undefined && current.hardwareVersion >= i.hardwareVersionMin) ||
1164
+ (extraMetas.hardwareVersionMin !== undefined && extraMetas.hardwareVersionMin >= i.hardwareVersionMin)) &&
1165
+ (i.hardwareVersionMax === undefined ||
1166
+ (current.hardwareVersion !== undefined && current.hardwareVersion <= i.hardwareVersionMax) ||
1167
+ (extraMetas.hardwareVersionMax !== undefined && extraMetas.hardwareVersionMax <= i.hardwareVersionMax)));
1168
+ }
1169
+ async #notifyOta(endpoint) {
1170
+ // Some devices (e.g. Insta) take a very long trying to discover the correct coordinator EP for OTA
1171
+ const queryNextImageRequest = this.#waitForOtaCommand(endpoint.ID, Zcl.Clusters.genOta.commands.queryNextImageRequest.ID, undefined, 60000);
1172
+ try {
1173
+ await endpoint.commandResponse("genOta", "imageNotify", { payloadType: 0, queryJitter: 100 }, { sendPolicy: "immediate" });
1174
+ const response = await queryNextImageRequest.promise;
1175
+ return [response.payload, response.header.transactionSequenceNumber];
1176
+ }
1177
+ catch {
1178
+ queryNextImageRequest.cancel();
1179
+ throw new Error(`Device didn't respond to OTA request`);
1180
+ }
1181
+ }
1182
+ /**
1183
+ * If `current` is undefined, will automatically notify and reply to query with `NO_IMAGE_AVAILABLE` (stops device from doing further requests).
1184
+ */
1185
+ async checkOta(source, current, extraMetas, endpoint = this.endpoints.find((e) => e.supportsOutputCluster("genOta"))) {
1186
+ (0, node_assert_1.default)(endpoint !== undefined, `No endpoint found with OTA cluster support for ${this.ieeeAddr}`);
1187
+ if (this.modelID === "PP-WHT-US") {
1188
+ // see https://github.com/Koenkk/zigbee-OTA/pull/14
1189
+ const scenesEndpoint = this.endpoints.find((e) => e.supportsOutputCluster("genScenes"));
1190
+ if (scenesEndpoint !== undefined) {
1191
+ await scenesEndpoint.write("genScenes", { currentGroup: 49502 }, { disableDefaultResponse: true, sendPolicy: "immediate" });
1192
+ }
1193
+ }
1194
+ if (current === undefined) {
1195
+ let queryTsn;
1196
+ [current, queryTsn] = await this.#notifyOta(endpoint);
1197
+ await endpoint.commandResponse("genOta", "queryNextImageResponse", { status: Zcl.Status.NO_IMAGE_AVAILABLE }, undefined, queryTsn);
1198
+ }
1199
+ logger_1.logger.debug(() => `Checking OTA ${this.ieeeAddr} ${source.downgrade ? "downgrade" : "upgrade"} image availability, current=${JSON.stringify(current)}`, NS);
1200
+ if (this.meta.lumiFileVersion &&
1201
+ (this.modelID === "lumi.airrtc.agl001" || this.modelID === "lumi.curtain.acn003" || this.modelID === "lumi.curtain.agl001")) {
1202
+ // The current.fileVersion which comes from the device is wrong.
1203
+ // Use the `lumiFileVersion` which comes from the manuSpecificLumi.attributeReport instead.
1204
+ // https://github.com/Koenkk/zigbee2mqtt/issues/16345#issuecomment-1454835056
1205
+ // https://github.com/Koenkk/zigbee2mqtt/issues/16345 doesn't seem to be needed for all
1206
+ // https://github.com/Koenkk/zigbee2mqtt/issues/15745
1207
+ current = { ...current, fileVersion: this.meta.lumiFileVersion };
1208
+ }
1209
+ const meta = await this.findMatchingOtaImage(source, current, extraMetas);
1210
+ if (!meta) {
1211
+ // no image in repo/URL for specified device
1212
+ return {
1213
+ available: false,
1214
+ current,
1215
+ };
1216
+ }
1217
+ logger_1.logger.debug(() => `OTA ${source.downgrade ? "downgrade" : "upgrade"} image availability for ${this.ieeeAddr}, available=${JSON.stringify(meta)}`, NS);
1218
+ return {
1219
+ available: meta.force ? true : source.downgrade ? current.fileVersion > meta.fileVersion : current.fileVersion < meta.fileVersion,
1220
+ current,
1221
+ availableMeta: meta,
1222
+ };
1223
+ }
1224
+ async updateOta(source, requestPayload, requestTsn, extraMetas, onProgress, dataSettings, endpoint = this.endpoints.find((e) => e.supportsOutputCluster("genOta"))) {
1225
+ (0, node_assert_1.default)(this.#otaInProgress === false, `OTA already in progress for ${this.ieeeAddr}`);
1226
+ (0, node_assert_1.default)(endpoint !== undefined, `No endpoint found with OTA cluster support for ${this.ieeeAddr}`);
1227
+ if (source === undefined) {
1228
+ (0, node_assert_1.default)(this.#scheduledOta !== undefined, `No currently scheduled OTA for ${this.ieeeAddr}`);
1229
+ source = this.#scheduledOta;
1230
+ }
1231
+ this.#otaInProgress = true;
1232
+ // always expected both undefined if one is, but just in case
1233
+ if (requestPayload === undefined || requestTsn === undefined) {
1234
+ try {
1235
+ [requestPayload, requestTsn] = await this.#notifyOta(endpoint);
1236
+ }
1237
+ finally {
1238
+ this.#otaInProgress = false;
1239
+ }
1240
+ }
1241
+ let available = false;
1242
+ let image;
1243
+ if (source.url && !source.url.endsWith(".json")) {
1244
+ // firmware file at `source.url`
1245
+ try {
1246
+ const downloadedFile = await (0, ota_1.getOtaFirmware)(source.url, undefined);
1247
+ image = (0, ota_1.parseOtaImage)(downloadedFile);
1248
+ available = source.downgrade
1249
+ ? requestPayload.fileVersion > image.header.fileVersion
1250
+ : requestPayload.fileVersion < image.header.fileVersion;
1251
+ logger_1.logger.debug(() =>
1252
+ // biome-ignore lint/style/noNonNullAssertion: valid from above, won't change after assignment
1253
+ `Parsed image from '${source.url}' for ${this.ieeeAddr}, header=${JSON.stringify(image.header)}`, NS);
1254
+ }
1255
+ catch (error) {
1256
+ logger_1.logger.error(`Failed to parse OTA image from '${source.url}' for ${this.ieeeAddr}, aborting (${error.message})`, NS);
1257
+ // biome-ignore lint/style/noNonNullAssertion: expected valid
1258
+ logger_1.logger.debug(error.stack, NS);
1259
+ }
1260
+ }
1261
+ else {
1262
+ let availableMeta;
1263
+ try {
1264
+ // index file at `source.url` (or undefined to use defaults)
1265
+ ({ available, availableMeta } = await this.checkOta(source, requestPayload, extraMetas, endpoint));
1266
+ }
1267
+ finally {
1268
+ this.#otaInProgress = false;
1269
+ }
1270
+ if (available && availableMeta) {
1271
+ try {
1272
+ const downloadedFile = await (0, ota_1.getOtaFirmware)(availableMeta.url, availableMeta.sha512);
1273
+ image = (0, ota_1.parseOtaImage)(downloadedFile);
1274
+ logger_1.logger.debug(() =>
1275
+ // biome-ignore lint/style/noNonNullAssertion: valid from above, won't change after assignment
1276
+ `Parsed image from '${availableMeta.url}' for ${this.ieeeAddr}, header=${JSON.stringify(image.header)}`, NS);
1277
+ }
1278
+ catch (error) {
1279
+ logger_1.logger.error(`Failed to parse OTA image for ${this.ieeeAddr}, aborting (${error.message})`, NS);
1280
+ // biome-ignore lint/style/noNonNullAssertion: expected valid
1281
+ logger_1.logger.debug(error.stack, NS);
1282
+ }
1283
+ }
1284
+ else {
1285
+ logger_1.logger.info(() => `No OTA ${source.downgrade ? "downgrade" : "upgrade"} image currently available for ${this.ieeeAddr}`, NS);
1286
+ }
1287
+ }
1288
+ // reply to `queryNextImageRequest` now that we have the data for it, should trigger image block/page request from device
1289
+ // NOTE: previous code had try/catch wrapping with ignored error, but that doesn't look good (would fail to start OTA from device side)
1290
+ try {
1291
+ await endpoint.commandResponse("genOta", "queryNextImageResponse", image && available
1292
+ ? {
1293
+ status: Zcl.Status.SUCCESS,
1294
+ manufacturerCode: image.header.manufacturerCode,
1295
+ imageType: image.header.imageType,
1296
+ fileVersion: image.header.fileVersion,
1297
+ imageSize: image.header.totalImageSize,
1298
+ }
1299
+ : { status: Zcl.Status.NO_IMAGE_AVAILABLE }, undefined, requestTsn);
1300
+ }
1301
+ finally {
1302
+ this.#otaInProgress = false;
1303
+ }
1304
+ if (!image || !available) {
1305
+ this.#otaInProgress = false;
1306
+ return [requestPayload, undefined];
1307
+ }
1308
+ logger_1.logger.debug(() => `Starting OTA update for ${this.ieeeAddr}`, NS);
1309
+ const session = new ota_1.OtaSession(this.ieeeAddr, endpoint, image, onProgress, dataSettings, this.#waitForOtaCommand.bind(this));
1310
+ let endResult;
1311
+ try {
1312
+ endResult = await session.run();
1313
+ }
1314
+ finally {
1315
+ this.#otaInProgress = false;
1316
+ }
1317
+ logger_1.logger.debug(() => `Received upgrade end request for ${this.ieeeAddr}: ${JSON.stringify(endResult.payload)}`, NS);
1318
+ if (endResult.payload.status === Zcl.Status.SUCCESS) {
1319
+ try {
1320
+ const currentTime = timeService.timestampToZigbeeUtcTime(Date.now());
1321
+ await endpoint.commandResponse("genOta", "upgradeEndResponse", {
1322
+ manufacturerCode: image.header.manufacturerCode,
1323
+ imageType: image.header.imageType,
1324
+ fileVersion: image.header.fileVersion,
1325
+ currentTime,
1326
+ upgradeTime: currentTime + 1, // TODO: could this tiny offset be a problem for some stacks?
1327
+ }, undefined, endResult.header.transactionSequenceNumber);
1328
+ onProgress(100, 0);
1329
+ logger_1.logger.info(() => `Update of ${this.ieeeAddr} successful (${Math.round((performance.now() - session.startTime) / 1000)} seconds). Waiting for device announce...`, NS);
1330
+ let timer;
1331
+ await new Promise((resolve) => {
1332
+ const onDeviceAnnounce = () => {
1333
+ clearTimeout(timer);
1334
+ logger_1.logger.debug(() => `Received device announce for ${this.ieeeAddr}, OTA update finished.`, NS);
1335
+ resolve();
1336
+ };
1337
+ // force "finished" after given time
1338
+ timer = setTimeout(() => {
1339
+ this.removeListener("deviceAnnounce", onDeviceAnnounce);
1340
+ logger_1.logger.debug(() => `Timed out waiting for device announce for ${this.ieeeAddr}, OTA update considered finished.`, NS);
1341
+ resolve();
1342
+ }, 120000 /** consider "done" after timeout even if no announce seen */);
1343
+ this.once("deviceAnnounce", onDeviceAnnounce);
1344
+ });
1345
+ // only "cancel" possible scheduled OTA when successful
1346
+ this.#scheduledOta = undefined;
1347
+ this.#otaInProgress = false;
1348
+ return [
1349
+ requestPayload,
1350
+ {
1351
+ fieldControl: 0,
1352
+ manufacturerCode: image.header.manufacturerCode,
1353
+ imageType: image.header.imageType,
1354
+ fileVersion: image.header.fileVersion,
1355
+ },
1356
+ ];
1357
+ }
1358
+ catch (error) {
1359
+ this.#otaInProgress = false;
1360
+ throw new Error(`OTA upgrade end response failed: ${error.message}`);
1361
+ }
1362
+ }
1363
+ else {
1364
+ /**
1365
+ * For other status value received such as INVALID_IMAGE, REQUIRE_MORE_IMAGE, or ABORT,
1366
+ * the upgrade server SHALL not send Upgrade End Response command but it SHALL send default
1367
+ * response command with status of success and it SHALL wait for the client to reinitiate the upgrade process.
1368
+ */
1369
+ try {
1370
+ await endpoint.defaultResponse(Zcl.Clusters.genOta.commands.upgradeEndRequest.ID, Zcl.Status.SUCCESS, Zcl.Clusters.genOta.ID, endResult.header.transactionSequenceNumber);
1371
+ }
1372
+ catch (error) {
1373
+ logger_1.logger.debug(() => `OTA upgrade end request default response for ${this.ieeeAddr} failed: ${error.message}`, NS);
1374
+ }
1375
+ this.#otaInProgress = false;
1376
+ throw new Error(`OTA update of ${this.ieeeAddr} failed with reason: ${Zcl.Status[endResult.payload.status]}`);
1377
+ }
1378
+ }
1379
+ scheduleOta(source) {
1380
+ (0, node_assert_1.default)(this.endpoints.some((e) => e.supportsOutputCluster("genOta")), `No endpoint found with OTA cluster support for ${this.ieeeAddr}`);
1381
+ if (this.#scheduledOta) {
1382
+ logger_1.logger.info(`Previously scheduled OTA update for '${this.ieeeAddr}' was cancelled in favor of new schedule request`, NS);
1383
+ }
1384
+ this.#scheduledOta = source;
1385
+ logger_1.logger.info(`Scheduled OTA update for '${this.ieeeAddr}' on next request from device`, NS);
1386
+ }
1387
+ unscheduleOta() {
1388
+ if (this.#scheduledOta !== undefined) {
1389
+ this.#scheduledOta = undefined;
1390
+ logger_1.logger.info(`Previously scheduled OTA update for '${this.ieeeAddr}' was cancelled`, NS);
1391
+ }
1392
+ }
1393
+ }
1394
+ exports.Device = Device;
1395
+ exports.default = Device;
1396
+ //# sourceMappingURL=device.js.map