iobroker.zigbee 1.7.5 → 1.7.6

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 (85) 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 +382 -376
  9. package/admin/adapter-settings.js +244 -244
  10. package/admin/admin.js +2927 -2926
  11. package/admin/img/philips_hue_lom001.png +0 -0
  12. package/admin/index.html +159 -159
  13. package/admin/index_m.html +1161 -1161
  14. package/admin/moment.min.js +1 -1
  15. package/admin/shuffle.min.js +2 -2
  16. package/admin/tab_m.html +944 -944
  17. package/admin/vis-network.min.css +1 -1
  18. package/admin/vis-network.min.js +27 -27
  19. package/admin/words.js +111 -112
  20. package/io-package.json +370 -366
  21. package/lib/backup.js +171 -171
  22. package/lib/binding.js +325 -325
  23. package/lib/colors.js +460 -460
  24. package/lib/commands.js +501 -501
  25. package/lib/developer.js +148 -148
  26. package/lib/devices.js +3145 -3145
  27. package/lib/exclude.js +168 -168
  28. package/lib/exposes.js +804 -804
  29. package/lib/groups.js +342 -342
  30. package/lib/json.js +60 -60
  31. package/lib/networkmap.js +56 -56
  32. package/lib/ota.js +179 -179
  33. package/lib/rgb.js +255 -255
  34. package/lib/seriallist.js +37 -37
  35. package/lib/states.js +6416 -6416
  36. package/lib/statescontroller.js +670 -670
  37. package/lib/tools.js +54 -54
  38. package/lib/utils.js +151 -151
  39. package/lib/zbBaseExtension.js +36 -36
  40. package/lib/zbDelayedAction.js +152 -152
  41. package/lib/zbDeviceAvailability.js +315 -315
  42. package/lib/zbDeviceConfigure.js +159 -152
  43. package/lib/zbDeviceEvent.js +49 -49
  44. package/lib/zigbeecontroller.js +951 -946
  45. package/package.json +3 -3
  46. package/support/docgen.js +93 -93
  47. package/docs/de/img/CC2531.png +0 -0
  48. package/docs/de/img/CC2538_CC2592_PA.PNG +0 -0
  49. package/docs/de/img/CC2591.png +0 -0
  50. package/docs/de/img/boards.jpg +0 -0
  51. package/docs/de/img/cc26x2r.PNG +0 -0
  52. package/docs/de/img/results.jpg +0 -0
  53. package/docs/de/img/sku_429478_2.png +0 -0
  54. package/docs/de/img/sku_429601_2.png +0 -0
  55. package/docs/de/readme.md +0 -27
  56. package/docs/en/img/CC2531.png +0 -0
  57. package/docs/en/img/CC2591.png +0 -0
  58. package/docs/en/img/deconz.png +0 -0
  59. package/docs/en/img/sku_429478_2.png +0 -0
  60. package/docs/en/img/sku_429601_2.png +0 -0
  61. package/docs/en/readme.md +0 -30
  62. package/docs/flashing_via_arduino_(en).md +0 -110
  63. package/docs/ru/img/CC2531.png +0 -0
  64. package/docs/ru/img/CC2591.png +0 -0
  65. package/docs/ru/img/sku_429478_2.png +0 -0
  66. package/docs/ru/img/sku_429601_2.png +0 -0
  67. package/docs/ru/readme.md +0 -28
  68. package/docs/tutorial/CC2530_20190425.zip +0 -0
  69. package/docs/tutorial/CC2530_CC2591_20190515.zip +0 -0
  70. package/docs/tutorial/CC2530_CC2592_20190515.zip +0 -0
  71. package/docs/tutorial/CC2531_20190425.zip +0 -0
  72. package/docs/tutorial/adm5_1.PNG +0 -0
  73. package/docs/tutorial/adm5_2.PNG +0 -0
  74. package/docs/tutorial/cat.PNG +0 -0
  75. package/docs/tutorial/groups-1.png +0 -0
  76. package/docs/tutorial/groups-2.png +0 -0
  77. package/docs/tutorial/inst.PNG +0 -0
  78. package/docs/tutorial/reflash-finish.PNG +0 -0
  79. package/docs/tutorial/reflash-step0.png +0 -0
  80. package/docs/tutorial/reflash-step1.PNG +0 -0
  81. package/docs/tutorial/reflash-step2.PNG +0 -0
  82. package/docs/tutorial/settings.png +0 -0
  83. package/docs/tutorial/tab-dev-1.png +0 -0
  84. package/docs/tutorial/zigbee.png +0 -0
  85. package/docs/tutorial/zigbee15.png +0 -0
@@ -1,670 +1,670 @@
1
- 'use strict';
2
-
3
- const EventEmitter = require('events').EventEmitter;
4
- const statesMapping = require('./devices');
5
- const getAdId = require('./utils').getAdId;
6
- const getZbId = require('./utils').getZbId;
7
- const fs = require('fs');
8
- const request = require('request');
9
-
10
- var savedDeviceNames = {};
11
- var knownUndefinedDevices = {};
12
-
13
-
14
- class StatesController extends EventEmitter {
15
- constructor(adapter) {
16
- super();
17
- this.adapter = adapter;
18
- this.adapter.on('stateChange', this.onStateChange.bind(this));
19
- this.query_device_block = [];
20
- this.debugDevices = undefined;
21
- let fn = adapter.expandFileName('dev_names.json');
22
- this.dev_names_fn = fn.replace('.', '_');
23
- this.retTimeoutHandle = null;
24
- fs.readFile(this.dev_names_fn, (err, data) => {
25
- if (!err) {
26
- try
27
- {
28
- savedDeviceNames = JSON.parse(data);
29
- }
30
- catch
31
- {
32
- savedDeviceNames = {};
33
- };
34
- }
35
- });
36
- }
37
-
38
- info(message, data) {
39
- this.emit('log', 'info', message, data);
40
- }
41
-
42
- error(message, data) {
43
- this.emit('log', 'error', message, data);
44
- }
45
-
46
- debug(message, data) {
47
- this.emit('log', 'debug', message, data);
48
- }
49
-
50
- warn(message, data) {
51
- this.emit('log', 'warn', message, data);
52
- }
53
-
54
- sendError(error, message) {
55
- this.adapter.sendError(error, message);
56
- }
57
-
58
- retainDeviceNames()
59
- {
60
- clearTimeout(this.retTimeoutHandle);
61
- this.retTimeoutHanlde = setTimeout(()=> {
62
- fs.writeFile(this.dev_names_fn, JSON.stringify(savedDeviceNames, null, 2), (err) => {
63
- if (err)
64
- this.error('error saving device names: ' + JSON.Stringify(err));
65
- else
66
- this.debug('saved device names');
67
- });},5000);
68
- }
69
-
70
- getDebugDevices() {
71
- this.debugDevices = [];
72
- this.adapter.getState(this.adapter.namespace + '.info.debugmessages', (err, state) => {
73
- if (state) {
74
- if (typeof(state.val) == 'string' && state.val.length > 2) this.debugDevices = state.val.split(';');
75
- this.info('debug devices set to ' + JSON.stringify(this.debugDevices));
76
- } else {
77
- this.adapter.setObject('info.debugmessages', {
78
- 'type': 'state',
79
- 'common': {
80
- 'name': 'Log changes as warnings for',
81
- 'role': '',
82
- 'type': 'string',
83
- 'read': true,
84
- 'write': true,
85
- },
86
- 'native': {},
87
- });
88
- }
89
- });
90
- this.adapter.setObject('info.undefinedDevices', {
91
- 'type': 'state',
92
- 'common': {
93
- 'name': 'Recorded undefined devices',
94
- 'role': '',
95
- 'type': 'string',
96
- 'read': true,
97
- 'write': false,
98
- },
99
- 'native': {},
100
- });
101
- this.adapter.setStateAsync(`info.undefinedDevices`, JSON.stringify(knownUndefinedDevices), true);
102
- }
103
-
104
- onStateChange(id, state){
105
- if (!this.adapter.zbController || !this.adapter.zbController.connected()) return;
106
- if (this.debugDevices === undefined) this.getDebugDevices();
107
- if (state && !state.ack) {
108
- if (id.endsWith('pairingCountdown') || id.endsWith('pairingMessage') || id.endsWith('connection')) return;
109
- if (id.endsWith('debugmessages')) {
110
- if (typeof(state.val) == 'string' && state.val.length > 2)
111
- this.debugDevices = state.val.split(';');
112
- else {
113
- this.debugDevices = [];
114
- }
115
- return;
116
- }
117
- for (const addressPart of this.debugDevices) {
118
- if (typeof(id) == 'string' && id.indexOf(addressPart) > -1)
119
- {
120
- this.warn(`ELEVATED: User stateChange ${id} ${JSON.stringify(state)}`);
121
- break;
122
- }
123
- }
124
- this.debug(`User stateChange ${id} ${JSON.stringify(state)}`);
125
- const devId = getAdId(this.adapter, id); // iobroker device id
126
- let deviceId = getZbId(id); // zigbee device id
127
- // const stateKey = id.split('.')[3];
128
- const arr = /zigbee.[0-9].[^.]+.(\S+)/gm.exec(id);
129
- if (arr[1] === undefined) {
130
- this.warn(`unable to extract id from state ${id}`);
131
- return;
132
- }
133
- const stateKey = arr[1];
134
- this.adapter.getObject(devId, (err, obj) => {
135
- if (obj) {
136
- const model = obj.common.type;
137
- if (!model) return;
138
- if (obj.common.deactivated) {
139
- this.debug('State Change detected on deactivated Device - ignored');
140
- return;
141
- }
142
- if (model === 'group') {
143
- deviceId = parseInt(deviceId.replace('0xgroup_', ''));
144
- }
145
- this.collectOptions(id.split('.')[2], model, options => {
146
- this.publishFromState(deviceId, model, stateKey, state, options);
147
- });
148
- }
149
- });
150
- }
151
- }
152
-
153
- async collectOptions(devId, model, callback) {
154
- const result = {};
155
- // find model states for options and get it values
156
- const devStates = await this.getDevStates('0x'+devId, model);
157
- if (!devStates) {
158
- callback(result);
159
- return;
160
- }
161
- const states = devStates.states.filter((statedesc) => statedesc.isOption || statedesc.inOptions);
162
- if (!states) {
163
- callback(result);
164
- return;
165
- }
166
- let cnt = 0;
167
- try {
168
- const len = states.length;
169
- states.forEach(statedesc => {
170
- const id = this.adapter.namespace + '.' + devId + '.' + statedesc.id;
171
- this.adapter.getState(id, (err, state) => {
172
- cnt = cnt + 1;
173
- if (!err && state) {
174
- result[statedesc.id] = state.val;
175
- }
176
- if (cnt === len) {
177
- callback(result);
178
- }
179
- });
180
- });
181
- if (!len) callback(result);
182
- } catch (error) {
183
- this.sendError(error);
184
- this.error(`Error collectOptions for ${devId}. Error: ${error.stack}`);
185
- }
186
- }
187
-
188
- async getDevStates(deviceId, model) {
189
- try {
190
- let states = [];
191
- let stateModel;
192
- if (model === 'group') {
193
- states = statesMapping.groupStates;
194
- } else {
195
- stateModel = statesMapping.findModel(model);
196
- if (!stateModel) {
197
- if (knownUndefinedDevices[deviceId])
198
- {
199
- knownUndefinedDevices[deviceId]++;
200
- }
201
- else {
202
- knownUndefinedDevices[deviceId] = 1;
203
- this.error('Device ' + deviceId + ' "' + model + '" not described in statesMapping.');
204
- }
205
- this.adapter.setStateAsync(`info.undefinedDevices`, JSON.stringify(knownUndefinedDevices), true);
206
- states = statesMapping.commonStates;
207
- } else {
208
- states = stateModel.states;
209
- }
210
- if (typeof states === 'function' && !states.prototype) {
211
- const entity = await this.adapter.zbController.resolveEntity(deviceId);
212
- if (entity)
213
- states = states(entity);
214
- }
215
- }
216
- return {states: states, stateModel: stateModel};
217
- } catch (error) {
218
- this.sendError(error);
219
- this.error(`Error getDevStates for ${deviceId}. Error: ${error.stack}`);
220
- }
221
- }
222
-
223
- async publishFromState(deviceId, model, stateKey, state, options) {
224
- if (this.debugDevices === undefined) this.getDebugDevices();
225
- this.debug(`Change state '${stateKey}' at device ${deviceId} type '${model}'`);
226
- for (const addressPart of this.debugDevices) {
227
- if (typeof(deviceId) == 'string' && deviceId.indexOf(addressPart) > -1)
228
- {
229
- this.warn(`ELEVATED Change state '${stateKey}' at device ${deviceId} type '${model}'`);
230
- break;
231
- }
232
- }
233
- const devStates = await this.getDevStates(deviceId, model);
234
- if (!devStates) {
235
- return;
236
- }
237
- const commonStates = statesMapping.commonStates.find((statedesc) => stateKey === statedesc.id);
238
- const stateDesc = (commonStates === undefined ? devStates.states.find((statedesc) => stateKey === statedesc.id) : commonStates);
239
- const stateModel = devStates.stateModel;
240
- if (!stateDesc) {
241
- this.error(`No state available for '${model}' with key '${stateKey}'`);
242
- return;
243
- }
244
-
245
- const value = state.val;
246
- if (value === undefined || value === '')
247
- return;
248
- let stateList = [{stateDesc: stateDesc, value: value, index: 0, timeout: 0}];
249
- if (stateModel && stateModel.linkedStates) {
250
- stateModel.linkedStates.forEach((linkedFunct) => {
251
- try {
252
- if (typeof linkedFunct === 'function') {
253
- const res = linkedFunct(stateDesc, value, options, this.adapter.config.disableQueue);
254
- if (res) {
255
- stateList = stateList.concat(res);
256
- }
257
- }
258
- else {
259
- this.warn('publish from State - LinkedState is not a function ' + JSON.stringify(linkedFunct));
260
- }
261
- } catch (e) {
262
- this.sendError(e);
263
- this.error('Exception caught in publishfromstate');
264
- }
265
-
266
- });
267
- // sort by index
268
- stateList.sort((a, b) => {
269
- return a.index - b.index;
270
- });
271
- }
272
-
273
- // holds the states for for read after write requests
274
- let readAfterWriteStates = [];
275
- if (stateModel && stateModel.readAfterWriteStates) {
276
- stateModel.readAfterWriteStates.forEach((readAfterWriteStateDesc) => {
277
- readAfterWriteStates = readAfterWriteStates.concat(readAfterWriteStateDesc.id);
278
- });
279
- }
280
-
281
- this.emit('changed', deviceId, model, stateModel, stateList, options);
282
- }
283
-
284
- renameDevice(id, newName) {
285
- this.storeDeviceName(id, newName);
286
- this.adapter.extendObject(id, {common: {name: newName}});
287
- }
288
-
289
- setDeviceActivated(id, active) {
290
- this.adapter.extendObject(id, {common: {deactivated: active }})
291
- }
292
-
293
- storeDeviceName(id, name) {
294
- savedDeviceNames[id.replace(`${this.adapter.namespace}.`, '')] = name;
295
- this.retainDeviceNames();
296
- }
297
-
298
- verifyDeviceName(id, name) {
299
- const savedId = id.replace(`${this.adapter.namespace}.`, '');
300
- if (!savedDeviceNames.hasOwnProperty(savedId)) {
301
- savedDeviceNames[savedId] = name;
302
- this.retainDeviceNames();
303
- }
304
- return savedDeviceNames[savedId];
305
- }
306
-
307
- deleteDeviceStates(devId, callback) {
308
- this.adapter.getStatesOf(devId, (err, states) => {
309
- if (!err && states) {
310
- states.forEach((state) => {
311
- this.adapter.deleteState(devId, null, state._id);
312
- });
313
- }
314
- this.adapter.deleteDevice(devId, () => {
315
- callback && callback();
316
- });
317
- });
318
- }
319
-
320
- async deleteDeviceStatesAsync(devId) {
321
- const states = await this.adapter.getStatesOf(devId);
322
- if (states) {
323
- await this.adapter.deleteState(devId, null, state._id);
324
- }
325
- await this.adapter.deleteDevice(devId);
326
- }
327
-
328
- // eslint-disable-next-line no-unused-vars
329
- async deleteOrphanedDeviceStates(ieeeAddr, model, force, callback) {
330
- const devStates = await this.getDevStates(ieeeAddr, model);
331
- const commonStates = statesMapping.commonStates;
332
- const devId = ieeeAddr.substr(2);
333
- this.adapter.getStatesOf(devId, (err, states) => {
334
- if (!err && states) {
335
- states.forEach((state) => {
336
- let statename = state._id;
337
- const arr = /zigbee.[0-9].[^.]+.(\S+)/gm.exec(statename);
338
- if (arr[1] === undefined) {
339
- this.warn(`unable to extract id from state ${statename}`);
340
- const idx = statename.lastIndexOf('.');
341
- if (idx > -1) statename = statename.slice(idx+1);
342
- } else {
343
- statename = arr[1];
344
- }
345
- if (commonStates.find((statedesc) => statename === statedesc.id) === undefined &&
346
- devStates.states.find((statedesc) => statename === statedesc.id) === undefined) {
347
- if (state.common.hasOwnProperty('custom') && !force) {
348
- this.info(`keeping disconnected state ${JSON.stringify(statename)} of ${devId} `);
349
- } else {
350
- this.info(`deleting disconnected state ${JSON.stringify(statename)} of ${devId} `);
351
- this.adapter.deleteState(devId, null, state._id);
352
- }
353
- }
354
- else {
355
- this.debug(`keeping connecte state ${JSON.stringify(statename)} of ${devId} `);
356
- }
357
- });
358
- }
359
- });
360
- }
361
-
362
- updateStateWithTimeout(dev_id, name, value, common, timeout, outValue) {
363
- this.updateState(dev_id, name, value, common);
364
- setTimeout(() => this.updateState(dev_id, name, outValue, common), timeout);
365
- }
366
-
367
- updateState(devId, name, value, common) {
368
- this.adapter.getObject(devId, (err, obj) => {
369
- if (obj) {
370
- if (!obj.common.deactivated) {
371
- const new_common = {name: name};
372
- const id = devId + '.' + name;
373
- const new_name = obj.common.name;
374
- if (common) {
375
- if (common.name !== undefined) {
376
- new_common.name = common.name;
377
- }
378
- if (common.type !== undefined) {
379
- new_common.type = common.type;
380
- }
381
- if (common.unit !== undefined) {
382
- new_common.unit = common.unit;
383
- }
384
- if (common.states !== undefined) {
385
- new_common.states = common.states;
386
- }
387
- if (common.read !== undefined) {
388
- new_common.read = common.read;
389
- }
390
- if (common.write !== undefined) {
391
- new_common.write = common.write;
392
- }
393
- if (common.role !== undefined) {
394
- new_common.role = common.role;
395
- }
396
- if (common.min !== undefined) {
397
- new_common.min = common.min;
398
- }
399
- if (common.max !== undefined) {
400
- new_common.max = common.max;
401
- }
402
- if (common.icon !== undefined) {
403
- new_common.icon = common.icon;
404
- }
405
- }
406
- // check if state exist
407
- this.adapter.getObject(id, (err, stobj) => {
408
- let hasChanges = false;
409
- if (stobj) {
410
- // update state - not change name and role (user can it changed)
411
- if (stobj.common.name)
412
- delete new_common.name;
413
- else
414
- new_common.name = new_name + ' ' + new_common.name;
415
- delete new_common.role;
416
-
417
- // check whether any common property is different
418
- if (stobj.common) {
419
- for (const property in new_common) {
420
- if (stobj.common.hasOwnProperty(property)) {
421
- if (stobj.common[property] === new_common[property]) {
422
- delete new_common[property];
423
- } else {
424
- hasChanges = true;
425
- }
426
- }
427
- }
428
- }
429
- } else {
430
- hasChanges = true;
431
- }
432
-
433
- // only change object when any common property has changed
434
- if (hasChanges) {
435
- this.adapter.extendObject(id, {type: 'state', common: new_common, native: {} }, () => {
436
- value !== undefined && this.setState_typed(id, value, true, (stobj) ? stobj.common.type : new_common.type);
437
- });
438
- } else if (value !== undefined) {
439
- this.setState_typed(id, value, true, stobj.common.type);
440
- }
441
-
442
- });
443
- }
444
- else this.debug(`UpdateState: Device is deactivated ${devId} ${JSON.stringify(obj)}`);
445
- } else {
446
- this.debug(`UpdateState: missing device ${devId} ${JSON.stringify(obj)}`);
447
- }
448
- });
449
- }
450
-
451
- setState_typed(id, value, ack, type, callback)
452
- {
453
- // never set a null or undefined value
454
- if (value === null || value === undefined) return;
455
- if (!type) {
456
- this.debug("SetState_typed called without type");
457
- // identify datatype, recursively call this function with set datatype
458
- this.adapter.getObject(id, (err, obj) => {
459
- if (obj && obj.common)
460
- this.setState_typed(id, value, ack, obj.common.type, callback);
461
- else {
462
- this.setState_typed(id, value, ack, 'noobj', callback);
463
- }
464
- });
465
- return;
466
- }
467
- if (typeof value != type) {
468
- this.debug("SetState_typed : converting " + JSON.stringify(value) + " for " + id + " from " + typeof value + " to " + type);
469
- switch (type) {
470
- case 'number':
471
- value = parseFloat(value);
472
- if (isNaN (value)) value = 0;
473
- break;
474
- case 'string':
475
- case 'text': value = JSON.stringify(value); break;
476
- case 'boolean':
477
- if (typeof value == 'number') {
478
- value = (value != 0);
479
- break;
480
- }
481
- const sval = JSON.stringify(value).toLowerCase().trim();
482
- value = (sval == 'true' || sval == 'yes' || sval == 'on');
483
- break;
484
- }
485
- }
486
- this.adapter.setState(id, value, ack, callback);
487
- }
488
-
489
- updateDev(dev_id, dev_name, model, callback) {
490
- const __dev_name = this.verifyDeviceName(dev_id, dev_name);
491
- const id = '' + dev_id;
492
- const modelDesc = statesMapping.findModel(model);
493
- let icon = (modelDesc && modelDesc.icon) ? modelDesc.icon : 'img/unknown.png';
494
-
495
- // download icon if it external and not undef
496
- if (model === undefined) {
497
- this.warn(`download icon ${__dev_name} for undefined Device not available. Check your devices.`);
498
- } else {
499
- const model_modif = model.replace(/\//g, '-');
500
- const pathToIcon = this.adapter.adapterDir + '/admin/img/' + model_modif + '.png';
501
-
502
- if (icon.startsWith('http')) {
503
- try {
504
- if (!fs.existsSync(pathToIcon)) {
505
- this.warn(`download icon from ${icon} saved into ${pathToIcon}`);
506
- this.downloadIcon(icon, pathToIcon);
507
- }
508
- icon = 'img/' + model_modif + '.png';
509
- } catch (e) {
510
- this.debug(`ERROR : icon not found from ${icon} saved into ${pathToIcon}`);
511
- }
512
- }
513
- }
514
-
515
- this.adapter.setObjectNotExists(id, {
516
- type: 'device',
517
- // actually this is an error, so device.common has no attribute type. It must be in native part
518
- common: {name: __dev_name, type: model, icon: icon, color: null, statusStates: {onlineId: `${this.adapter.namespace}.${dev_id}.available`}},
519
- native: {id: dev_id}
520
- }, () => {
521
- // update type and icon
522
- this.adapter.extendObject(id, {common: {type: model, icon: icon, color: null, statusStates: {onlineId: `${this.adapter.namespace}.${dev_id}.available`}}}, callback);
523
- });
524
- }
525
-
526
- async downloadIcon(url, image_path) {
527
- if (!fs.existsSync(image_path)) {
528
- return new Promise((resolve, reject) => {
529
- request.head(url, function (err, res, body) {
530
- if (err) {
531
- return reject(err);
532
- }
533
- let stream = request(url);
534
- stream.pipe(
535
- fs.createWriteStream(image_path)
536
- .on('error', err => {
537
- reject(err);
538
- })
539
- )
540
- .on('close', function () {
541
- resolve();
542
- });
543
- });
544
- });
545
- }
546
- }
547
-
548
- async syncDevStates(dev, model) {
549
- const devId = dev.ieeeAddr.substr(2);
550
- // devId - iobroker device id
551
- const devStates = await this.getDevStates(dev.ieeeAddr, model);
552
- if (!devStates) {
553
- return;
554
- }
555
- const states = statesMapping.commonStates.concat(devStates.states);
556
-
557
- for (const stateInd in states) {
558
- if (!states.hasOwnProperty(stateInd)) continue;
559
-
560
- const statedesc = states[stateInd];
561
- if (statedesc === undefined)
562
- {
563
- this.error(`syncDevStates: Illegal state in ${JSON.stringify(dev)} - ${JSON.stringify(stateInd)}`);
564
- return;
565
- }
566
- // Filter out non routers or devices that are battery driven for the availability flag
567
- if (statedesc.id === 'available')
568
- if (!(dev.type === 'Router') || dev.powerSource === 'Battery')
569
- continue;
570
- // lazy states
571
- if (statedesc.lazy) continue;
572
-
573
- const common = {
574
- name: statedesc.name,
575
- type: statedesc.type,
576
- unit: statedesc.unit,
577
- read: statedesc.read,
578
- write: statedesc.write,
579
- icon: statedesc.icon,
580
- role: statedesc.role,
581
- min: statedesc.min,
582
- max: statedesc.max,
583
- states: statedesc.states,
584
- };
585
- this.updateState(devId, statedesc.id, undefined, common);
586
- }
587
- }
588
-
589
-
590
- async getExcludeExposes(allExcludesObj) {
591
- statesMapping.fillStatesWithExposes(allExcludesObj);
592
- }
593
-
594
-
595
- async publishToState(devId, model, payload) {
596
- const devStates = await this.getDevStates('0x'+devId, model);
597
- let has_debug=false;
598
- if (this.debugDevices === undefined) this.getDebugDevices();
599
- for (const addressPart of this.debugDevices) {
600
- if (typeof(devId) == 'string' && devId.indexOf(addressPart) > -1)
601
- {
602
- if (payload.hasOwnProperty('msg_from_zigbee')) break;
603
- this.warn(`ELEVATED publishToState: message received '${JSON.stringify(payload)}' from device ${devId} type '${model}'`);
604
- has_debug = true;
605
- break;
606
- }
607
- }
608
- if (!devStates) {
609
- return;
610
- }
611
- // find states for payload
612
- if (devStates.states !== undefined) {
613
- const states = statesMapping.commonStates.concat(
614
- devStates.states.filter((statedesc) => payload.hasOwnProperty(statedesc.prop || statedesc.id))
615
- );
616
- for (const stateInd in states) {
617
- const statedesc = states[stateInd];
618
- let value;
619
- if (statedesc.getter) {
620
- value = statedesc.getter(payload);
621
- } else {
622
- value = payload[statedesc.prop || statedesc.id];
623
- }
624
- // checking value
625
- if (value === undefined || value === null) continue;
626
- let stateID = statedesc.id;
627
-
628
- if (has_debug && statedesc.id != 'msg_from_zigbee') {
629
- this.warn(`ELEVATED publishToState: value generated '${JSON.stringify(value)}' from device ${devId} for '${statedesc.name}'`);
630
- }
631
-
632
- const common = {
633
- name: statedesc.name,
634
- type: statedesc.type,
635
- unit: statedesc.unit,
636
- read: statedesc.read,
637
- write: statedesc.write,
638
- icon: statedesc.icon,
639
- role: statedesc.role,
640
- min: statedesc.min,
641
- max: statedesc.max,
642
- };
643
- if ( (typeof(value)== 'object') && (value.hasOwnProperty('stateid'))) {
644
- stateID = stateID + '.' + value.stateid;
645
- if (value.hasOwnProperty('unit')) common.unit = value.unit;
646
- common.name = (value.name? value.name:value.stateid);
647
- common.role = (value.role ? 'value.'+value.role:'number');
648
- value = value.value;
649
-
650
- }
651
- // if need return value to back after timeout
652
- if (statedesc.isEvent) {
653
- this.updateStateWithTimeout(devId, statedesc.id, value, common, 300, !value);
654
- } else {
655
- if (statedesc.prepublish) {
656
- this.collectOptions(devId, model, (options) => {
657
- statedesc.prepublish(devId, value, (newvalue) => {
658
- this.updateState(devId, stateID, newvalue, common);
659
- }, options);
660
- });
661
- } else {
662
- this.updateState(devId, stateID, value, common);
663
- }
664
- }
665
- }
666
- }
667
- }
668
- }
669
-
670
- module.exports = StatesController;
1
+ 'use strict';
2
+
3
+ const EventEmitter = require('events').EventEmitter;
4
+ const statesMapping = require('./devices');
5
+ const getAdId = require('./utils').getAdId;
6
+ const getZbId = require('./utils').getZbId;
7
+ const fs = require('fs');
8
+ const request = require('request');
9
+
10
+ var savedDeviceNames = {};
11
+ var knownUndefinedDevices = {};
12
+
13
+
14
+ class StatesController extends EventEmitter {
15
+ constructor(adapter) {
16
+ super();
17
+ this.adapter = adapter;
18
+ this.adapter.on('stateChange', this.onStateChange.bind(this));
19
+ this.query_device_block = [];
20
+ this.debugDevices = undefined;
21
+ let fn = adapter.expandFileName('dev_names.json');
22
+ this.dev_names_fn = fn.replace('.', '_');
23
+ this.retTimeoutHandle = null;
24
+ fs.readFile(this.dev_names_fn, (err, data) => {
25
+ if (!err) {
26
+ try
27
+ {
28
+ savedDeviceNames = JSON.parse(data);
29
+ }
30
+ catch
31
+ {
32
+ savedDeviceNames = {};
33
+ };
34
+ }
35
+ });
36
+ }
37
+
38
+ info(message, data) {
39
+ this.emit('log', 'info', message, data);
40
+ }
41
+
42
+ error(message, data) {
43
+ this.emit('log', 'error', message, data);
44
+ }
45
+
46
+ debug(message, data) {
47
+ this.emit('log', 'debug', message, data);
48
+ }
49
+
50
+ warn(message, data) {
51
+ this.emit('log', 'warn', message, data);
52
+ }
53
+
54
+ sendError(error, message) {
55
+ this.adapter.sendError(error, message);
56
+ }
57
+
58
+ retainDeviceNames()
59
+ {
60
+ clearTimeout(this.retTimeoutHandle);
61
+ this.retTimeoutHanlde = setTimeout(()=> {
62
+ fs.writeFile(this.dev_names_fn, JSON.stringify(savedDeviceNames, null, 2), (err) => {
63
+ if (err)
64
+ this.error('error saving device names: ' + JSON.Stringify(err));
65
+ else
66
+ this.debug('saved device names');
67
+ });},5000);
68
+ }
69
+
70
+ getDebugDevices() {
71
+ this.debugDevices = [];
72
+ this.adapter.getState(this.adapter.namespace + '.info.debugmessages', (err, state) => {
73
+ if (state) {
74
+ if (typeof(state.val) == 'string' && state.val.length > 2) this.debugDevices = state.val.split(';');
75
+ this.info('debug devices set to ' + JSON.stringify(this.debugDevices));
76
+ } else {
77
+ this.adapter.setObject('info.debugmessages', {
78
+ 'type': 'state',
79
+ 'common': {
80
+ 'name': 'Log changes as warnings for',
81
+ 'role': '',
82
+ 'type': 'string',
83
+ 'read': true,
84
+ 'write': true,
85
+ },
86
+ 'native': {},
87
+ });
88
+ }
89
+ });
90
+ this.adapter.setObject('info.undefinedDevices', {
91
+ 'type': 'state',
92
+ 'common': {
93
+ 'name': 'Recorded undefined devices',
94
+ 'role': '',
95
+ 'type': 'string',
96
+ 'read': true,
97
+ 'write': false,
98
+ },
99
+ 'native': {},
100
+ });
101
+ this.adapter.setStateAsync(`info.undefinedDevices`, JSON.stringify(knownUndefinedDevices), true);
102
+ }
103
+
104
+ onStateChange(id, state){
105
+ if (!this.adapter.zbController || !this.adapter.zbController.connected()) return;
106
+ if (this.debugDevices === undefined) this.getDebugDevices();
107
+ if (state && !state.ack) {
108
+ if (id.endsWith('pairingCountdown') || id.endsWith('pairingMessage') || id.endsWith('connection')) return;
109
+ if (id.endsWith('debugmessages')) {
110
+ if (typeof(state.val) == 'string' && state.val.length > 2)
111
+ this.debugDevices = state.val.split(';');
112
+ else {
113
+ this.debugDevices = [];
114
+ }
115
+ return;
116
+ }
117
+ for (const addressPart of this.debugDevices) {
118
+ if (typeof(id) == 'string' && id.indexOf(addressPart) > -1)
119
+ {
120
+ this.warn(`ELEVATED: User stateChange ${id} ${JSON.stringify(state)}`);
121
+ break;
122
+ }
123
+ }
124
+ this.debug(`User stateChange ${id} ${JSON.stringify(state)}`);
125
+ const devId = getAdId(this.adapter, id); // iobroker device id
126
+ let deviceId = getZbId(id); // zigbee device id
127
+ // const stateKey = id.split('.')[3];
128
+ const arr = /zigbee.[0-9].[^.]+.(\S+)/gm.exec(id);
129
+ if (arr[1] === undefined) {
130
+ this.warn(`unable to extract id from state ${id}`);
131
+ return;
132
+ }
133
+ const stateKey = arr[1];
134
+ this.adapter.getObject(devId, (err, obj) => {
135
+ if (obj) {
136
+ const model = obj.common.type;
137
+ if (!model) return;
138
+ if (obj.common.deactivated) {
139
+ this.debug('State Change detected on deactivated Device - ignored');
140
+ return;
141
+ }
142
+ if (model === 'group') {
143
+ deviceId = parseInt(deviceId.replace('0xgroup_', ''));
144
+ }
145
+ this.collectOptions(id.split('.')[2], model, options => {
146
+ this.publishFromState(deviceId, model, stateKey, state, options);
147
+ });
148
+ }
149
+ });
150
+ }
151
+ }
152
+
153
+ async collectOptions(devId, model, callback) {
154
+ const result = {};
155
+ // find model states for options and get it values
156
+ const devStates = await this.getDevStates('0x'+devId, model);
157
+ if (!devStates) {
158
+ callback(result);
159
+ return;
160
+ }
161
+ const states = devStates.states.filter((statedesc) => statedesc.isOption || statedesc.inOptions);
162
+ if (!states) {
163
+ callback(result);
164
+ return;
165
+ }
166
+ let cnt = 0;
167
+ try {
168
+ const len = states.length;
169
+ states.forEach(statedesc => {
170
+ const id = this.adapter.namespace + '.' + devId + '.' + statedesc.id;
171
+ this.adapter.getState(id, (err, state) => {
172
+ cnt = cnt + 1;
173
+ if (!err && state) {
174
+ result[statedesc.id] = state.val;
175
+ }
176
+ if (cnt === len) {
177
+ callback(result);
178
+ }
179
+ });
180
+ });
181
+ if (!len) callback(result);
182
+ } catch (error) {
183
+ this.sendError(error);
184
+ this.error(`Error collectOptions for ${devId}. Error: ${error.stack}`);
185
+ }
186
+ }
187
+
188
+ async getDevStates(deviceId, model) {
189
+ try {
190
+ let states = [];
191
+ let stateModel;
192
+ if (model === 'group') {
193
+ states = statesMapping.groupStates;
194
+ } else {
195
+ stateModel = statesMapping.findModel(model);
196
+ if (!stateModel) {
197
+ if (knownUndefinedDevices[deviceId])
198
+ {
199
+ knownUndefinedDevices[deviceId]++;
200
+ }
201
+ else {
202
+ knownUndefinedDevices[deviceId] = 1;
203
+ this.error('Device ' + deviceId + ' "' + model + '" not described in statesMapping.');
204
+ }
205
+ this.adapter.setStateAsync(`info.undefinedDevices`, JSON.stringify(knownUndefinedDevices), true);
206
+ states = statesMapping.commonStates;
207
+ } else {
208
+ states = stateModel.states;
209
+ }
210
+ if (typeof states === 'function' && !states.prototype) {
211
+ const entity = await this.adapter.zbController.resolveEntity(deviceId);
212
+ if (entity)
213
+ states = states(entity);
214
+ }
215
+ }
216
+ return {states: states, stateModel: stateModel};
217
+ } catch (error) {
218
+ this.sendError(error);
219
+ this.error(`Error getDevStates for ${deviceId}. Error: ${error.stack}`);
220
+ }
221
+ }
222
+
223
+ async publishFromState(deviceId, model, stateKey, state, options) {
224
+ if (this.debugDevices === undefined) this.getDebugDevices();
225
+ this.debug(`Change state '${stateKey}' at device ${deviceId} type '${model}'`);
226
+ for (const addressPart of this.debugDevices) {
227
+ if (typeof(deviceId) == 'string' && deviceId.indexOf(addressPart) > -1)
228
+ {
229
+ this.warn(`ELEVATED Change state '${stateKey}' at device ${deviceId} type '${model}'`);
230
+ break;
231
+ }
232
+ }
233
+ const devStates = await this.getDevStates(deviceId, model);
234
+ if (!devStates) {
235
+ return;
236
+ }
237
+ const commonStates = statesMapping.commonStates.find((statedesc) => stateKey === statedesc.id);
238
+ const stateDesc = (commonStates === undefined ? devStates.states.find((statedesc) => stateKey === statedesc.id) : commonStates);
239
+ const stateModel = devStates.stateModel;
240
+ if (!stateDesc) {
241
+ this.error(`No state available for '${model}' with key '${stateKey}'`);
242
+ return;
243
+ }
244
+
245
+ const value = state.val;
246
+ if (value === undefined || value === '')
247
+ return;
248
+ let stateList = [{stateDesc: stateDesc, value: value, index: 0, timeout: 0}];
249
+ if (stateModel && stateModel.linkedStates) {
250
+ stateModel.linkedStates.forEach((linkedFunct) => {
251
+ try {
252
+ if (typeof linkedFunct === 'function') {
253
+ const res = linkedFunct(stateDesc, value, options, this.adapter.config.disableQueue);
254
+ if (res) {
255
+ stateList = stateList.concat(res);
256
+ }
257
+ }
258
+ else {
259
+ this.warn('publish from State - LinkedState is not a function ' + JSON.stringify(linkedFunct));
260
+ }
261
+ } catch (e) {
262
+ this.sendError(e);
263
+ this.error('Exception caught in publishfromstate');
264
+ }
265
+
266
+ });
267
+ // sort by index
268
+ stateList.sort((a, b) => {
269
+ return a.index - b.index;
270
+ });
271
+ }
272
+
273
+ // holds the states for for read after write requests
274
+ let readAfterWriteStates = [];
275
+ if (stateModel && stateModel.readAfterWriteStates) {
276
+ stateModel.readAfterWriteStates.forEach((readAfterWriteStateDesc) => {
277
+ readAfterWriteStates = readAfterWriteStates.concat(readAfterWriteStateDesc.id);
278
+ });
279
+ }
280
+
281
+ this.emit('changed', deviceId, model, stateModel, stateList, options);
282
+ }
283
+
284
+ renameDevice(id, newName) {
285
+ this.storeDeviceName(id, newName);
286
+ this.adapter.extendObject(id, {common: {name: newName}});
287
+ }
288
+
289
+ setDeviceActivated(id, active) {
290
+ this.adapter.extendObject(id, {common: {deactivated: active }})
291
+ }
292
+
293
+ storeDeviceName(id, name) {
294
+ savedDeviceNames[id.replace(`${this.adapter.namespace}.`, '')] = name;
295
+ this.retainDeviceNames();
296
+ }
297
+
298
+ verifyDeviceName(id, name) {
299
+ const savedId = id.replace(`${this.adapter.namespace}.`, '');
300
+ if (!savedDeviceNames.hasOwnProperty(savedId)) {
301
+ savedDeviceNames[savedId] = name;
302
+ this.retainDeviceNames();
303
+ }
304
+ return savedDeviceNames[savedId];
305
+ }
306
+
307
+ deleteDeviceStates(devId, callback) {
308
+ this.adapter.getStatesOf(devId, (err, states) => {
309
+ if (!err && states) {
310
+ states.forEach((state) => {
311
+ this.adapter.deleteState(devId, null, state._id);
312
+ });
313
+ }
314
+ this.adapter.deleteDevice(devId, () => {
315
+ callback && callback();
316
+ });
317
+ });
318
+ }
319
+
320
+ async deleteDeviceStatesAsync(devId) {
321
+ const states = await this.adapter.getStatesOf(devId);
322
+ if (states) {
323
+ await this.adapter.deleteState(devId, null, state._id);
324
+ }
325
+ await this.adapter.deleteDevice(devId);
326
+ }
327
+
328
+ // eslint-disable-next-line no-unused-vars
329
+ async deleteOrphanedDeviceStates(ieeeAddr, model, force, callback) {
330
+ const devStates = await this.getDevStates(ieeeAddr, model);
331
+ const commonStates = statesMapping.commonStates;
332
+ const devId = ieeeAddr.substr(2);
333
+ this.adapter.getStatesOf(devId, (err, states) => {
334
+ if (!err && states) {
335
+ states.forEach((state) => {
336
+ let statename = state._id;
337
+ const arr = /zigbee.[0-9].[^.]+.(\S+)/gm.exec(statename);
338
+ if (arr[1] === undefined) {
339
+ this.warn(`unable to extract id from state ${statename}`);
340
+ const idx = statename.lastIndexOf('.');
341
+ if (idx > -1) statename = statename.slice(idx+1);
342
+ } else {
343
+ statename = arr[1];
344
+ }
345
+ if (commonStates.find((statedesc) => statename === statedesc.id) === undefined &&
346
+ devStates.states.find((statedesc) => statename === statedesc.id) === undefined) {
347
+ if (state.common.hasOwnProperty('custom') && !force) {
348
+ this.info(`keeping disconnected state ${JSON.stringify(statename)} of ${devId} `);
349
+ } else {
350
+ this.info(`deleting disconnected state ${JSON.stringify(statename)} of ${devId} `);
351
+ this.adapter.deleteState(devId, null, state._id);
352
+ }
353
+ }
354
+ else {
355
+ this.debug(`keeping connecte state ${JSON.stringify(statename)} of ${devId} `);
356
+ }
357
+ });
358
+ }
359
+ });
360
+ }
361
+
362
+ updateStateWithTimeout(dev_id, name, value, common, timeout, outValue) {
363
+ this.updateState(dev_id, name, value, common);
364
+ setTimeout(() => this.updateState(dev_id, name, outValue, common), timeout);
365
+ }
366
+
367
+ updateState(devId, name, value, common) {
368
+ this.adapter.getObject(devId, (err, obj) => {
369
+ if (obj) {
370
+ if (!obj.common.deactivated) {
371
+ const new_common = {name: name};
372
+ const id = devId + '.' + name;
373
+ const new_name = obj.common.name;
374
+ if (common) {
375
+ if (common.name !== undefined) {
376
+ new_common.name = common.name;
377
+ }
378
+ if (common.type !== undefined) {
379
+ new_common.type = common.type;
380
+ }
381
+ if (common.unit !== undefined) {
382
+ new_common.unit = common.unit;
383
+ }
384
+ if (common.states !== undefined) {
385
+ new_common.states = common.states;
386
+ }
387
+ if (common.read !== undefined) {
388
+ new_common.read = common.read;
389
+ }
390
+ if (common.write !== undefined) {
391
+ new_common.write = common.write;
392
+ }
393
+ if (common.role !== undefined) {
394
+ new_common.role = common.role;
395
+ }
396
+ if (common.min !== undefined) {
397
+ new_common.min = common.min;
398
+ }
399
+ if (common.max !== undefined) {
400
+ new_common.max = common.max;
401
+ }
402
+ if (common.icon !== undefined) {
403
+ new_common.icon = common.icon;
404
+ }
405
+ }
406
+ // check if state exist
407
+ this.adapter.getObject(id, (err, stobj) => {
408
+ let hasChanges = false;
409
+ if (stobj) {
410
+ // update state - not change name and role (user can it changed)
411
+ if (stobj.common.name)
412
+ delete new_common.name;
413
+ else
414
+ new_common.name = new_name + ' ' + new_common.name;
415
+ delete new_common.role;
416
+
417
+ // check whether any common property is different
418
+ if (stobj.common) {
419
+ for (const property in new_common) {
420
+ if (stobj.common.hasOwnProperty(property)) {
421
+ if (stobj.common[property] === new_common[property]) {
422
+ delete new_common[property];
423
+ } else {
424
+ hasChanges = true;
425
+ }
426
+ }
427
+ }
428
+ }
429
+ } else {
430
+ hasChanges = true;
431
+ }
432
+
433
+ // only change object when any common property has changed
434
+ if (hasChanges) {
435
+ this.adapter.extendObject(id, {type: 'state', common: new_common, native: {} }, () => {
436
+ value !== undefined && this.setState_typed(id, value, true, (stobj) ? stobj.common.type : new_common.type);
437
+ });
438
+ } else if (value !== undefined) {
439
+ this.setState_typed(id, value, true, stobj.common.type);
440
+ }
441
+
442
+ });
443
+ }
444
+ else this.debug(`UpdateState: Device is deactivated ${devId} ${JSON.stringify(obj)}`);
445
+ } else {
446
+ this.debug(`UpdateState: missing device ${devId} ${JSON.stringify(obj)}`);
447
+ }
448
+ });
449
+ }
450
+
451
+ setState_typed(id, value, ack, type, callback)
452
+ {
453
+ // never set a null or undefined value
454
+ if (value === null || value === undefined) return;
455
+ if (!type) {
456
+ this.debug("SetState_typed called without type");
457
+ // identify datatype, recursively call this function with set datatype
458
+ this.adapter.getObject(id, (err, obj) => {
459
+ if (obj && obj.common)
460
+ this.setState_typed(id, value, ack, obj.common.type, callback);
461
+ else {
462
+ this.setState_typed(id, value, ack, 'noobj', callback);
463
+ }
464
+ });
465
+ return;
466
+ }
467
+ if (typeof value != type) {
468
+ this.debug("SetState_typed : converting " + JSON.stringify(value) + " for " + id + " from " + typeof value + " to " + type);
469
+ switch (type) {
470
+ case 'number':
471
+ value = parseFloat(value);
472
+ if (isNaN (value)) value = 0;
473
+ break;
474
+ case 'string':
475
+ case 'text': value = JSON.stringify(value); break;
476
+ case 'boolean':
477
+ if (typeof value == 'number') {
478
+ value = (value != 0);
479
+ break;
480
+ }
481
+ const sval = JSON.stringify(value).toLowerCase().trim();
482
+ value = (sval == 'true' || sval == 'yes' || sval == 'on');
483
+ break;
484
+ }
485
+ }
486
+ this.adapter.setState(id, value, ack, callback);
487
+ }
488
+
489
+ updateDev(dev_id, dev_name, model, callback) {
490
+ const __dev_name = this.verifyDeviceName(dev_id, dev_name);
491
+ const id = '' + dev_id;
492
+ const modelDesc = statesMapping.findModel(model);
493
+ let icon = (modelDesc && modelDesc.icon) ? modelDesc.icon : 'img/unknown.png';
494
+
495
+ // download icon if it external and not undef
496
+ if (model === undefined) {
497
+ this.warn(`download icon ${__dev_name} for undefined Device not available. Check your devices.`);
498
+ } else {
499
+ const model_modif = model.replace(/\//g, '-');
500
+ const pathToIcon = this.adapter.adapterDir + '/admin/img/' + model_modif + '.png';
501
+
502
+ if (icon.startsWith('http')) {
503
+ try {
504
+ if (!fs.existsSync(pathToIcon)) {
505
+ this.warn(`download icon from ${icon} saved into ${pathToIcon}`);
506
+ this.downloadIcon(icon, pathToIcon);
507
+ }
508
+ icon = 'img/' + model_modif + '.png';
509
+ } catch (e) {
510
+ this.debug(`ERROR : icon not found from ${icon} saved into ${pathToIcon}`);
511
+ }
512
+ }
513
+ }
514
+
515
+ this.adapter.setObjectNotExists(id, {
516
+ type: 'device',
517
+ // actually this is an error, so device.common has no attribute type. It must be in native part
518
+ common: {name: __dev_name, type: model, icon: icon, color: null, statusStates: {onlineId: `${this.adapter.namespace}.${dev_id}.available`}},
519
+ native: {id: dev_id}
520
+ }, () => {
521
+ // update type and icon
522
+ this.adapter.extendObject(id, {common: {type: model, icon: icon, color: null, statusStates: {onlineId: `${this.adapter.namespace}.${dev_id}.available`}}}, callback);
523
+ });
524
+ }
525
+
526
+ async downloadIcon(url, image_path) {
527
+ if (!fs.existsSync(image_path)) {
528
+ return new Promise((resolve, reject) => {
529
+ request.head(url, function (err, res, body) {
530
+ if (err) {
531
+ return reject(err);
532
+ }
533
+ let stream = request(url);
534
+ stream.pipe(
535
+ fs.createWriteStream(image_path)
536
+ .on('error', err => {
537
+ reject(err);
538
+ })
539
+ )
540
+ .on('close', function () {
541
+ resolve();
542
+ });
543
+ });
544
+ });
545
+ }
546
+ }
547
+
548
+ async syncDevStates(dev, model) {
549
+ const devId = dev.ieeeAddr.substr(2);
550
+ // devId - iobroker device id
551
+ const devStates = await this.getDevStates(dev.ieeeAddr, model);
552
+ if (!devStates) {
553
+ return;
554
+ }
555
+ const states = statesMapping.commonStates.concat(devStates.states);
556
+
557
+ for (const stateInd in states) {
558
+ if (!states.hasOwnProperty(stateInd)) continue;
559
+
560
+ const statedesc = states[stateInd];
561
+ if (statedesc === undefined)
562
+ {
563
+ this.error(`syncDevStates: Illegal state in ${JSON.stringify(dev)} - ${JSON.stringify(stateInd)}`);
564
+ return;
565
+ }
566
+ // Filter out non routers or devices that are battery driven for the availability flag
567
+ if (statedesc.id === 'available')
568
+ if (!(dev.type === 'Router') || dev.powerSource === 'Battery')
569
+ continue;
570
+ // lazy states
571
+ if (statedesc.lazy) continue;
572
+
573
+ const common = {
574
+ name: statedesc.name,
575
+ type: statedesc.type,
576
+ unit: statedesc.unit,
577
+ read: statedesc.read,
578
+ write: statedesc.write,
579
+ icon: statedesc.icon,
580
+ role: statedesc.role,
581
+ min: statedesc.min,
582
+ max: statedesc.max,
583
+ states: statedesc.states,
584
+ };
585
+ this.updateState(devId, statedesc.id, undefined, common);
586
+ }
587
+ }
588
+
589
+
590
+ async getExcludeExposes(allExcludesObj) {
591
+ statesMapping.fillStatesWithExposes(allExcludesObj);
592
+ }
593
+
594
+
595
+ async publishToState(devId, model, payload) {
596
+ const devStates = await this.getDevStates('0x'+devId, model);
597
+ let has_debug=false;
598
+ if (this.debugDevices === undefined) this.getDebugDevices();
599
+ for (const addressPart of this.debugDevices) {
600
+ if (typeof(devId) == 'string' && devId.indexOf(addressPart) > -1)
601
+ {
602
+ if (payload.hasOwnProperty('msg_from_zigbee')) break;
603
+ this.warn(`ELEVATED publishToState: message received '${JSON.stringify(payload)}' from device ${devId} type '${model}'`);
604
+ has_debug = true;
605
+ break;
606
+ }
607
+ }
608
+ if (!devStates) {
609
+ return;
610
+ }
611
+ // find states for payload
612
+ if (devStates.states !== undefined) {
613
+ const states = statesMapping.commonStates.concat(
614
+ devStates.states.filter((statedesc) => payload.hasOwnProperty(statedesc.prop || statedesc.id))
615
+ );
616
+ for (const stateInd in states) {
617
+ const statedesc = states[stateInd];
618
+ let value;
619
+ if (statedesc.getter) {
620
+ value = statedesc.getter(payload);
621
+ } else {
622
+ value = payload[statedesc.prop || statedesc.id];
623
+ }
624
+ // checking value
625
+ if (value === undefined || value === null) continue;
626
+ let stateID = statedesc.id;
627
+
628
+ if (has_debug && statedesc.id != 'msg_from_zigbee') {
629
+ this.warn(`ELEVATED publishToState: value generated '${JSON.stringify(value)}' from device ${devId} for '${statedesc.name}'`);
630
+ }
631
+
632
+ const common = {
633
+ name: statedesc.name,
634
+ type: statedesc.type,
635
+ unit: statedesc.unit,
636
+ read: statedesc.read,
637
+ write: statedesc.write,
638
+ icon: statedesc.icon,
639
+ role: statedesc.role,
640
+ min: statedesc.min,
641
+ max: statedesc.max,
642
+ };
643
+ if ( (typeof(value)== 'object') && (value.hasOwnProperty('stateid'))) {
644
+ stateID = stateID + '.' + value.stateid;
645
+ if (value.hasOwnProperty('unit')) common.unit = value.unit;
646
+ common.name = (value.name? value.name:value.stateid);
647
+ common.role = (value.role ? 'value.'+value.role:'number');
648
+ value = value.value;
649
+
650
+ }
651
+ // if need return value to back after timeout
652
+ if (statedesc.isEvent) {
653
+ this.updateStateWithTimeout(devId, statedesc.id, value, common, 300, !value);
654
+ } else {
655
+ if (statedesc.prepublish) {
656
+ this.collectOptions(devId, model, (options) => {
657
+ statedesc.prepublish(devId, value, (newvalue) => {
658
+ this.updateState(devId, stateID, newvalue, common);
659
+ }, options);
660
+ });
661
+ } else {
662
+ this.updateState(devId, stateID, value, common);
663
+ }
664
+ }
665
+ }
666
+ }
667
+ }
668
+ }
669
+
670
+ module.exports = StatesController;