iobroker.zigbee 1.6.8 → 1.6.16

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 (64) 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 +424 -385
  9. package/admin/adapter-settings.js +244 -244
  10. package/admin/admin.js +2926 -2704
  11. package/admin/img/14153905L.png +0 -0
  12. package/admin/img/81855.png +0 -0
  13. package/admin/img/HG06338.png +0 -0
  14. package/admin/img/TI0001-cover.png +0 -0
  15. package/admin/img/philips_hue_lom001.png +0 -0
  16. package/admin/index.html +159 -159
  17. package/admin/index_m.html +1158 -1055
  18. package/admin/moment.min.js +1 -1
  19. package/admin/shuffle.min.js +2 -2
  20. package/admin/tab_m.html +944 -1025
  21. package/admin/vis-network.min.js +26 -26
  22. package/admin/words.js +108 -107
  23. package/docs/de/readme.md +27 -27
  24. package/docs/en/readme.md +30 -30
  25. package/docs/flashing_via_arduino_(en).md +110 -110
  26. package/docs/ru/readme.md +28 -28
  27. package/docs/tutorial/groups-1.png +0 -0
  28. package/docs/tutorial/groups-2.png +0 -0
  29. package/docs/tutorial/tab-dev-1.png +0 -0
  30. package/docs/tutorial/zigbee.png +0 -0
  31. package/io-package.json +355 -317
  32. package/lib/backup.js +132 -132
  33. package/lib/binding.js +325 -325
  34. package/lib/colors.js +460 -460
  35. package/lib/commands.js +501 -435
  36. package/lib/developer.js +148 -148
  37. package/lib/devices.js +3144 -3119
  38. package/lib/exclude.js +168 -168
  39. package/lib/exposes.js +13 -9
  40. package/lib/groups.js +342 -316
  41. package/lib/json.js +60 -60
  42. package/lib/networkmap.js +56 -56
  43. package/lib/ota.js +179 -153
  44. package/lib/rgb.js +255 -225
  45. package/lib/seriallist.js +37 -37
  46. package/lib/states.js +6407 -6381
  47. package/lib/statescontroller.js +627 -502
  48. package/lib/tools.js +54 -54
  49. package/lib/utils.js +151 -151
  50. package/lib/zbBaseExtension.js +32 -31
  51. package/lib/zbDelayedAction.js +152 -151
  52. package/lib/zbDeviceAvailability.js +318 -306
  53. package/lib/zbDeviceConfigure.js +152 -148
  54. package/lib/zbDeviceEvent.js +49 -43
  55. package/lib/zigbeecontroller.js +946 -856
  56. package/main.js +8 -4
  57. package/package.json +77 -74
  58. package/support/docgen.js +93 -93
  59. package/.devcontainer/devcontainer.json +0 -36
  60. package/.devcontainer/docker-compose.yml +0 -51
  61. package/.devcontainer/iobroker/Dockerfile +0 -2
  62. package/.devcontainer/nginx/nginx.conf +0 -33
  63. package/.devcontainer/parcel/Dockerfile +0 -9
  64. package/.devcontainer/parcel/run.sh +0 -7
@@ -1,306 +1,318 @@
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.number_of_registered_devices = 0;
43
- // force publish availability for new devices
44
- this.zigbee.on('new', (entity) => {
45
- // wait for 1s for creating device states
46
- setTimeout(() => {
47
- this.publishAvailability(entity.device, true, true);
48
- }, 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
- }
54
-
55
- setOptions(options) {
56
- if (typeof(options) != 'object') return false;
57
- if (options.disableActivePing) this.active_ping = false;
58
- if (options.disableForcedPing) this.forced_ping = false;
59
- if (typeof(options.pingTimeout)=='number') this.availability_timeout = Math.min(60,options.pingTimeout);
60
- if (typeof(options.pingCount)=='number') this.max_ping = Math.min(2, options.pingCount);
61
- return true;
62
- }
63
-
64
- isPingable(device) {
65
- if (this.active_ping)
66
- {
67
- if (this.forced_ping && forcedPingable.find((d) => d && d.hasOwnProperty('zigbeeModel') && d.zigbeeModel.includes(device.modelID))) {
68
- return true;
69
- }
70
-
71
- const result = utils.isRouter(device) && !utils.isBatteryPowered(device);
72
- return result;
73
- }
74
- return false;
75
- }
76
-
77
- async getAllPingableDevices() {
78
- const clients = await this.zigbee.getClients();
79
- return clients.filter((d) => this.isPingable(d));
80
- }
81
-
82
- async registerDevicePing(device, entity) {
83
- // this.warn(`Called registerDevicePing for '${device}' of '${entity}'`);
84
- if (!this.isPingable(device)) return;
85
- // ensure we do not already have this device in the queue
86
- this.startDevicePingQueue.forEach(item => {
87
- if (item && item.device == device)
88
- return;
89
- });
90
- this.number_of_registered_devices++;
91
- this.availability_timeout = Math.max(Math.min(this.number_of_registered_devices * AverageTimeBetweenPings,MaxAvailabilityTimeout ),MinAvailabilityTimeout);
92
- this.startDevicePingQueue.push({device:device, entity:entity});
93
- if (this.startDevicePingTimeout == null)
94
- this.startDevicePingTimeout = setTimeout(async() => {
95
- await this.startDevicePing();
96
- }, this.startDevicePingDelay);
97
- }
98
-
99
- async startDevicePing() {
100
- // this.warn(JSON.stringify(this));
101
- this.startDevicePingTimeout = null;
102
- const item = this.startDevicePingQueue.shift();
103
- if (this.startDevicePingQueue.length >0) {
104
- this.startDevicePingTimeout = setTimeout(async() => {
105
- await this.startDevicePing();
106
- }, this.startDevicePingDelay);
107
- }
108
- if (item && item.hasOwnProperty('device')) {
109
- this.handleIntervalPingable(item.device, item.entity);
110
- }
111
- }
112
- async onZigbeeStarted() {
113
- // As some devices are not checked for availability (e.g. battery powered devices)
114
- // we mark these device as online by default.
115
- // NOTE: The start of active pings for pingable devices is done separately,
116
- // triggered by the 'new device' event to ensure that they are handled
117
- // identically on reconnect, disconnect and new pair (as)
118
- const clients = await this.zigbee.getClients();
119
- // this.warn('onZigbeeStarted called');
120
- for (const device of clients) {
121
-
122
- if (this.isPingable(device)) {
123
- // this.setTimerPingable(device);
124
- } else {
125
- // this.warn(`Setting '${device.ieeeAddr}' as available - battery driven`);
126
- this.publishAvailability(device, true);
127
- this.timers[device.ieeeAddr] = setInterval(() => {
128
- this.handleIntervalNotPingable(device);
129
- },utils.secondsToMilliseconds(this.availability_timeout));
130
- }
131
- }
132
- }
133
-
134
- async handleIntervalPingable(device, entity) {
135
- const ieeeAddr = device.ieeeAddr;
136
- const resolvedEntity = (entity ? entity: await this.zigbee.resolveEntity(ieeeAddr));
137
- if (!resolvedEntity) {
138
- this.debug(`Stop pinging '${ieeeAddr}' ${device.modelID}, device is not known anymore`);
139
- return;
140
- }
141
- if (this.isPingable(device)) {
142
- let pingCount = this.ping_counters[device.ieeeAddr];
143
- if (pingCount === undefined) {
144
- this.ping_counters[device.ieeeAddr] = { failed: 0, reported: 0};
145
- pingCount = { failed: 0, reported: 0};
146
- }
147
-
148
- // first see if we can "ping" the device by reading a Status
149
- try {
150
- for (const key of toZigbeeCandidates) {
151
- const converter = resolvedEntity.mapped.toZigbee.find((tz) => tz.key.includes(key));
152
- if (converter) {
153
- await converter.convertGet(device.endpoints[0], key, {});
154
- this.debug(`Successful read state '${key}' of '${device.ieeeAddr}' in stead of pinging`);
155
- this.setTimerPingable(device, 1);
156
- this.ping_counters[device.ieeeAddr].failed = 0;
157
- return;
158
- }
159
- }
160
- }
161
- catch (error) {
162
- this.sendError(error);
163
- this.debug(`Exception in readState of '${device.ieeeAddr}' - error : '${error}'`);
164
- // intentionally empty: Just present to ensure we cause no harm
165
- // when reading the state fails. => fall back on standard Ping function
166
- }
167
- try {
168
- await device.ping();
169
- this.publishAvailability(device, true);
170
- this.debug(`Successfully pinged ${ieeeAddr} ${device.modelID}`);
171
- this.setTimerPingable(device, 1);
172
- this.ping_counters[device.ieeeAddr].failed = 0;
173
- } catch (error) {
174
- this.publishAvailability(device, false);
175
- if (pingCount.failed++ <= this.max_ping)
176
- {
177
- if (pingCount.failed < 2 && pingCount.reported < this.max_ping) {
178
- this.warn(`Failed to ping ${ieeeAddr} ${device.modelID}`);
179
- pingCount.reported++;
180
- }
181
- else {
182
- this.debug(`Failed to ping ${ieeeAddr} ${device.modelID} on ${pingCount} consecutive attempts`);
183
- }
184
- this.setTimerPingable(device, pingCount.failed);
185
- this.ping_counters[device.ieeeAddr]= pingCount;
186
- }
187
- else {
188
- this.warn(`Stopping to ping ${ieeeAddr} ${device.modelID} after ${pingCount.failed} ping attempts`);
189
- }
190
- }
191
- }
192
- }
193
-
194
-
195
- async handleIntervalNotPingable(device) {
196
- const entity = await this.zigbee.resolveEntity(device.ieeeAddr);
197
- if (!entity || !device.lastSeen) {
198
- return;
199
- }
200
-
201
- const ago = Date.now() - entity.device.lastSeen;
202
- this.debug(`Non-pingable device ${entity.device.ieeeAddr} ${entity.device.modelID} was last seen '${ago / 1000}' seconds ago.`);
203
-
204
- if (ago > Hours25) {
205
- this.publishAvailability(entity.device, false);
206
- }
207
- }
208
-
209
- setTimerPingable(device, factor) {
210
- if (factor === undefined || factor < 1) factor = 1;
211
- if (this.timers[device.ieeeAddr]) {
212
- clearTimeout(this.timers[device.ieeeAddr]);
213
- }
214
- this.timers[device.ieeeAddr] = setTimeout(async() => {
215
- await this.handleIntervalPingable(device);
216
- }, utils.secondsToMilliseconds(this.availability_timeout * factor));
217
- }
218
-
219
- async stop() {
220
- for (const timer of Object.values(this.timers)) {
221
- clearTimeout(timer);
222
- }
223
- const clients = await this.zigbee.getClients();
224
- clients.forEach((device) => this.publishAvailability(device, false));
225
- }
226
-
227
- async onReconnect(device) {
228
- const entity = await this.zigbee.resolveEntity(device);
229
- if (entity && entity.mapped) {
230
- const used = [];
231
- try {
232
- for (const key of toZigbeeCandidates) {
233
- const converter = entity.mapped.toZigbee.find((tz) => tz.key.includes(key));
234
- if (converter && !used.includes(converter)) {
235
- await converter.convertGet(device.endpoints[0], key, {});
236
- used.push(converter);
237
- }
238
- }
239
- } catch (error) {
240
- this.sendError(error);
241
- this.debug(`Failed to read state of '${entity.device.ieeeAddr}' after reconnect`);
242
- }
243
- }
244
- }
245
-
246
- async publishAvailability(device, available, force) {
247
- const entity = await this.zigbee.resolveEntity(device);
248
- if (entity && entity.mapped) {
249
- const ieeeAddr = device.ieeeAddr;
250
- if (this.state.hasOwnProperty(ieeeAddr) && !this.state[ieeeAddr] && available) {
251
- this.onReconnect(device);
252
- }
253
-
254
- if (this.state[ieeeAddr] !== available || force) {
255
- this.state[ieeeAddr] = available;
256
- const payload = {available: available};
257
- this.debug(`Publish available for ${ieeeAddr} = ${available}`);
258
- this.zigbee.emit('publish', ieeeAddr.substr(2), entity.mapped.model, payload);
259
- this.debug(`Publish LQ for ${ieeeAddr} = ${(available ? 10: 0)}`);
260
- this.zigbee.emit('publish', ieeeAddr.substr(2), entity.mapped.model, { linkquality: (available ? 10: 0) });
261
- }
262
- // if (!available) {
263
- // this.debug(`Publish LQ for ${ieeeAddr} = 0`);
264
- // this.zigbee.emit('publish', ieeeAddr.substr(2), entity.mapped.model, { linkquality: 0 });
265
- // }
266
- }
267
- }
268
-
269
- onZigbeeEvent(data) {
270
- const device = data.device;
271
- if (!device) {
272
- return;
273
- }
274
-
275
- this.publishAvailability(device, true);
276
-
277
- if (this.isPingable(device)) {
278
- // When a zigbee message from a device is received we know the device is still alive.
279
- // => reset the timer.
280
- this.setTimerPingable(device, 1);
281
- const pc = this.ping_counters[device.ieeeAddr];
282
- if (pc == undefined) {
283
- this.ping_counters[device.ieeeAddr] = { failed:0, reported:0 };
284
- }
285
- else {
286
- this.ping_counters[device.ieeeAddr].failed++;
287
- }
288
-
289
- const online = this.state.hasOwnProperty(device.ieeeAddr) && this.state[device.ieeeAddr];
290
- if (online && data.type === 'deviceAnnounce' && !utils.isIkeaTradfriDevice(device)) {
291
- /**
292
- * In case the device is powered off AND on within the availability timeout,
293
- * zigbee2qmtt does not detect the device as offline (device is still marked online).
294
- * When a device is turned on again the state could be out of sync.
295
- * https://github.com/Koenkk/zigbee2mqtt/issues/1383#issuecomment-489412168
296
- * endDeviceAnnce is typically send when a device comes online.
297
- *
298
- * This isn't needed for TRADFRI devices as they already send the state themself.
299
- */
300
- this.onReconnect(device);
301
- }
302
- }
303
- }
304
- }
305
-
306
- 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
+ }
56
+
57
+ setOptions(options) {
58
+ if (typeof(options) != 'object') return false;
59
+ if (options.disableActivePing) this.active_ping = false;
60
+ if (options.disableForcedPing) this.forced_ping = false;
61
+ if (typeof(options.pingTimeout)=='number') this.availability_timeout = Math.min(60,options.pingTimeout);
62
+ if (typeof(options.pingCount)=='number') this.max_ping = Math.min(2, options.pingCount);
63
+ return true;
64
+ }
65
+
66
+ isPingable(device) {
67
+ if (this.active_ping)
68
+ {
69
+ if (this.forced_ping && forcedPingable.find((d) => d && d.hasOwnProperty('zigbeeModel') && d.zigbeeModel.includes(device.modelID))) {
70
+ return true;
71
+ }
72
+
73
+ const result = utils.isRouter(device) && !utils.isBatteryPowered(device);
74
+ return result;
75
+ }
76
+ return false;
77
+ }
78
+
79
+ async getAllPingableDevices() {
80
+ const clients = await this.zigbee.getClients();
81
+ return clients.filter((d) => this.isPingable(d));
82
+ }
83
+
84
+ async registerDevicePing(device, entity) {
85
+ this.debug('register device Ping for ' + JSON.stringify(device.ieeeAddr));
86
+ this.forcedNonPingable[device.ieeeAddr] = false;
87
+ // this.warn(`Called registerDevicePing for '${device}' of '${entity}'`);
88
+ if (!this.isPingable(device)) return;
89
+ // ensure we do not already have this device in the queue
90
+ this.startDevicePingQueue.forEach(item => {
91
+ if (item && item.device == device)
92
+ return;
93
+ });
94
+ this.number_of_registered_devices++;
95
+ this.availability_timeout = Math.max(Math.min(this.number_of_registered_devices * AverageTimeBetweenPings,MaxAvailabilityTimeout ),MinAvailabilityTimeout);
96
+ this.startDevicePingQueue.push({device:device, entity:entity});
97
+ if (this.startDevicePingTimeout == null)
98
+ this.startDevicePingTimeout = setTimeout(async() => {
99
+ await this.startDevicePing();
100
+ }, this.startDevicePingDelay);
101
+ }
102
+
103
+ async deregisterDevicePing(device) {
104
+ this.info('deregister device Ping for deactivated device ' + JSON.stringify(device.ieeeAddr));
105
+ this.forcedNonPingable[device.ieeeAddr] = true;
106
+ if (this.timers[device.ieeeAddr]) {
107
+ clearTimeout(this.timers[device.ieeeAddr]);
108
+ }
109
+ }
110
+
111
+ async startDevicePing() {
112
+ // this.warn(JSON.stringify(this));
113
+ this.startDevicePingTimeout = null;
114
+ const item = this.startDevicePingQueue.shift();
115
+ if (this.startDevicePingQueue.length >0) {
116
+ this.startDevicePingTimeout = setTimeout(async() => {
117
+ await this.startDevicePing();
118
+ }, this.startDevicePingDelay);
119
+ }
120
+ if (item && item.hasOwnProperty('device')) {
121
+ this.handleIntervalPingable(item.device, item.entity);
122
+ }
123
+ }
124
+ async onZigbeeStarted() {
125
+ // As some devices are not checked for availability (e.g. battery powered devices)
126
+ // we mark these device as online by default.
127
+ // NOTE: The start of active pings for pingable devices is done separately,
128
+ // triggered by the 'new device' event to ensure that they are handled
129
+ // identically on reconnect, disconnect and new pair (as)
130
+ const clients = await this.zigbee.getClients();
131
+ // this.warn('onZigbeeStarted called');
132
+ for (const device of clients) {
133
+
134
+ if (this.isPingable(device)) {
135
+ // this.setTimerPingable(device);
136
+ } else {
137
+ // this.warn(`Setting '${device.ieeeAddr}' as available - battery driven`);
138
+ this.publishAvailability(device, true);
139
+ this.timers[device.ieeeAddr] = setInterval(() => {
140
+ this.handleIntervalNotPingable(device);
141
+ },utils.secondsToMilliseconds(this.availability_timeout));
142
+ }
143
+ }
144
+ }
145
+
146
+ async handleIntervalPingable(device, entity) {
147
+ const ieeeAddr = device.ieeeAddr;
148
+ const resolvedEntity = (entity ? entity: await this.zigbee.resolveEntity(ieeeAddr));
149
+ if (!resolvedEntity) {
150
+ this.debug(`Stop pinging '${ieeeAddr}' ${device.modelID}, device is not known anymore`);
151
+ return;
152
+ }
153
+ if (this.isPingable(device)) {
154
+ let pingCount = this.ping_counters[device.ieeeAddr];
155
+ if (pingCount === undefined) {
156
+ this.ping_counters[device.ieeeAddr] = { failed: 0, reported: 0};
157
+ pingCount = { failed: 0, reported: 0};
158
+ }
159
+
160
+ // first see if we can "ping" the device by reading a Status
161
+ try {
162
+ for (const key of toZigbeeCandidates) {
163
+ const converter = resolvedEntity.mapped.toZigbee.find((tz) => tz.key.includes(key));
164
+ if (converter) {
165
+ await converter.convertGet(device.endpoints[0], key, {});
166
+ this.debug(`Successful read state '${key}' of '${device.ieeeAddr}' in stead of pinging`);
167
+ this.setTimerPingable(device, 1);
168
+ this.ping_counters[device.ieeeAddr].failed = 0;
169
+ return;
170
+ }
171
+ }
172
+ }
173
+ catch (error) {
174
+ this.sendError(error);
175
+ this.debug(`Exception in readState of '${device.ieeeAddr}' - error : '${error}'`);
176
+ // intentionally empty: Just present to ensure we cause no harm
177
+ // when reading the state fails. => fall back on standard Ping function
178
+ }
179
+ try {
180
+ await device.ping();
181
+ this.publishAvailability(device, true);
182
+ this.debug(`Successfully pinged ${ieeeAddr} ${device.modelID}`);
183
+ this.setTimerPingable(device, 1);
184
+ this.ping_counters[device.ieeeAddr].failed = 0;
185
+ } catch (error) {
186
+ this.publishAvailability(device, false);
187
+ if (pingCount.failed++ <= this.max_ping)
188
+ {
189
+ if (pingCount.failed < 2 && pingCount.reported < this.max_ping) {
190
+ this.warn(`Failed to ping ${ieeeAddr} ${device.modelID}`);
191
+ pingCount.reported++;
192
+ }
193
+ else {
194
+ this.debug(`Failed to ping ${ieeeAddr} ${device.modelID} on ${pingCount} consecutive attempts`);
195
+ }
196
+ this.setTimerPingable(device, pingCount.failed);
197
+ this.ping_counters[device.ieeeAddr]= pingCount;
198
+ }
199
+ else {
200
+ this.warn(`Stopping to ping ${ieeeAddr} ${device.modelID} after ${pingCount.failed} ping attempts`);
201
+ }
202
+ }
203
+ }
204
+ }
205
+
206
+
207
+ async handleIntervalNotPingable(device) {
208
+ const entity = await this.zigbee.resolveEntity(device.ieeeAddr);
209
+ if (!entity || !device.lastSeen) {
210
+ return;
211
+ }
212
+
213
+ const ago = Date.now() - entity.device.lastSeen;
214
+ this.debug(`Non-pingable device ${entity.device.ieeeAddr} ${entity.device.modelID} was last seen '${ago / 1000}' seconds ago.`);
215
+
216
+ if (ago > Hours25) {
217
+ this.publishAvailability(entity.device, false);
218
+ }
219
+ }
220
+
221
+ setTimerPingable(device, factor) {
222
+ if (factor === undefined || factor < 1) factor = 1;
223
+ if (this.timers[device.ieeeAddr]) {
224
+ clearTimeout(this.timers[device.ieeeAddr]);
225
+ }
226
+ this.timers[device.ieeeAddr] = setTimeout(async() => {
227
+ await this.handleIntervalPingable(device);
228
+ }, utils.secondsToMilliseconds(this.availability_timeout * factor));
229
+ }
230
+
231
+ async stop() {
232
+ for (const timer of Object.values(this.timers)) {
233
+ clearTimeout(timer);
234
+ }
235
+ const clients = await this.zigbee.getClients();
236
+ clients.forEach((device) => this.publishAvailability(device, false));
237
+ }
238
+
239
+ async onReconnect(device) {
240
+ const entity = await this.zigbee.resolveEntity(device);
241
+ if (entity && entity.mapped) {
242
+ const used = [];
243
+ try {
244
+ for (const key of toZigbeeCandidates) {
245
+ const converter = entity.mapped.toZigbee.find((tz) => tz.key.includes(key));
246
+ if (converter && !used.includes(converter)) {
247
+ await converter.convertGet(device.endpoints[0], key, {});
248
+ used.push(converter);
249
+ }
250
+ }
251
+ } catch (error) {
252
+ this.sendError(error);
253
+ this.debug(`Failed to read state of '${entity.device.ieeeAddr}' after reconnect`);
254
+ }
255
+ }
256
+ }
257
+
258
+ async publishAvailability(device, available, force) {
259
+ const entity = await this.zigbee.resolveEntity(device);
260
+ if (entity && entity.mapped) {
261
+ const ieeeAddr = device.ieeeAddr;
262
+ if (this.state.hasOwnProperty(ieeeAddr) && !this.state[ieeeAddr] && available) {
263
+ this.onReconnect(device);
264
+ }
265
+
266
+ if (this.state[ieeeAddr] !== available || force) {
267
+ this.state[ieeeAddr] = available;
268
+ const payload = {available: available};
269
+ this.debug(`Publish available for ${ieeeAddr} = ${available}`);
270
+ this.zigbee.emit('publish', ieeeAddr.substr(2), entity.mapped.model, payload);
271
+ this.debug(`Publish LQ for ${ieeeAddr} = ${(available ? 10: 0)}`);
272
+ this.zigbee.emit('publish', ieeeAddr.substr(2), entity.mapped.model, { linkquality: (available ? 10: 0) });
273
+ }
274
+ // if (!available) {
275
+ // this.debug(`Publish LQ for ${ieeeAddr} = 0`);
276
+ // this.zigbee.emit('publish', ieeeAddr.substr(2), entity.mapped.model, { linkquality: 0 });
277
+ // }
278
+ }
279
+ }
280
+
281
+ onZigbeeEvent(data) {
282
+ const device = data.device;
283
+ if (!device || this.forcedNonPingable[device.ieeeAddr]) {
284
+ return;
285
+ }
286
+
287
+ this.publishAvailability(device, true);
288
+
289
+ if (this.isPingable(device)) {
290
+ // When a zigbee message from a device is received we know the device is still alive.
291
+ // => reset the timer.
292
+ this.setTimerPingable(device, 1);
293
+ const pc = this.ping_counters[device.ieeeAddr];
294
+ if (pc == undefined) {
295
+ this.ping_counters[device.ieeeAddr] = { failed:0, reported:0 };
296
+ }
297
+ else {
298
+ this.ping_counters[device.ieeeAddr].failed++;
299
+ }
300
+
301
+ const online = this.state.hasOwnProperty(device.ieeeAddr) && this.state[device.ieeeAddr];
302
+ if (online && data.type === 'deviceAnnounce' && !utils.isIkeaTradfriDevice(device)) {
303
+ /**
304
+ * In case the device is powered off AND on within the availability timeout,
305
+ * zigbee2qmtt does not detect the device as offline (device is still marked online).
306
+ * When a device is turned on again the state could be out of sync.
307
+ * https://github.com/Koenkk/zigbee2mqtt/issues/1383#issuecomment-489412168
308
+ * endDeviceAnnce is typically send when a device comes online.
309
+ *
310
+ * This isn't needed for TRADFRI devices as they already send the state themself.
311
+ */
312
+ this.onReconnect(device);
313
+ }
314
+ }
315
+ }
316
+ }
317
+
318
+ module.exports = DeviceAvailability;