This repository has been archived by the owner on Mar 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
main.js
1428 lines (1303 loc) · 61.6 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
/**
* ioBroker Z-Wave Adapter
*
* Copyright 2016, bluefox <[email protected]>
*
* License: GNU LGPL
*/
const path = require("path");
const fs = require("fs");
const utils = require('@iobroker/adapter-core'); // Get common adapter utils
const comClasses = require(path.join(__dirname, 'admin/js/comClasses.js'));
var zwave;
var objects = {};
var nodes = {};
var inclusion = null;
var exclusion = null;
var addNodeSecure = false;
var notificationCodes = [
/*0:*/ 'message complete',
/*1:*/ 'timeout',
/*2:*/ 'nop',
/*3:*/ 'node awake',
/*4:*/ 'node sleep',
/*5:*/ 'node dead (Undead Undead Undead)',
/*6:*/ 'node alive'
];
var ctrlState = [
/*0: */ 'No command in progress',
/*1: */ 'The command is starting',
/*2: */ 'The command was cancelled',
/*3: */ 'Command invocation had error(s) and was aborted',
/*4: */ 'Controller is waiting for a user action (60s)',
/*5: */ 'Controller command is on a sleep queue wait for device',
/*6: */ 'The controller is communicating with the other device to carry out the command',
/*7: */ 'The command has completed successfully',
/*8: */ 'The command has failed',
/*9: */ 'The controller thinks the node is OK',
/*10:*/ 'The controller thinks the node has failed'
];
var ctrlError = [
/*0:*/ 'No error',
/*1*/ 'ButtonNotFound',
/*2:*/ 'NodeNotFound',
/*3:*/ 'NotBridge',
/*4:*/ 'NotSUC',
/*5:*/ 'NotSecondary',
/*6:*/ 'NotPrimary',
/*7:*/ 'IsPrimary',
/*8:*/ 'NotFound',
/*9:*/ 'Busy',
/*10:*/ 'Failed',
/*11:*/ 'Disabled',
/*12:*/ 'Overflow'
];
/**
* The adapter instance
* @type {ioBroker.Adapter}
*/
let adapter;
/**
* Starts the adapter instance
* @param {Partial<ioBroker.AdapterOptions>} [options]
*/
function startAdapter(options) {
// Create the adapter and define its methods
return adapter = utils.adapter(Object.assign({}, options, {
name: 'zwave',
ready: function () {
adapter.getObjectList({
startkey: adapter.namespace + '.',
endkey: adapter.namespace + '.\u9999',
include_docs: true
}, function (err, res) {
adapter.getObjectList({
startkey: 'enum.rooms.',
endkey: 'enum.rooms.\u9999',
include_docs: true
}, function (err, rooms) {
objects = {};
var devices = [];
if (res) {
res = res.rows;
if (res) {
for (var i = 0; i < res.length; i++) {
objects[res[i].value._id] = res[i].value;
if (res[i].value.type === 'device') devices.push(res[i].value._id);
}
}
}
if (rooms) {
res = rooms.rows;
if (res) {
for (var r = 0; r < res.length; r++) {
objects[res[r].value._id] = res[r].value;
}
}
}
adapter.log.debug('received all objects');
adapter.subscribeObjects('*');
adapter.subscribeStates('*');
adapter.subscribeForeignObjects('enum.rooms.*');
extendInstanceObjects();
setAllNotReady(devices, main);
});
});
},
message: function (obj) {
// responds to the adapter that sent the original message
function respond(response) {
if (obj.callback)
adapter.sendTo(obj.from, obj.command, response, obj.callback);
}
// some predefined responses so we only have to define them once
var predefinedResponses = {
ACK: { error: null },
OK: { error: null, result: 'ok' },
ERROR_UNKNOWN_COMMAND: { error: 'Unknown command!' },
ERROR_NOT_RUNNING: { error: 'zwave driver is not running!' },
MISSING_PARAMETER: function (paramName) {
return {error: 'missing parameter "' + paramName + '"!'};
},
COMMAND_RUNNING: {error: 'command running'}
};
// make required parameters easier
function requireParams(params) {
if (!(params && params.length)) return true;
for (var i = 0; i < params.length; i++) {
if (!(obj.message && obj.message.hasOwnProperty(params[i]))) {
respond(predefinedResponses.MISSING_PARAMETER(params[i]));
return false;
}
}
return true;
}
// handle the message
if (obj) {
if (obj.command !== 'stopCommand' && obj.command !== 'listUart' && (inclusion || exclusion)) {
respond(predefinedResponses.COMMAND_RUNNING);
return;
}
addNodeSecure = false;
switch (obj.command) {
case 'stopCommand':
disableInclusion();
disableExclusion();
respond(predefinedResponses.ACK);
break;
case 'listUart':
if (obj.callback) {
var ports = listSerial();
adapter.log.info('List of ports: ' + JSON.stringify(ports));
respond(ports);
}
break;
case 'softReset':
case 'hardReset': // destructive! will wipe out all known configuration
case 'healNetwork':
if (zwave) {
adapter.log.info('Execute ' + obj.command);
if (zwave[obj.command]) {
zwave[obj.command]();
respond(predefinedResponses.OK);
if (obj.command === "hardReset") {
// hardReset deletes all node info on the controller
// make sure the nodes get deleted in ioBroker aswell
deleteAllNonControllerNodes();
}
} else {
adapter.log.error('Unknown command!');
respond(predefinedResponses.ERROR_UNKNOWN_COMMAND);
}
} else {
respond(predefinedResponses.ERROR_NOT_RUNNING);
}
break;
case 'networkmap':
if (zwave) {
adapter.log.debug('Show network map');
var map = [];
var allNodeIDs = Object.keys(nodes);
var edges = {};
for (var i in allNodeIDs) {
const nodeID = allNodeIDs[i];
edges[nodeID] = [];
const neighbors = zwave.getNodeNeighbors(nodeID);
for (var n in neighbors) {
if (!edges[neighbors[n]]) {
edges[nodeID].push(neighbors[n]);
}
}
const channelID = calcName(nodeID);
const label = objects[channelID] ? objects[channelID].common.name : "Node" + nodeID;
const item = {
"nodeID": nodeID,
"neighbors": edges[nodeID],
"label": label
}
map.push(item);
}
adapter.getState('info.networkLayout', function (err, result) {
if (!err && result && result.val) {
const layout = JSON.parse(result.val);
for (var e in map) {
var item = map[e];
if (layout[item.nodeID]) {
item['x'] = layout[item.nodeID].x;
item['y'] = layout[item.nodeID].y;
}
}
respond(map);
} else {
respond(map);
}
});
} else {
respond(predefinedResponses.ERROR_NOT_RUNNING);
}
break;
case 'storeNetworkLayout':
if (obj.message) {
adapter.log.debug("saving layout");
adapter.setState('info.networkLayout', JSON.stringify(obj.message), true);
respond(predefinedResponses.OK);
} else {
respond(predefinedResponses.ERROR_UNKNOWN_COMMAND);
}
break;
case 'removeFailedNode':
case 'requestNodeNeighborUpdate':
case 'assignReturnRoute':
case 'deleteAllReturnRoutes':
case 'replaceFailedNode':
case 'requestNetworkUpdate':
case 'replicationSend':
case 'refreshNodeInfo':
case 'healNetworkNode':
if (zwave && obj.message) {
adapter.log.info('Execute ' + obj.command + ' for ' + obj.message.nodeID);
if (zwave[obj.command]) {
zwave[obj.command](obj.message.nodeID);
respond(predefinedResponses.OK);
} else {
adapter.log.error('Unknown command!');
respond(predefinedResponses.ERROR_UNKNOWN_COMMAND);
}
} else {
respond(predefinedResponses.ERROR_NOT_RUNNING);
}
break;
case 'setNodeName':
case 'setNodeLocation':
if (zwave && obj.message) {
adapter.log.info('Execute ' + obj.command + ' for ' + obj.message.nodeID + ' with "' + obj.message.param + '"');
if (zwave[obj.command]) {
zwave[obj.command](obj.message.nodeID, obj.message.param);
respond(predefinedResponses.OK);
} else {
adapter.log.error('Unknown command!');
respond(predefinedResponses.ERROR_UNKNOWN_COMMAND);
}
} else {
respond(predefinedResponses.ERROR_NOT_RUNNING);
}
break;
// createButton(nodeid, buttonid)
// deleteButton(nodeid, buttonid)
case 'createButton':
case 'deleteButton':
if (zwave && obj.message) {
adapter.log.info('Execute ' + obj.command + ' for ' + obj.message.nodeID + ' with "' + obj.message.param + '"');
if (zwave[obj.command]) {
zwave[obj.command](obj.message.nodeID, obj.message.param);
respond(predefinedResponses.OK);
} else {
adapter.log.error('Unknown command!');
respond(predefinedResponses.ERROR_UNKNOWN_COMMAND);
}
} else {
respond(predefinedResponses.ERROR_NOT_RUNNING);
}
break;
case 'addNodeSecure':
addNodeSecure = true;
case 'addNode':
if (zwave) {
adapter.log.info('Execute addNode ' + (addNodeSecure ? 'secure' : ''));
adapter.setState('inclusionOn', true, true);
inclusion = setTimeout(function () {
disableInclusion();
}, 60000);
zwave.addNode(addNodeSecure);
respond(predefinedResponses.ACK);
} else {
respond(predefinedResponses.ERROR_NOT_RUNNING);
}
break;
case 'removeNode':
if (zwave) {
adapter.log.info('Execute ' + obj.command);
adapter.setState('exclusionOn', true, true);
exclusion = setTimeout(function () {
disableExclusion();
}, 60000);
zwave.removeNode();
respond(predefinedResponses.ACK);
} else {
respond(predefinedResponses.ERROR_NOT_RUNNING);
}
break;
// Association groups management functions:
case 'getNumGroups': // zwave.getNumGroups(nodeid) => number;
if (zwave && obj.message) {
if (!requireParams(["nodeID"])) break;
adapter.log.info('Requesting number of association groups from node' + obj.message.nodeID);
if (zwave[obj.command]) {
let result = zwave[obj.command](obj.message.nodeID);
respond({ error: null, result: result });
} else {
adapter.log.error('Unknown command!');
respond(predefinedResponses.ERROR_UNKNOWN_COMMAND);
}
} else {
respond(predefinedResponses.ERROR_NOT_RUNNING);
}
break;
case 'getGroupLabel': // zwave.getGroupLabel(nodeid, group) => string;
if (zwave && obj.message) {
if (!requireParams(["nodeID", "group"])) break;
adapter.log.info('Requesting label of association group ' + obj.message.group + ' from node ' + obj.message.nodeID);
if (zwave[obj.command]) {
let result = zwave[obj.command](obj.message.nodeID, obj.message.group);
respond({ error: null, result: result });
} else {
adapter.log.error('Unknown command!');
respond(predefinedResponses.ERROR_UNKNOWN_COMMAND);
}
} else {
respond(predefinedResponses.ERROR_NOT_RUNNING);
}
break;
case 'getAllAssociationGroups': // shortcut to get all groups => { groupIndex: {label: <string>, maxAssociations: <number>, isLifeline: <boolean>}, ...}
if (zwave && obj.message) {
if (!requireParams(["nodeID"])) break;
adapter.log.info('Requesting all association groups from node ' + obj.message.nodeID);
/** @type {Record<string, any> | string} */
let result = {};
// get the number of groups
var numGroups = zwave.getNumGroups(obj.message.nodeID);
if (numGroups > 0) {
// and for each group request the label and association count
for (var group = 1; group <= numGroups; group++) {
result[group] = {
label: zwave.getGroupLabel(obj.message.nodeID, group),
maxAssociations: zwave.getMaxAssociations(obj.message.nodeID, group),
isLifeline: false
};
}
// now find out which group is the lifeline
var foundLifeline = false;
for (var strategy = 1; strategy <= 3; strategy++) {
switch (strategy) {
case 1: // strategy 1: find the group with maxAssoc 1 and label "Lifeline"
for (var group = 1; group <= numGroups; group++) {
if (result[group].label === "Lifeline" && result[group].maxAssociations === 1) {
result[group].isLifeline = true;
foundLifeline = true;
break;
}
}
break;
case 2: // strategy 2: find a group with maxAssoc 1
for (var group = 1; group <= numGroups; group++) {
if (result[group].maxAssociations === 1) {
result[group].isLifeline = true;
foundLifeline = true;
break;
}
}
break;
case 3: // strategy 3: use group #1 as lifeline
result[1].isLifeline = true;
foundLifeline = true;
break;
}
if (foundLifeline) break;
}
} else {
result = "no groups";
}
respond({ error: null, result: result });
} else {
respond(predefinedResponses.ERROR_NOT_RUNNING);
}
break;
case 'getAssociations': // zwave.getAssociations(nodeid, group);
if (zwave && obj.message) {
if (!requireParams(["nodeID", "group"])) break;
adapter.log.info('Requesting associations in group ' + obj.message.group + ' from node ' + obj.message.nodeID);
if (zwave.isMultiInstance(obj.message.nodeID, obj.message.group)) {
let result = zwave.getAssociationsInstances(obj.message.nodeID, obj.message.group);
var response = [];
if (result.length > 0) {
for (var i = 0; i < result.length; ++i) {
if (result[i].instance > 0) {
// <node id>.<instance id>
response.push(result[i].nodeid+"."+result[i].instance);
} else {
response.push(result[i].nodeid);
}
}
}
respond({ error: null, result: response });
} else {
let result = zwave.getAssociations(obj.message.nodeID, obj.message.group);
respond({ error: null, result: result });
}
} else {
respond(predefinedResponses.ERROR_NOT_RUNNING);
}
break;
case 'getMaxAssociations': // zwave.getMaxAssociations(nodeid, group);
if (zwave && obj.message) {
if (!requireParams(["nodeID", "group"])) break;
adapter.log.info('Requesting max number of associations in group ' + obj.message.group + ' from node ' + obj.message.nodeID);
if (zwave[obj.command]) {
let result = zwave[obj.command](obj.message.nodeID, obj.message.group);
respond({ error: null, result: result });
} else {
adapter.log.error('Unknown command!');
respond(predefinedResponses.ERROR_UNKNOWN_COMMAND);
}
} else {
respond(predefinedResponses.ERROR_NOT_RUNNING);
}
break;
case 'addAssociation': // zwave.addAssociation(nodeid, group, target_nodeid);
if (zwave && obj.message) {
if (!requireParams(["nodeID", "group", "target_nodeid"])) break;
if (zwave[obj.command]) {
if (typeof obj.message.target_nodeid === 'string' && obj.message.target_nodeid.indexOf('.') != -1) {
var parts = obj.message.target_nodeid.split('.');
adapter.log.info('Adding association with node ' + parts[0] + ' and instance ' + parts[1] + ' to group ' + obj.message.group + ' of node ' + obj.message.nodeID);
zwave.addAssociation(obj.message.nodeID, obj.message.group, parts[0], parts[1]);
} else {
adapter.log.info('Adding association with node ' + obj.message.target_nodeid + ' to group ' + obj.message.group + ' of node ' + obj.message.nodeID);
zwave.addAssociation(obj.message.nodeID, obj.message.group, obj.message.target_nodeid);
}
respond(predefinedResponses.OK);
} else {
adapter.log.error('Unknown command!');
respond(predefinedResponses.ERROR_UNKNOWN_COMMAND);
}
} else {
respond(predefinedResponses.ERROR_NOT_RUNNING);
}
break;
case 'removeAssociation': // zwave.removeAssociation(nodeid, group, target_nodeid);
if (zwave && obj.message) {
if (!requireParams(["nodeID", "group", "target_nodeid"])) break;
if (zwave[obj.command]) {
if (typeof obj.message.target_nodeid === 'string' && obj.message.target_nodeid.indexOf('.') != -1) {
var parts = obj.message.target_nodeid.split('.');
adapter.log.info('Removing association with node ' + parts[0] + ' and instance ' + parts[1] + ' from group ' + obj.message.group + ' of node ' + obj.message.nodeID);
zwave.removeAssociation(obj.message.nodeID, obj.message.group, parts[0], parts[1]);
} else {
adapter.log.info('Removing association with node ' + obj.message.target_nodeid + ' from group ' + obj.message.group + ' of node ' + obj.message.nodeID);
zwave.removeAssociation(obj.message.nodeID, obj.message.group, obj.message.target_nodeid);
}
} else {
adapter.log.error('Unknown command!');
respond(predefinedResponses.ERROR_UNKNOWN_COMMAND);
}
} else {
respond(predefinedResponses.ERROR_NOT_RUNNING);
}
break;
case 'getNumberOfInstances': // get the number of instances that are supported by the node
if (zwave && obj.message) {
if (!requireParams(["nodeID"])) break;
var instances = 1;
const id = calcName(obj.message.nodeID);
for (var i in objects) {
if (!objects.hasOwnProperty(i)) continue;
if (i.startsWith(id + '.')) {
if (objects[i].native && objects[i].native.value_id && objects[i].native.instance > instances) {
instances = objects[i].native.instance;
}
}
}
adapter.log.debug("getNumberOfInstances for "+obj.message.nodeID + "=" + instances);
respond(instances);
} else {
respond(predefinedResponses.ERROR_NOT_RUNNING);
}
break;
case 'getControllerState': // used by the message view of the admin
adapter.getState('info.controllerMessage', function (err, result) {
if (!err && result && result.val) {
const data = JSON.parse(result.val);
var response = {
"state": ctrlState[data.state],
"error": ((data.error && data.error !== 0) || data.state == 8) ? true : false,
"helpMsg": data.helpMsg + " (" + ctrlError[data.error] + ")"
}
respond(response);
}
});
break;
default:
adapter.log.error('Unknown command: ' + obj.command);
break;
}
}
},
objectChange: function (id, obj) {
if (!obj) {
if (objects[id]) delete objects[id];
} else {
objects[id] = obj;
}
},
stateChange: function (id, state) {
if (!state || state.ack || state.val === undefined) return;
adapter.log.debug('stateChange ' + id + ' set ' + JSON.stringify(state));
var obj = objects[id];
if (obj && obj.native) {
var nodeID = obj.native.node_id;
var valueID = { // this allows to shorten the zwave API calls
node_id: obj.native.node_id,
class_id: obj.native.class_id,
instance: obj.native.instance,
index: obj.native.index
};
if (nodes[nodeID]) {
var value = state.val;
if (state.val === true || state.val === 'true') {
value = 1;
if (obj.native.max !== undefined && obj.native.max !== obj.native.min) value = obj.native.max;
} else if (state.val === false || state.val === 'false') {
value = 0;
if (obj.native.min !== undefined && obj.native.max !== obj.native.min) value = obj.native.min;
}
if (obj.native.type === 'bool' || obj.native.type === 'button') value = !!value;
if (obj.common.role === 'meta.config') {
// set a configuration parameter
adapter.log.debug('setConfigParam for: nodeID=' + obj.native.node_id + ': index=' + obj.native.index + ': value=' + value);
if (zwave) {
zwave.setConfigParam(
obj.native.node_id,
obj.native.index,
value,
value.length
);
}
} else if (obj.native.type === 'button') {
// openzwave-shared only presses buttons and doesn't release them on setValue
// so we need to press/release them ourselves
adapter.log.debug((value ? 'pushing' : 'releasing') + ' button for: nodeID=' + obj.native.node_id + ': comClass=' + obj.native.class_id + ': index=' + obj.native.index + ': instance=' + obj.native.instance);
if (zwave) {
if (value) {
zwave.pressButton(valueID);
} else {
zwave.releaseButton(valueID);
}
}
} else {
// set a value
adapter.log.debug('setState for: nodeID=' + obj.native.node_id + ': comClass=' + obj.native.class_id + ': index=' + obj.native.index + ': instance=' + obj.native.instance + ': value=' + value);
if (zwave) zwave.setValue(valueID, value);
}
} else {
if (!nodes[nodeID]) {
adapter.log.warn('Object "' + id + '" was not detected');
} else {
adapter.log.warn('Object "' + id + '" is not ready');
}
}
} else {
adapter.log.warn('Object "' + id + '" not found for stateChange');
}
},
unload: function (callback) {
if (zwave) zwave.disconnect(adapter.config.usb);
resetInstanceStatusInfo();
callback();
}
}));
}
function filterSerialPorts(path) {
// get only serial port names
if (!(/(tty(S|ACM|USB|AMA|MFD)|rfcomm)/).test(path)) return false;
return fs
.statSync(path)
.isCharacterDevice();
}
function listSerial() {
// Filter out the devices that aren't serial ports
var devDirName = '/dev';
let result;
try {
result = fs
.readdirSync(devDirName)
.map(function (file) {
return path.join(devDirName, file);
})
.filter(filterSerialPorts)
.map(function (port) {
return {comName: port};
});
} catch (e) {
adapter.log.error('Cannot read "' + devDirName + '": ' + e);
result = [];
}
return result;
}
function extendInclusion() {
if (inclusion) {
clearTimeout(inclusion);
inclusion = setTimeout(function () {
disableInclusion();
}, 30000);
}
}
function disableInclusion() {
adapter.log.info('disabled inclusion mode');
adapter.setState('inclusionOn', false, true);
if (inclusion) {
clearTimeout(inclusion);
inclusion = null;
if (zwave) zwave.cancelControllerCommand();
return true;
}
return false;
}
function disableExclusion() {
adapter.log.info('disabled exclusion mode');
adapter.setState('exclusionOn', false, true);
if (exclusion) {
clearTimeout(exclusion);
exclusion = null;
if (zwave) zwave.cancelControllerCommand();
return true;
}
return false;
}
function setAllNotReady(list, callback) {
if (!list || !list.length) {
callback();
} else {
var id = list.pop();
adapter.setForeignState(id + '.ready', false, true, function () {
adapter.setForeignState(id + '.sleep', false, true, function () {
adapter.setForeignState(id + '.alive', false, true, function () {
setTimeout(setAllNotReady, 0, list, callback);
});
});
});
}
}
function delObjects(list, callback) {
if (!list || !list.length) {
if (callback) callback();
} else {
var obj = list.pop();
var id = obj.id || obj._id;
var type = obj.value ? obj.value.type : obj.type;
adapter.delForeignObject(id, function (err) {
if (err && err !== 'Not exists') adapter.log.error('res from delObject: ' + err);
if (type === 'state') {
adapter.delForeignState(id, function (err) {
if (err && err !== 'Not exists') adapter.log.error('res from deleteState: ' + err);
setTimeout(delObjects, 0, list, callback);
});
} else {
setTimeout(delObjects, 0, list, callback);
}
});
}
}
// This fixes existing zwave state objects, so they are using role="switch" instead of role="button"
// because Zwave buttons support two states. Call
function fixZwaveButtons(callback) {
adapter.log.debug('fixing zwave buttons to use common.role "switch" instead of "button"');
// Find all state objects representing a zwave button
var stateObjs = Object.keys(objects)
.filter(function (id) { return id.startsWith(adapter.namespace); })
.map(function (id) { return objects[id] })
.filter(function (obj) { return obj.type === "state" && obj.common.role === "button" && obj.native.type === "button"; })
;
if (!(stateObjs && stateObjs.length > 0)) {
// no objects to fix, return immediately
if (callback) callback();
return;
} else {
adapter.log.debug('found ' + stateObjs.length + ' states to fix');
doFix(stateObjs);
}
function doFix(list) {
if (!list.length) {
adapter.log.debug('done fixing states');
if (callback) callback();
return;
}
var obj = list.pop();
var id = obj.id || obj._id;
obj.common.role = "switch";
adapter.setObject(id, obj, function (err) {
setTimeout(doFix, 0, list);
});
}
}
/**
* Replaces forbidden chars in strings used for IDs
* @param {string} id The ID which might contain forbidden
* @param {boolean} [includeDots=false] Whether "." should be escaped aswell
* @returns {string}
*/
function replaceForbiddenCharsInID(id, includeDots) {
// Although JS-Controller offers a FORBIDDEN_CHARS regex on the adapter class,
// we use our own here, because we need to escape spaces aswell
const regex = /[\]\[*,;'"`<>\\?\s]+/g;
id = id.replace(regex, '_');
if (includeDots) id = id.replace(/\./g, '');
return id;
}
function calcName(nodeID, comClass, idx, instance) {
var name = adapter.namespace + '.NODE' + nodeID;
if (comClass) {
name += '.' + ((comClasses[comClass] ? comClasses[comClass].name : '') || ('CLASSES' + comClass));
if (idx !== undefined) {
idx = replaceForbiddenCharsInID(idx, true);
name = name + '.' + idx;
if (instance !== undefined) {
name = name + '_' + instance;
}
}
}
var i = name.lastIndexOf('.');
var len = name.length - 1;
if (i === len) name = name.substring(0, len);
return name;
}
function extendNode(nodeID, nodeInfo, callback) {
var id = calcName(nodeID);
nodeInfo = JSON.parse(JSON.stringify(nodeInfo));
nodeInfo.nodeID = nodeID;
var count = 0;
if (objects[id]) {
if (JSON.stringify(objects[id].native) !== JSON.stringify(nodeInfo)) {
adapter.log.info('Update ' + id);
objects[id].native = nodeInfo;
if (!objects[id].common.name || nodeInfo.name) objects[id].common.name = nodeInfo.name || nodeInfo.manufacturer ? nodeInfo.name || (nodeInfo.manufacturer + ' ' + nodeInfo.product) : '';
count++;
adapter.extendForeignObject(id, objects[id], function () {
if (!--count && callback) callback();
});
}
} else {
/** @type {ioBroker.SettableObject} */
var devObj = {
common: {
name: nodeInfo.name || nodeInfo.manufacturer ? nodeInfo.name || (nodeInfo.manufacturer + ' ' + nodeInfo.product) : '',
role: 'state'
},
native: nodeInfo,
type: 'device'
};
adapter.log.info('Create new device: ' + id + '[' + devObj.common.name + ']');
count++;
adapter.setForeignObject(id, devObj, function () {
if (!--count && callback) callback();
});
}
// create ready flag
if (!objects[id + '.ready']) {
count++;
adapter.setForeignObject(id + '.ready', {
common: {
name: 'If ' + nodeInfo.product + ' is ready for commands',
write: false,
read: true,
type: 'boolean',
role: 'indicator.ready'
},
native: {},
type: 'state'
}, function () {
if (!--count && callback) callback();
});
}
if (!objects[id + '.alive']) {
count++;
adapter.setForeignObject(id + '.alive', {
common: {
name: 'If ' + nodeInfo.product + ' is alive',
write: false,
read: true,
type: 'boolean',
role: 'indicator.alive'
},
native: {},
type: 'state'
}, function () {
if (!--count && callback) callback();
});
}
if (!objects[id + '.sleep']) {
count++;
adapter.setForeignObject(id + '.sleep', {
common: {
name: 'If ' + nodeInfo.product + ' is sleeping',
write: false,
read: true,
type: 'boolean',
role: 'indicator.sleep'
},
native: {},
type: 'state'
}, function () {
if (!--count && callback) callback();
});
}
//create event state
if (!objects[id + '.event']) {
count++;
adapter.setForeignObject(id + '.event', {
common: {
name: 'Received events from node',
write: false,
read: true,
type: 'mixed',
role: 'state'
},
native: {},
type: 'state'
}, function () {
if (!--count && callback) callback();
});
}
if (nodeInfo.loc) {
var roomId = 'enum.rooms.' + replaceForbiddenCharsInID(nodeInfo.loc, false);
if (!objects[roomId]) {
count++;
objects[roomId] = {
type: 'enum',
common: {
name: nodeInfo.loc,
desc: '',
members: [roomId]
}
};
adapter.setForeignObject(roomId, objects[roomId], function () {
if (!--count && callback) callback();
});
} else if (objects[roomId].common.members && objects[roomId].common.members.indexOf(id) === -1) {
objects[roomId].common.members.push(id);
count++;
adapter.setForeignObject(roomId, objects[roomId], function () {
if (!--count && callback) callback();
});
}
}
if (!count && callback) callback();
}
function extendChannel(nodeID, comClass, valueId) {
if (!valueId || !comClass) return;
var channelID = calcName(nodeID, comClass);
var stateID = calcName(nodeID, comClass, valueId.label, valueId.genre === 'user' ? valueId.instance : undefined);
// Create channel
if (objects[channelID]) {
var newNative = objects[channelID].native || {};
newNative.nodeID = nodeID;
// compare native
if (JSON.stringify(objects[channelID].native) !== JSON.stringify(newNative) ||
// compare role
(comClasses[comClass] && comClasses[comClass].role && !objects[channelID].common.role)) {
if (comClasses[comClass] && comClasses[comClass].role) {
objects[channelID].common.role = comClasses[comClass].role;
}
objects[channelID].native = newNative;
adapter.log.info('Channel updated: ' + channelID + ' = ' + valueId.value + ', index = ' + valueId.index + ', comClass = ' + comClass + ', instance = ' + valueId.instance);
adapter.extendForeignObject(channelID, objects[channelID]);
}
} else {
/** @type {ioBroker.SettableObject} */
var chObj = {
common: {
name: valueId.label
},
native: {
nodeID: nodeID
},
type: 'channel',
_id: channelID
};
if (comClasses[comClass] && comClasses[comClass].role) {
chObj.common.role = comClasses[comClass].role;
}
adapter.log.info('Channel created: ' + channelID + ' = ' + valueId.value + ', index = ' + valueId.index + ', comClass = ' + comClass + ', instance = ' + valueId.instance);
adapter.setForeignObject(channelID, chObj);
}
var role;
var type;
if (comClasses[comClass] && comClasses[comClass].role) {
if (comClasses[comClass].children && comClasses[comClass].children[valueId.label]) {
var child = comClasses[comClass].children[valueId.label];
if (child.role) {
role = child.role;
} else {
role = comClasses[comClass].role;
}
if (child.type) {
type = child.type;
} else if (comClasses[comClass].type) {
type = comClasses[comClass].type;
}
} else {
role = comClasses[comClass].role;
type = comClasses[comClass].type;
}
}
valueId = JSON.parse(JSON.stringify(valueId));