iobroker.zigbee 1.7.1 → 1.7.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/.eslintignore +1 -1
  2. package/.eslintrc.json +36 -36
  3. package/.github/FUNDING.yml +3 -3
  4. package/.github/stale.yml +13 -13
  5. package/.github/workflows/test-and-release.yml +151 -151
  6. package/.travis/wiki.sh +27 -27
  7. package/LICENSE +21 -21
  8. package/README.md +379 -373
  9. package/admin/adapter-settings.js +244 -244
  10. package/admin/admin.js +2926 -2926
  11. package/admin/img/MLI-404011-MLI-404049.png +0 -0
  12. package/admin/img/philips_hue_lom001.png +0 -0
  13. package/admin/index.html +159 -159
  14. package/admin/index_m.html +1161 -1161
  15. package/admin/moment.min.js +1 -1
  16. package/admin/shuffle.min.js +2 -2
  17. package/admin/tab_m.html +944 -944
  18. package/admin/vis-network.min.css +1 -1
  19. package/admin/vis-network.min.js +27 -27
  20. package/admin/words.js +112 -112
  21. package/docs/de/readme.md +27 -27
  22. package/docs/en/readme.md +30 -30
  23. package/docs/flashing_via_arduino_(en).md +110 -110
  24. package/docs/ru/readme.md +28 -28
  25. package/docs/tutorial/groups-1.png +0 -0
  26. package/docs/tutorial/groups-2.png +0 -0
  27. package/docs/tutorial/tab-dev-1.png +0 -0
  28. package/io-package.json +354 -330
  29. package/lib/backup.js +171 -171
  30. package/lib/binding.js +325 -325
  31. package/lib/colors.js +460 -460
  32. package/lib/commands.js +501 -501
  33. package/lib/developer.js +148 -148
  34. package/lib/devices.js +3145 -3145
  35. package/lib/exclude.js +168 -168
  36. package/lib/exposes.js +804 -804
  37. package/lib/groups.js +342 -342
  38. package/lib/json.js +60 -60
  39. package/lib/networkmap.js +56 -56
  40. package/lib/ota.js +179 -179
  41. package/lib/rgb.js +255 -255
  42. package/lib/seriallist.js +37 -37
  43. package/lib/states.js +6416 -6416
  44. package/lib/statescontroller.js +666 -658
  45. package/lib/tools.js +54 -54
  46. package/lib/utils.js +151 -151
  47. package/lib/zbBaseExtension.js +36 -36
  48. package/lib/zbDelayedAction.js +152 -152
  49. package/lib/zbDeviceAvailability.js +315 -315
  50. package/lib/zbDeviceConfigure.js +152 -152
  51. package/lib/zbDeviceEvent.js +49 -49
  52. package/lib/zigbeecontroller.js +946 -946
  53. package/package.json +2 -2
  54. package/support/docgen.js +93 -93
  55. package/admin/img/zbt_remote.png +0 -0
@@ -1,315 +1,315 @@
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);
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;