iobroker.zigbee 1.7.6 → 1.8.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 (97) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +368 -381
  3. package/admin/admin.js +2951 -2927
  4. package/admin/i18n/de/translations.json +108 -0
  5. package/admin/i18n/en/translations.json +108 -0
  6. package/admin/i18n/es/translations.json +102 -0
  7. package/admin/i18n/fr/translations.json +108 -0
  8. package/admin/i18n/it/translations.json +102 -0
  9. package/admin/i18n/nl/translations.json +108 -0
  10. package/admin/i18n/pl/translations.json +108 -0
  11. package/admin/i18n/pt/translations.json +102 -0
  12. package/admin/i18n/ru/translations.json +108 -0
  13. package/admin/i18n/uk/translations.json +108 -0
  14. package/admin/i18n/zh-cn/translations.json +102 -0
  15. package/admin/img/philips_hue_lom001.png +0 -0
  16. package/admin/index.html +159 -159
  17. package/admin/index_m.html +1161 -1161
  18. package/admin/moment.min.js +1 -1
  19. package/admin/shuffle.min.js +2 -2
  20. package/admin/tab_m.html +985 -944
  21. package/admin/vis-network.min.css +1 -1
  22. package/admin/vis-network.min.js +27 -27
  23. package/admin/words.js +110 -110
  24. package/docs/de/img/CC2531.png +0 -0
  25. package/docs/de/img/CC2538_CC2592_PA.PNG +0 -0
  26. package/docs/de/img/CC2591.png +0 -0
  27. package/docs/de/img/boards.jpg +0 -0
  28. package/docs/de/img/cc26x2r.PNG +0 -0
  29. package/docs/de/img/results.jpg +0 -0
  30. package/docs/de/img/sku_429478_2.png +0 -0
  31. package/docs/de/img/sku_429601_2.png +0 -0
  32. package/docs/de/readme.md +27 -0
  33. package/docs/en/img/CC2531.png +0 -0
  34. package/docs/en/img/CC2591.png +0 -0
  35. package/docs/en/img/deconz.png +0 -0
  36. package/docs/en/img/sku_429478_2.png +0 -0
  37. package/docs/en/img/sku_429601_2.png +0 -0
  38. package/docs/en/readme.md +30 -0
  39. package/docs/flashing_via_arduino_(en).md +110 -0
  40. package/docs/ru/img/CC2531.png +0 -0
  41. package/docs/ru/img/CC2591.png +0 -0
  42. package/docs/ru/img/sku_429478_2.png +0 -0
  43. package/docs/ru/img/sku_429601_2.png +0 -0
  44. package/docs/ru/readme.md +28 -0
  45. package/docs/tutorial/CC2530_20190425.zip +0 -0
  46. package/docs/tutorial/CC2530_CC2591_20190515.zip +0 -0
  47. package/docs/tutorial/CC2530_CC2592_20190515.zip +0 -0
  48. package/docs/tutorial/CC2531_20190425.zip +0 -0
  49. package/docs/tutorial/adm5_1.PNG +0 -0
  50. package/docs/tutorial/adm5_2.PNG +0 -0
  51. package/docs/tutorial/cat.PNG +0 -0
  52. package/docs/tutorial/groups-1.png +0 -0
  53. package/docs/tutorial/groups-2.png +0 -0
  54. package/docs/tutorial/inst.PNG +0 -0
  55. package/docs/tutorial/reflash-finish.PNG +0 -0
  56. package/docs/tutorial/reflash-step0.png +0 -0
  57. package/docs/tutorial/reflash-step1.PNG +0 -0
  58. package/docs/tutorial/reflash-step2.PNG +0 -0
  59. package/docs/tutorial/settings.png +0 -0
  60. package/docs/tutorial/tab-dev-1.png +0 -0
  61. package/docs/tutorial/zigbee.png +0 -0
  62. package/docs/tutorial/zigbee15.png +0 -0
  63. package/io-package.json +335 -370
  64. package/lib/backup.js +171 -171
  65. package/lib/binding.js +320 -325
  66. package/lib/colors.js +465 -460
  67. package/lib/commands.js +510 -501
  68. package/lib/developer.js +145 -148
  69. package/lib/devices.js +3135 -3145
  70. package/lib/exclude.js +162 -168
  71. package/lib/exposes.js +828 -804
  72. package/lib/groups.js +340 -342
  73. package/lib/json.js +59 -60
  74. package/lib/networkmap.js +55 -56
  75. package/lib/ota.js +195 -179
  76. package/lib/rgb.js +297 -255
  77. package/lib/seriallist.js +48 -37
  78. package/lib/states.js +6405 -6416
  79. package/lib/statescontroller.js +693 -670
  80. package/lib/tools.js +54 -54
  81. package/lib/utils.js +152 -151
  82. package/lib/zbBaseExtension.js +36 -36
  83. package/lib/zbDelayedAction.js +144 -152
  84. package/lib/zbDeviceAvailability.js +319 -315
  85. package/lib/zbDeviceConfigure.js +147 -159
  86. package/lib/zbDeviceEvent.js +48 -49
  87. package/lib/zigbeecontroller.js +957 -951
  88. package/main.js +163 -147
  89. package/package.json +33 -19
  90. package/support/docgen.js +93 -93
  91. package/.eslintignore +0 -2
  92. package/.eslintrc.json +0 -37
  93. package/.github/FUNDING.yml +0 -3
  94. package/.github/stale.yml +0 -13
  95. package/.github/workflows/test-and-release.yml +0 -151
  96. package/.travis/wiki.sh +0 -28
  97. package/admin/adapter-settings.js +0 -244
@@ -1,315 +1,319 @@
1
- 'use strict';
2
-
3
- const BaseExtension = require('./zbBaseExtension');
4
- const zigbeeHerdsmanConverters = require('zigbee-herdsman-converters');
5
- const utils = require('./utils');
6
-
7
- // Some EndDevices should be pinged
8
- // e.g. E11-G13 https://github.com/Koenkk/zigbee2mqtt/issues/775#issuecomment-453683846
9
- const forcedPingable = [
10
- zigbeeHerdsmanConverters.devices.find((d) => d.model === 'E11-G13'),
11
- zigbeeHerdsmanConverters.devices.find((d) => d.model === '53170161'),
12
- zigbeeHerdsmanConverters.devices.find((d) => d.model === 'V3-BTZB'),
13
- zigbeeHerdsmanConverters.devices.find((d) => d.model === 'SPZB0001'),
14
- zigbeeHerdsmanConverters.devices.find((d) => d.model === '014G2461')
15
- ];
16
-
17
- // asgothian: 29.12.2020: Removed color and color_temp from readable
18
- // state candidates as most states do not provide a getter to ikea_transform
19
- // the data from the herdsman back to the value needed, which
20
- // will result in warnings "illegal state x,y" or "illegal state h,s" for color
21
- // and possibly sudden changes in value due to the support for color_temp
22
- // in mired and Kelvin.
23
- const toZigbeeCandidates = ['local_temperature','state', 'brightness']; //, 'color', 'color_temp'];
24
- const Hours25 = 1000 * 60 * 60 * 25;
25
- const MinAvailabilityTimeout = 300; // ping every 5 minutes with few devices
26
- const MaxAvailabilityTimeout = 1800; // ping every 30 minutes with many devices;
27
- const AverageTimeBetweenPings = 45; // on average, plan for 30 seconds between pings.
28
-
29
- /**
30
- * This extensions pings devices to check if they are online.
31
- */
32
- class DeviceAvailability extends BaseExtension {
33
- constructor(zigbee, options) {
34
- super(zigbee, options);
35
- this.availability_timeout = 300; // wait 5 min for live check
36
- this.timers = {};
37
- this.ping_counters = {};
38
- this.max_ping = 3;
39
- this.state = {};
40
- this.active_ping = true;
41
- this.forced_ping = true;
42
- this.forcedNonPingable = {};
43
- this.number_of_registered_devices = 0;
44
- // force publish availability for new devices
45
- this.zigbee.on('new', (entity) => {
46
- // wait for 1s for creating device states
47
- setTimeout(() => {
48
- this.publishAvailability(entity.device, true, true);
49
- }, 1000);
50
- });
51
- this.startDevicePingQueue = []; // simple fifo array for starting device pings
52
- this.startDevicePingTimeout = null; // handle for the timeout which empties the queue
53
- this.startDevicePingDelay = 200; // 200 ms delay between starting the ping timeout
54
- this.name = "DeviceAvailability";
55
- this.elevate_debug = false;
56
- }
57
-
58
- setOptions(options) {
59
- if (typeof(options) != 'object') return false;
60
- if (options.disableActivePing) this.active_ping = false;
61
- if (options.disableForcedPing) this.forced_ping = false;
62
- if (typeof(options.pingTimeout)=='number') this.availability_timeout = Math.min(60,options.pingTimeout);
63
- if (typeof(options.pingCount)=='number') this.max_ping = Math.min(2, options.pingCount);
64
- return true;
65
- }
66
-
67
- isPingable(device) {
68
- if (this.active_ping)
69
- {
70
- if (this.forced_ping && forcedPingable.find((d) => d && d.hasOwnProperty('zigbeeModel') && d.zigbeeModel.includes(device.modelID))) {
71
- return true;
72
- }
73
-
74
- const result = utils.isRouter(device) && !utils.isBatteryPowered(device);
75
- return result;
76
- }
77
- return false;
78
- }
79
-
80
- async getAllPingableDevices() {
81
- const clients = await this.zigbee.getClients();
82
- return clients.filter((d) => this.isPingable(d));
83
- }
84
-
85
- async registerDevicePing(device, entity) {
86
- this.debug('register device Ping for ' + JSON.stringify(device.ieeeAddr));
87
- this.forcedNonPingable[device.ieeeAddr] = false;
88
- // this.warn(`Called registerDevicePing for '${device}' of '${entity}'`);
89
- if (!this.isPingable(device)) return;
90
- // ensure we do not already have this device in the queue
91
- this.startDevicePingQueue.forEach(item => {
92
- if (item && item.device == device)
93
- return;
94
- });
95
- this.number_of_registered_devices++;
96
- this.availability_timeout = Math.max(Math.min(this.number_of_registered_devices * AverageTimeBetweenPings,MaxAvailabilityTimeout ),MinAvailabilityTimeout);
97
- this.startDevicePingQueue.push({device:device, entity:entity});
98
- if (this.startDevicePingTimeout == null)
99
- this.startDevicePingTimeout = setTimeout(async() => {
100
- await this.startDevicePing();
101
- }, this.startDevicePingDelay);
102
- }
103
-
104
- async deregisterDevicePing(device) {
105
- this.info('deregister device Ping for deactivated device ' + JSON.stringify(device.ieeeAddr));
106
- this.forcedNonPingable[device.ieeeAddr] = true;
107
- if (this.timers[device.ieeeAddr]) {
108
- clearTimeout(this.timers[device.ieeeAddr]);
109
- }
110
- }
111
-
112
- async startDevicePing() {
113
- // this.warn(JSON.stringify(this));
114
- this.startDevicePingTimeout = null;
115
- const item = this.startDevicePingQueue.shift();
116
- if (this.startDevicePingQueue.length >0) {
117
- this.startDevicePingTimeout = setTimeout(async() => {
118
- await this.startDevicePing();
119
- }, this.startDevicePingDelay);
120
- }
121
- if (item && item.hasOwnProperty('device')) {
122
- this.handleIntervalPingable(item.device, item.entity);
123
- }
124
- }
125
- async onZigbeeStarted() {
126
- // As some devices are not checked for availability (e.g. battery powered devices)
127
- // we mark these device as online by default.
128
- // NOTE: The start of active pings for pingable devices is done separately,
129
- // triggered by the 'new device' event to ensure that they are handled
130
- // identically on reconnect, disconnect and new pair (as)
131
- const clients = await this.zigbee.getClients();
132
- // this.warn('onZigbeeStarted called');
133
- for (const device of clients) {
134
-
135
- if (this.isPingable(device)) {
136
- // this.setTimerPingable(device);
137
- } else {
138
- // this.warn(`Setting '${device.ieeeAddr}' as available - battery driven`);
139
- this.publishAvailability(device, true);
140
- this.timers[device.ieeeAddr] = setInterval(() => {
141
- this.handleIntervalNotPingable(device);
142
- },utils.secondsToMilliseconds(this.availability_timeout));
143
- }
144
- }
145
- }
146
-
147
- async handleIntervalPingable(device, entity) {
148
- const ieeeAddr = device.ieeeAddr;
149
- const resolvedEntity = (entity ? entity: await this.zigbee.resolveEntity(ieeeAddr));
150
- if (!resolvedEntity) {
151
- this.debug(`Stop pinging '${ieeeAddr}' ${device.modelID}, device is not known anymore`);
152
- return;
153
- }
154
- if (this.isPingable(device)) {
155
- let pingCount = this.ping_counters[device.ieeeAddr];
156
- if (pingCount === undefined) {
157
- this.ping_counters[device.ieeeAddr] = { failed: 0, reported: 0};
158
- pingCount = { failed: 0, reported: 0};
159
- }
160
-
161
- // first see if we can "ping" the device by reading a Status
162
- try {
163
- for (const key of toZigbeeCandidates) {
164
- const converter = resolvedEntity.mapped.toZigbee.find((tz) => tz.key.includes(key));
165
- if (converter) {
166
- await converter.convertGet(device.endpoints[0], key, {});
167
- this.debug(`Successful read state '${key}' of '${device.ieeeAddr}' in stead of pinging`);
168
- this.setTimerPingable(device, 1);
169
- this.ping_counters[device.ieeeAddr].failed = 0;
170
- return;
171
- }
172
- }
173
- }
174
- catch (error) {
175
- this.sendError(error);
176
- this.debug(`Exception in readState of '${device.ieeeAddr}' - error : '${error}'`);
177
- // intentionally empty: Just present to ensure we cause no harm
178
- // when reading the state fails. => fall back on standard Ping function
179
- }
180
- try {
181
- await device.ping();
182
- this.publishAvailability(device, true);
183
- this.debug(`Successfully pinged ${ieeeAddr} ${device.modelID}`);
184
- this.setTimerPingable(device, 1);
185
- this.ping_counters[device.ieeeAddr].failed = 0;
186
- } catch (error) {
187
- this.publishAvailability(device, false);
188
- if (pingCount.failed++ <= this.max_ping)
189
- {
190
- if (pingCount.failed < 2 && pingCount.reported < this.max_ping) {
191
- this.warn(`Failed to ping ${ieeeAddr} ${device.modelID}`);
192
- pingCount.reported++;
193
- }
194
- else {
195
- this.debug(`Failed to ping ${ieeeAddr} ${device.modelID} on ${pingCount} consecutive attempts`);
196
- }
197
- this.setTimerPingable(device, pingCount.failed);
198
- this.ping_counters[device.ieeeAddr]= pingCount;
199
- }
200
- else {
201
- this.warn(`Stopping to ping ${ieeeAddr} ${device.modelID} after ${pingCount.failed} ping attempts`);
202
- }
203
- }
204
- }
205
- }
206
-
207
-
208
- async handleIntervalNotPingable(device) {
209
- const entity = await this.zigbee.resolveEntity(device.ieeeAddr);
210
- if (!entity || !device.lastSeen) {
211
- return;
212
- }
213
-
214
- const ago = Date.now() - entity.device.lastSeen;
215
- this.debug(`Non-pingable device ${entity.device.ieeeAddr} ${entity.device.modelID} was last seen '${ago / 1000}' seconds ago.`);
216
-
217
- if (ago > Hours25) {
218
- this.publishAvailability(entity.device, false);
219
- }
220
- }
221
-
222
- setTimerPingable(device, factor) {
223
- if (factor === undefined || factor < 1) factor = 1;
224
- if (this.timers[device.ieeeAddr]) {
225
- clearTimeout(this.timers[device.ieeeAddr]);
226
- }
227
- this.timers[device.ieeeAddr] = setTimeout(async() => {
228
- await this.handleIntervalPingable(device);
229
- }, utils.secondsToMilliseconds(this.availability_timeout * factor));
230
- }
231
-
232
- async stop() {
233
- for (const timer of Object.values(this.timers)) {
234
- clearTimeout(timer);
235
- }
236
- const clients = await this.zigbee.getClients();
237
- clients.forEach((device) => this.publishAvailability(device, false));
238
- }
239
-
240
- async onReconnect(device) {
241
- const entity = await this.zigbee.resolveEntity(device);
242
- if (entity && entity.mapped) {
243
- const used = [];
244
- try {
245
- for (const key of toZigbeeCandidates) {
246
- const converter = entity.mapped.toZigbee.find((tz) => tz.key.includes(key));
247
- if (converter && !used.includes(converter)) {
248
- await converter.convertGet(device.endpoints[0], key, {});
249
- used.push(converter);
250
- }
251
- }
252
- } catch (error) {
253
- this.sendError(error);
254
- this.debug(`Failed to read state of '${entity.device.ieeeAddr}' after reconnect`);
255
- }
256
- }
257
- }
258
-
259
- async publishAvailability(device, available, force) {
260
- const entity = await this.zigbee.resolveEntity(device);
261
- if (entity && entity.mapped) {
262
- const ieeeAddr = device.ieeeAddr;
263
- if (this.state.hasOwnProperty(ieeeAddr) && !this.state[ieeeAddr] && available) {
264
- this.onReconnect(device);
265
- }
266
-
267
- if (this.state[ieeeAddr] !== available || force) {
268
- this.state[ieeeAddr] = available;
269
- const payload = {available: available};
270
- this.debug(`Publish available for ${ieeeAddr} = ${available}`);
271
- this.zigbee.emit('publish', ieeeAddr.substr(2), entity.mapped.model, payload);
272
- this.debug(`Publish LQ for ${ieeeAddr} = ${(available ? 10: 0)}`);
273
- this.zigbee.emit('publish', ieeeAddr.substr(2), entity.mapped.model, { linkquality: (available ? 10: 0) });
274
- }
275
- }
276
- }
277
-
278
- onZigbeeEvent(data) {
279
- const device = data.device;
280
- if (!device || this.forcedNonPingable[device.ieeeAddr]) {
281
- return;
282
- }
283
-
284
- this.publishAvailability(device, true);
285
-
286
- if (this.isPingable(device)) {
287
- // When a zigbee message from a device is received we know the device is still alive.
288
- // => reset the timer.
289
- this.setTimerPingable(device, 1);
290
- const pc = this.ping_counters[device.ieeeAddr];
291
- if (pc == undefined) {
292
- this.ping_counters[device.ieeeAddr] = { failed:0, reported:0 };
293
- }
294
- else {
295
- this.ping_counters[device.ieeeAddr].failed++;
296
- }
297
-
298
- const online = this.state.hasOwnProperty(device.ieeeAddr) && this.state[device.ieeeAddr];
299
- if (online && data.type === 'deviceAnnounce' && !utils.isIkeaTradfriDevice(device)) {
300
- /**
301
- * In case the device is powered off AND on within the availability timeout,
302
- * zigbee2qmtt does not detect the device as offline (device is still marked online).
303
- * When a device is turned on again the state could be out of sync.
304
- * https://github.com/Koenkk/zigbee2mqtt/issues/1383#issuecomment-489412168
305
- * endDeviceAnnce is typically send when a device comes online.
306
- *
307
- * This isn't needed for TRADFRI devices as they already send the state themself.
308
- */
309
- this.onReconnect(device);
310
- }
311
- }
312
- }
313
- }
314
-
315
- module.exports = DeviceAvailability;
1
+ 'use strict';
2
+
3
+ const BaseExtension = require('./zbBaseExtension');
4
+ const zigbeeHerdsmanConverters = require('zigbee-herdsman-converters');
5
+ const utils = require('./utils');
6
+
7
+ // Some EndDevices should be pinged
8
+ // e.g. E11-G13 https://github.com/Koenkk/zigbee2mqtt/issues/775#issuecomment-453683846
9
+ const forcedPingable = [
10
+ zigbeeHerdsmanConverters.devices.find((d) => d.model === 'E11-G13'),
11
+ zigbeeHerdsmanConverters.devices.find((d) => d.model === '53170161'),
12
+ zigbeeHerdsmanConverters.devices.find((d) => d.model === 'V3-BTZB'),
13
+ zigbeeHerdsmanConverters.devices.find((d) => d.model === 'SPZB0001'),
14
+ zigbeeHerdsmanConverters.devices.find((d) => d.model === '014G2461')
15
+ ];
16
+
17
+ // asgothian: 29.12.2020: Removed color and color_temp from readable
18
+ // state candidates as most states do not provide a getter to ikea_transform
19
+ // the data from the herdsman back to the value needed, which
20
+ // will result in warnings "illegal state x,y" or "illegal state h,s" for color
21
+ // and possibly sudden changes in value due to the support for color_temp
22
+ // in mired and Kelvin.
23
+ const toZigbeeCandidates = ['local_temperature', 'state', 'brightness']; //, 'color', 'color_temp'];
24
+ const Hours25 = 1000 * 60 * 60 * 25;
25
+ const MinAvailabilityTimeout = 300; // ping every 5 minutes with few devices
26
+ const MaxAvailabilityTimeout = 1800; // ping every 30 minutes with many devices;
27
+ const AverageTimeBetweenPings = 45; // on average, plan for 30 seconds between pings.
28
+
29
+ /**
30
+ * This extensions pings devices to check if they are online.
31
+ */
32
+ class DeviceAvailability extends BaseExtension {
33
+ constructor(zigbee, options) {
34
+ super(zigbee, options);
35
+ this.availability_timeout = 300; // wait 5 min for live check
36
+ this.timers = {};
37
+ this.ping_counters = {};
38
+ this.max_ping = 3;
39
+ this.state = {};
40
+ this.active_ping = true;
41
+ this.forced_ping = true;
42
+ this.forcedNonPingable = {};
43
+ this.number_of_registered_devices = 0;
44
+ // force publish availability for new devices
45
+ this.zigbee.on('new', (entity) => {
46
+ // wait for 1s for creating device states
47
+ setTimeout(() =>
48
+ this.publishAvailability(entity.device, true, true), 1000);
49
+ });
50
+ this.startDevicePingQueue = []; // simple fifo array for starting device pings
51
+ this.startDevicePingTimeout = null; // handle for the timeout which empties the queue
52
+ this.startDevicePingDelay = 200; // 200 ms delay between starting the ping timeout
53
+ this.name = 'DeviceAvailability';
54
+ this.elevate_debug = false;
55
+ }
56
+
57
+ setOptions(options) {
58
+ if (typeof options !== 'object') {
59
+ return false;
60
+ }
61
+ if (options.disableActivePing) {
62
+ this.active_ping = false;
63
+ }
64
+ if (options.disableForcedPing) {
65
+ this.forced_ping = false;
66
+ }
67
+ if (typeof options.pingTimeout === 'number') {
68
+ this.availability_timeout = Math.min(60, options.pingTimeout);
69
+ }
70
+ if (typeof options.pingCount === 'number') {
71
+ this.max_ping = Math.min(2, options.pingCount);
72
+ }
73
+ return true;
74
+ }
75
+
76
+ isPingable(device) {
77
+ if (this.active_ping) {
78
+ if (this.forced_ping && forcedPingable.find(d => d && d.hasOwnProperty('zigbeeModel') && d.zigbeeModel.includes(device.modelID))) {
79
+ return true;
80
+ }
81
+
82
+ return utils.isRouter(device) && !utils.isBatteryPowered(device);
83
+ }
84
+ return false;
85
+ }
86
+
87
+ async getAllPingableDevices() {
88
+ const clients = await this.zigbee.getClients();
89
+ return clients.filter(d => this.isPingable(d));
90
+ }
91
+
92
+ async registerDevicePing(device, entity) {
93
+ this.debug(`register device Ping for ${JSON.stringify(device.ieeeAddr)}`);
94
+ this.forcedNonPingable[device.ieeeAddr] = false;
95
+ // this.warn(`Called registerDevicePing for '${device}' of '${entity}'`);
96
+ if (!this.isPingable(device)) {
97
+ return;
98
+ }
99
+ // ensure we do not already have this device in the queue
100
+ // TODO: Following does not work, may be `if (this.startDevicePingQueue.find(item => item && item.device === device)) { return; }`
101
+ this.startDevicePingQueue.forEach(item => {
102
+ if (item && item.device == device) {
103
+ return;
104
+ }
105
+ });
106
+ this.number_of_registered_devices++;
107
+ this.availability_timeout = Math.max(Math.min(this.number_of_registered_devices * AverageTimeBetweenPings, MaxAvailabilityTimeout), MinAvailabilityTimeout);
108
+ this.startDevicePingQueue.push({device, entity});
109
+ if (this.startDevicePingTimeout == null) {
110
+ this.startDevicePingTimeout = setTimeout(async () =>
111
+ await this.startDevicePing(), this.startDevicePingDelay);
112
+ }
113
+ }
114
+
115
+ async deregisterDevicePing(device) {
116
+ this.info(`deregister device Ping for deactivated device ${JSON.stringify(device.ieeeAddr)}`);
117
+ this.forcedNonPingable[device.ieeeAddr] = true;
118
+ if (this.timers[device.ieeeAddr]) {
119
+ clearTimeout(this.timers[device.ieeeAddr]);
120
+ }
121
+ }
122
+
123
+ async startDevicePing() {
124
+ // this.warn(JSON.stringify(this));
125
+ this.startDevicePingTimeout = null;
126
+ const item = this.startDevicePingQueue.shift();
127
+ if (this.startDevicePingQueue.length > 0) {
128
+ this.startDevicePingTimeout = setTimeout(async () =>
129
+ await this.startDevicePing(), this.startDevicePingDelay);
130
+ }
131
+ if (item && item.hasOwnProperty('device')) {
132
+ this.handleIntervalPingable(item.device, item.entity);
133
+ }
134
+ }
135
+
136
+ async onZigbeeStarted() {
137
+ // As some devices are not checked for availability (e.g. battery powered devices)
138
+ // we mark these device as online by default.
139
+ // NOTE: The start of active pings for pingable devices is done separately,
140
+ // triggered by the 'new device' event to ensure that they are handled
141
+ // identically on reconnect, disconnect and new pair (as)
142
+ const clients = await this.zigbee.getClients();
143
+ // this.warn('onZigbeeStarted called');
144
+ for (const device of clients) {
145
+ if (this.isPingable(device)) {
146
+ // this.setTimerPingable(device);
147
+ } else {
148
+ // this.warn(`Setting '${device.ieeeAddr}' as available - battery driven`);
149
+ this.publishAvailability(device, true);
150
+ this.timers[device.ieeeAddr] = setInterval(() =>
151
+ this.handleIntervalNotPingable(device), utils.secondsToMilliseconds(this.availability_timeout));
152
+ }
153
+ }
154
+ }
155
+
156
+ async handleIntervalPingable(device, entity) {
157
+ const ieeeAddr = device.ieeeAddr;
158
+ const resolvedEntity = entity ? entity : await this.zigbee.resolveEntity(ieeeAddr);
159
+ if (!resolvedEntity) {
160
+ this.debug(`Stop pinging '${ieeeAddr}' ${device.modelID}, device is not known anymore`);
161
+ return;
162
+ }
163
+ if (this.isPingable(device)) {
164
+ let pingCount = this.ping_counters[device.ieeeAddr];
165
+ if (pingCount === undefined) {
166
+ this.ping_counters[device.ieeeAddr] = {failed: 0, reported: 0};
167
+ pingCount = {failed: 0, reported: 0};
168
+ }
169
+
170
+ // first see if we can "ping" the device by reading a Status
171
+ try {
172
+ for (const key of toZigbeeCandidates) {
173
+ const converter = resolvedEntity.mapped.toZigbee.find((tz) => tz.key.includes(key));
174
+ if (converter) {
175
+ await converter.convertGet(device.endpoints[0], key, {});
176
+ this.debug(`Successful read state '${key}' of '${device.ieeeAddr}' in stead of pinging`);
177
+ this.setTimerPingable(device, 1);
178
+ this.ping_counters[device.ieeeAddr].failed = 0;
179
+ return;
180
+ }
181
+ }
182
+ } catch (error) {
183
+ this.sendError(error);
184
+ this.debug(`Exception in readState of '${device.ieeeAddr}' - error : '${error}'`);
185
+ // intentionally empty: Just present to ensure we cause no harm
186
+ // when reading the state fails. => fall back on standard Ping function
187
+ }
188
+ try {
189
+ await device.ping();
190
+ this.publishAvailability(device, true);
191
+ this.debug(`Successfully pinged ${ieeeAddr} ${device.modelID}`);
192
+ this.setTimerPingable(device, 1);
193
+ this.ping_counters[device.ieeeAddr].failed = 0;
194
+ } catch (error) {
195
+ this.publishAvailability(device, false);
196
+ if (pingCount.failed++ <= this.max_ping) {
197
+ if (pingCount.failed < 2 && pingCount.reported < this.max_ping) {
198
+ this.warn(`Failed to ping ${ieeeAddr} ${device.modelID}`);
199
+ pingCount.reported++;
200
+ } else {
201
+ this.debug(`Failed to ping ${ieeeAddr} ${device.modelID} on ${pingCount} consecutive attempts`);
202
+ }
203
+ this.setTimerPingable(device, pingCount.failed);
204
+ this.ping_counters[device.ieeeAddr] = pingCount;
205
+ } else {
206
+ this.warn(`Stopping to ping ${ieeeAddr} ${device.modelID} after ${pingCount.failed} ping attempts`);
207
+ }
208
+ }
209
+ }
210
+ }
211
+
212
+ async handleIntervalNotPingable(device) {
213
+ const entity = await this.zigbee.resolveEntity(device.ieeeAddr);
214
+ if (!entity || !device.lastSeen) {
215
+ return;
216
+ }
217
+
218
+ const ago = Date.now() - entity.device.lastSeen;
219
+ this.debug(`Non-pingable device ${entity.device.ieeeAddr} ${entity.device.modelID} was last seen '${ago / 1000}' seconds ago.`);
220
+
221
+ if (ago > Hours25) {
222
+ this.publishAvailability(entity.device, false);
223
+ }
224
+ }
225
+
226
+ setTimerPingable(device, factor) {
227
+ if (factor === undefined || factor < 1) {
228
+ factor = 1;
229
+ }
230
+ if (this.timers[device.ieeeAddr]) {
231
+ clearTimeout(this.timers[device.ieeeAddr]);
232
+ }
233
+ this.timers[device.ieeeAddr] = setTimeout(async () =>
234
+ await this.handleIntervalPingable(device), utils.secondsToMilliseconds(this.availability_timeout * factor));
235
+ }
236
+
237
+ async stop() {
238
+ for (const timer of Object.values(this.timers)) {
239
+ clearTimeout(timer);
240
+ }
241
+ const clients = await this.zigbee.getClients();
242
+ clients.forEach(device => this.publishAvailability(device, false));
243
+ }
244
+
245
+ async onReconnect(device) {
246
+ const entity = await this.zigbee.resolveEntity(device);
247
+ if (entity && entity.mapped) {
248
+ const used = [];
249
+ try {
250
+ for (const key of toZigbeeCandidates) {
251
+ const converter = entity.mapped.toZigbee.find((tz) => tz.key.includes(key));
252
+ if (converter && !used.includes(converter)) {
253
+ await converter.convertGet(device.endpoints[0], key, {});
254
+ used.push(converter);
255
+ }
256
+ }
257
+ } catch (error) {
258
+ this.sendError(error);
259
+ this.debug(`Failed to read state of '${entity.device.ieeeAddr}' after reconnect`);
260
+ }
261
+ }
262
+ }
263
+
264
+ async publishAvailability(device, available, force) {
265
+ const entity = await this.zigbee.resolveEntity(device);
266
+ if (entity && entity.mapped) {
267
+ const ieeeAddr = device.ieeeAddr;
268
+ if (this.state.hasOwnProperty(ieeeAddr) && !this.state[ieeeAddr] && available) {
269
+ this.onReconnect(device);
270
+ }
271
+
272
+ if (this.state[ieeeAddr] !== available || force) {
273
+ this.state[ieeeAddr] = available;
274
+ const payload = {available: available};
275
+ this.debug(`Publish available for ${ieeeAddr} = ${available}`);
276
+ this.zigbee.emit('publish', ieeeAddr.substr(2), entity.mapped.model, payload);
277
+ this.debug(`Publish LQ for ${ieeeAddr} = ${(available ? 10 : 0)}`);
278
+ this.zigbee.emit('publish', ieeeAddr.substr(2), entity.mapped.model, {linkquality: (available ? 10 : 0)});
279
+ }
280
+ }
281
+ }
282
+
283
+ onZigbeeEvent(data) {
284
+ const device = data.device;
285
+ if (!device || this.forcedNonPingable[device.ieeeAddr]) {
286
+ return;
287
+ }
288
+
289
+ this.publishAvailability(device, true);
290
+
291
+ if (this.isPingable(device)) {
292
+ // When a zigbee message from a device is received we know the device is still alive.
293
+ // => reset the timer.
294
+ this.setTimerPingable(device, 1);
295
+ const pc = this.ping_counters[device.ieeeAddr];
296
+ if (pc == undefined) {
297
+ this.ping_counters[device.ieeeAddr] = {failed: 0, reported: 0};
298
+ } else {
299
+ this.ping_counters[device.ieeeAddr].failed++;
300
+ }
301
+
302
+ const online = this.state.hasOwnProperty(device.ieeeAddr) && this.state[device.ieeeAddr];
303
+ if (online && data.type === 'deviceAnnounce' && !utils.isIkeaTradfriDevice(device)) {
304
+ /**
305
+ * In case the device is powered off AND on within the availability timeout,
306
+ * zigbee2qmtt does not detect the device as offline (device is still marked online).
307
+ * When a device is turned on again the state could be out of sync.
308
+ * https://github.com/Koenkk/zigbee2mqtt/issues/1383#issuecomment-489412168
309
+ * endDeviceAnnce is typically send when a device comes online.
310
+ *
311
+ * This isn't needed for TRADFRI devices as they already send the state themself.
312
+ */
313
+ this.onReconnect(device);
314
+ }
315
+ }
316
+ }
317
+ }
318
+
319
+ module.exports = DeviceAvailability;