This repository has been archived by the owner on Feb 24, 2021. It is now read-only.
/
ZwaveClient.js
1439 lines (1236 loc) · 37.1 KB
/
ZwaveClient.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
/* eslint-disable camelcase */
'use strict'
// eslint-disable-next-line one-var
var reqlib = require('app-root-path').require,
OpenZWave = require('openzwave-shared'),
utils = reqlib('/lib/utils.js'),
EventEmitter = require('events'),
fs = require('fs'),
jsonStore = reqlib('/lib/jsonStore.js'),
store = reqlib('config/store.js'),
storeDir = utils.joinPath(true, reqlib('config/app.js').storeDir),
debug = reqlib('/lib/debug')('Zwave'),
Tail = require('tail').Tail,
inherits = require('util').inherits
debug.color = 4
const ZWAVE_STATUS = {
0: 'driverReady',
1: 'connected',
2: 'scanDone',
5: 'driverFailed',
6: 'closed'
}
const ZWAVE_LOG_FILE = utils.joinPath(storeDir, 'OZW_Log.txt')
const readFile = path =>
new Promise((resolve, reject) =>
fs.readFile(path, 'utf8', (err, data) =>
err ? reject(err) : resolve(data)
)
)
// https://github.com/OpenZWave/open-zwave/wiki/Adding-Devices#configuration-variable-types
const VAR_TYPES = {
bool: v => Boolean(v),
byte: v => parseInt(v),
int: v => parseInt(v),
short: v => parseInt(v),
decimal: v => +v.toString().replace(',', '.'),
string: null,
raw: null,
list: null,
bitset: (v, valueId) => {
valueId.value = parseInt(v)
var binaryValue = v.toString(2)
if (binaryValue.length < 8) {
binaryValue = '0'.repeat(8 - binaryValue.length) + binaryValue
}
for (const bit in valueId.bitSetIds) {
valueId.bitSetIds[bit].value =
binaryValue.charAt(8 - parseInt(bit)) === '1'
}
return valueId.value
}
}
// Events to subscribe to
// Info at: https://github.com/OpenZWave/node-openzwave-shared/blob/master/src/callbacks.cc
const EVENTS = {
'driver ready': driverReady,
'driver failed': driverFailed,
connected: connected,
'node added': nodeAdded,
'node removed': nodeRemoved,
'node available': nodeAvailable,
'node ready': nodeReady,
// 'node naming': nop,
'node event': nodeEvent,
// 'polling disabled': nop,
// 'polling enabled': nop,
// 'create button': nop,
// 'delete button': nop,
// 'button on': nop,
// 'button off': nop,
'scene event': sceneEvent,
'value added': valueAdded,
'value changed': valueChanged,
'value removed': valueRemoved,
'value refreshed': valueChanged,
notification: notification,
'scan complete': scanComplete,
'controller command': controllerCommand
}
// Status based on notification
const NODE_STATUS = {
0: 'Initializing',
3: 'Awake',
4: 'Sleep',
5: 'Dead',
6: 'Alive'
}
// the singleton client connection instance
var CLIENT
/**
* The constructor
*/
function ZwaveClient (config, socket) {
if (!(this instanceof ZwaveClient)) {
return new ZwaveClient(config)
}
EventEmitter.call(this)
init.call(this, config, socket)
}
inherits(ZwaveClient, EventEmitter)
async function init (cfg, socket) {
this.cfg = cfg
this.socket = socket
// create file if doesn't exist
fs.writeFileSync(ZWAVE_LOG_FILE, '')
this.tail = new Tail(ZWAVE_LOG_FILE)
this.tail.on(
'line',
function (data) {
data = data.substr(23)
this.emitEvent(
'DEBUG',
'\x1b[36m' + 'OpenZWave' + '\x1b[0m' + data + '\n'
)
}.bind(this)
)
this.tail.on('error', function (error) {
debug('Error while tailing log file ', error)
})
this.closed = false
this.scenes = jsonStore.get(store.scenes)
cfg.saveConfig = cfg.saveConfig || process.env.OZW_SAVE_CONFIG
cfg.autoUpdateConfig =
cfg.autoUpdateConfig || process.env.OZW_AUTO_UPDATE_CONFIG
// Full option list: https://github.com/OpenZWave/open-zwave/wiki/Config-Options
var options = {
Logging: cfg.logging,
ConsoleOutput: cfg.logging,
QueueLogLevel: cfg.logging ? 8 : 6,
UserPath: storeDir, // where to store config files
DriverMaxAttempts: 9999,
SaveConfiguration: Boolean(cfg.saveConfig),
// RetryTimeout: 10000,
// IntervalBetweenPolls: true,
PollInterval: cfg.pollInterval || process.env.OZW_POLL_INTERVAL,
AutoUpdateConfigFile: Boolean(cfg.autoUpdateConfig)
// SuppressValueRefresh: true,
}
cfg.networkKey = cfg.networkKey || process.env.OZW_NETWORK_KEY
if (cfg.networkKey) {
options.NetworkKey = cfg.networkKey.replace(/\s/g, '')
}
if (cfg.configPath) {
options.ConfigPath = cfg.configPath || process.env.OZW_CONFIG_PATH
}
if (cfg.assumeAwake) {
options.AssumeAwake = cfg.assumeAwake || process.env.OZW_ASSUME_AWAKE
}
if (cfg.options) {
Object.assign(options, cfg.options)
}
if (CLIENT) {
this.client = CLIENT
this.client.updateOptions(options)
} else {
this.client = CLIENT = new OpenZWave(options)
if (cfg.plugin) {
try {
require(cfg.plugin)(this)
} catch (error) {
debug(`Error while loading ${cfg.plugin} plugin`, error.message)
}
}
}
this.nodes = []
this.zwcfg_nodes = {}
this.devices = {}
this.ozwConfig = {}
this.healTimeout = null
var self = this
Object.keys(EVENTS).forEach(function (evt) {
self.client.on(evt, onEvent.bind(self, evt))
self.client.on(evt, EVENTS[evt].bind(self))
})
}
// ---------- ZWAVE EVENTS -------------------------------------
// catch all events
function onEvent (name, ...args) {
this.lastUpdate = Date.now()
this.emit('event', name, ...args)
}
async function driverReady (homeid) {
this.driverReadyStatus = true
this.ozwConfig.homeid = homeid
var homeHex = '0x' + homeid.toString(16)
this.ozwConfig.name = homeHex
this.error = false
this.status = ZWAVE_STATUS[0]
this.zwcfg_nodes = jsonStore.get(store.nodes)
// pre-load nodes properties by reading zwcfg xml file
if (this.zwcfg_nodes.length === 0) {
try {
var zwcfg = await readFile(
utils.joinPath(storeDir, 'zwcfg_' + homeHex + '.xml')
)
var matches
// Fails if name or location contains " char
var regex = /Node id="([\d]+)" name="([^"]*)" location="([^"]*)"/g
// eslint-disable-next-line no-cond-assign
while ((matches = regex.exec(zwcfg))) {
var nodeID = parseInt(matches[1])
var name = matches[2] || ''
var loc = matches[3] || ''
// this call is async so it is possible that node has been already added
if (this.nodes[nodeID]) {
this.nodes[nodeID].name = name
this.nodes[nodeID].loc = loc
}
this.zwcfg_nodes[nodeID] = {}
this.zwcfg_nodes[nodeID].name = name
this.zwcfg_nodes[nodeID].loc = loc
}
// update in memory file
if (this.zwcfg_nodes.length > 0) {
await jsonStore.put(store.nodes, this.zwcfg_nodes)
}
} catch (error) {
debug('Error while reading zwcfg file', error.message)
}
}
debug('Scanning network with homeid:', homeHex)
// delete any previous existing config
if (!this.cfg.saveConfig) {
fs.readdir(storeDir, (err, files) => {
if (err) debug('Error while reading configuration dir', err.message)
else {
files.forEach(file => {
if (/zwcfg_[\w]+.xml/g.test(file) || file === 'zwscene.xml') {
fs.unlinkSync(utils.joinPath(storeDir, file))
}
})
}
})
}
}
function driverFailed () {
this.error = 'Driver failed'
this.status = ZWAVE_STATUS[5]
debug('Driver failed', this.ozwConfig)
}
function connected (version) {
this.ozwConfig.version = version
debug('Zwave connected, Openzwave version:', version)
this.status = ZWAVE_STATUS[1]
this.emitEvent('CONNECTED', this.ozwConfig)
}
function nodeRemoved (nodeid) {
// don't use splice here, nodeid equals to the index in the array
var node = this.nodes[nodeid]
if (node) {
this.nodes[nodeid] = null
}
debug('Node removed', nodeid)
this.emit('nodeRemoved', node)
this.addEmptyNodes()
this.emitEvent('NODE_REMOVED', this.nodes[nodeid])
}
// Triggered when a node is added
function nodeAdded (nodeid) {
this.nodes[nodeid] = {
node_id: nodeid,
device_id: '',
manufacturer: '',
manufacturerid: '',
product: '',
producttype: '',
productid: '',
type: '',
name: this.zwcfg_nodes[nodeid] ? this.zwcfg_nodes[nodeid].name : '',
loc: this.zwcfg_nodes[nodeid] ? this.zwcfg_nodes[nodeid].loc : '',
values: {},
groups: [],
neighborns: [],
ready: false,
available: false,
hassDevices: {},
failed: false,
lastActive: null,
status: NODE_STATUS[0] // initializing
}
this.addEmptyNodes()
debug('Node added', nodeid)
}
// Triggered after node added event when the node info are firstly loaded
// ATTENTION: Values not added yet here
function nodeAvailable (nodeid, nodeinfo) {
var ozwnode = this.nodes[nodeid]
if (ozwnode) {
this.initNode(ozwnode, nodeinfo)
debug(
'node %d AVAILABLE: %s - %s (%s)',
nodeid,
nodeinfo.manufacturer,
nodeinfo.product,
nodeinfo.type || 'Unknown'
)
}
}
// Triggered after node available event when a value is added
function valueAdded (nodeid, comclass, valueId) {
var ozwnode = this.nodes[nodeid]
if (!ozwnode) {
debug('ValueAdded: no such node: ' + nodeid, 'error')
} else {
// if (comclass === 0x86) {
// valueId = {
// "value_id": nodeid+"-112-1-48",
// "node_id": 5,
// "class_id": 112,
// "type": "bitset",
// "genre": "config",
// "instance": 1,
// "index": 48,
// "label": "Enable/disable to send a report on Threshold",
// "units": "",
// "help": "Enable/disable to send a report when the measurement is more than the upper limit value or less than the lower limit value. Note: If USB power, the Sensor will check the limit every 10 seconds. If battery power, the Sensor will check the limit when it is waken up.",
// "read_only": false,
// "write_only": false,
// "min": 0,
// "max": 0,
// "is_polled": false,
// "bitSetIds": {
// "1": {
// "help": "Lower Temperature Threshold",
// "label": "Lower Temperature",
// "value": false
// },
// "2": {
// "help": "Lower Humdity Threshold",
// "label": "Lower Humidity",
// "value": false
// },
// "3": {
// "help": "Lower Luminance Threshold",
// "label": "Lower Luminance",
// "value": false
// },
// "4": {
// "help": "Lower Ultraviolet Threshold",
// "label": "Lower Ultraviolet",
// "value": false
// },
// "5": {
// "help": "Upper Temerature Threshold",
// "label": "Upper Temperature",
// "value": false
// },
// "6": {
// "help": "Upper Humdity Threshold",
// "label": "Upper Humidity",
// "value": false
// },
// "7": {
// "help": "Upper Luminance Threshold",
// "label": "Upper Luminance",
// "value": false
// },
// "8": {
// "help": "Upper Ultraviolet Threshold",
// "label": "Upper Ultraviolet",
// "value": false
// }
// },
// "bitMask": 255,
// "value": 0
// }
// }
// if (comclass === 94 && valueId.instance === 1 && valueId.index === 0) {
// valueId = {
// 'value_id': nodeid + '-49-1-1',
// 'node_id': nodeid,
// 'class_id': 49,
// 'index': 1,
// 'type': 'decimal',
// 'genre': 'user',
// 'instance': 1,
// 'label': 'Temperature',
// 'units': '°C',
// 'help': 'Test temperature',
// 'read_only': true,
// 'write_only': false,
// 'min': 0,
// 'max': 40,
// 'is_polled': false,
// 'value': 28
// }
// }
parseValue(valueId)
debug('ValueAdded: %s %s', valueId.value_id, valueId.label)
var id = getValueID(valueId)
ozwnode.values[id] = valueId
if (comclass === 0x86 && valueId.index === 2) {
// application version
ozwnode.version = valueId.value
}
// check if node is added as secure node
if (comclass === 0x98 && valueId.index === 0) {
ozwnode.secure = valueId.value
}
this.emit('valueChanged', valueId, ozwnode)
}
}
// Triggered after all values have been added
function nodeReady (nodeid, nodeinfo) {
var ozwnode = this.nodes[nodeid]
if (ozwnode) {
// When a node is added 'on fly' it never triggers 'node available'
if (!ozwnode.available) {
this.initNode(ozwnode, nodeinfo)
}
ozwnode.ready = true
ozwnode.status = NODE_STATUS[6]
ozwnode.lastActive = Date.now()
// add it to know devices types (if not already present)
if (!this.devices[ozwnode.device_id]) {
this.devices[ozwnode.device_id] = {
name: `[${ozwnode.device_id}] ${ozwnode.product} (${ozwnode.manufacturer})`,
values: JSON.parse(JSON.stringify(ozwnode.values))
}
// remove node specific info from values
for (var v in this.devices[ozwnode.device_id].values) {
var tmp = this.devices[ozwnode.device_id].values[v]
delete tmp.node_id
delete tmp.hassDevices
tmp.value_id = getValueID(tmp)
}
}
// Update values and subscribe for changes
for (const id in ozwnode.values) {
this.emit('valueChanged', ozwnode.values[id], ozwnode)
}
this.emit('nodeStatus', ozwnode)
debug(
'node %d ready: %s - %s (%s)',
nodeid,
nodeinfo.manufacturer,
nodeinfo.product,
nodeinfo.type || 'Unknown'
)
}
}
// Triggered when a node is ready and a value changes
function valueChanged (nodeid, comclass, valueId) {
var ozwnode = this.nodes[nodeid]
var value_id = getValueID(valueId)
var triggerStatusUpdate = false
parseValue(valueId)
if (!ozwnode) {
debug('valueChanged: no such node: ' + nodeid, 'error')
} else {
var oldst
if (ozwnode.ready) {
oldst = ozwnode.values[value_id].value
debug(
`zwave node ${nodeid}: changed: ${value_id}:${valueId.label}:${oldst} -> ${valueId.value}`
)
this.emit('valueChanged', valueId, ozwnode, oldst !== valueId.value)
}
// update cache
ozwnode.values[value_id] = valueId
// update last active timestamp
ozwnode.lastActive = Date.now()
triggerStatusUpdate = true
}
// check if node is added as secure node
if (comclass === 0x98 && valueId.index === 0) {
ozwnode.secure = valueId.value
triggerStatusUpdate = true
}
// trigger a status update if something important has changed
if (triggerStatusUpdate) {
this.emit('nodeStatus', ozwnode)
}
}
function valueRemoved (nodeid, comclass, instance, index) {
var ozwnode = this.nodes[nodeid]
var value_id = getValueID({
class_id: comclass,
instance: instance,
index: index
})
if (ozwnode.values[value_id]) {
delete ozwnode.values[value_id]
debug('ValueRemoved: %s from node %d', value_id, nodeid)
} else {
debug('ValueRemoved: no such node: ' + nodeid, 'error')
}
}
function nodeEvent (nodeid, evtcode) {
debug('node event', nodeid, evtcode)
this.emit('nodeSceneEvent', 'node', this.nodes[nodeid], evtcode)
}
function sceneEvent (nodeid, sceneCode) {
debug('scene event', nodeid, sceneCode)
this.emit('nodeSceneEvent', 'scene', this.nodes[nodeid], sceneCode)
}
function notification (nodeid, notif, help) {
var ozwnode = this.nodes[nodeid]
switch (notif) {
case 0: // message complete
case 1: // timeout
case 2: // nop
break
case 3: // awake
case 4: // sleep
case 5: // dead
case 6: // alive
// eslint-disable-next-line no-case-declarations
const ready = notif !== 5
// eslint-disable-next-line no-case-declarations
const wasReady = ozwnode.ready
if (ready || (!ready && wasReady)) {
ozwnode.lastActive = Date.now()
}
ozwnode.status = NODE_STATUS[notif]
ozwnode.ready = ready
if (ozwnode.available) {
this.emit('nodeStatus', ozwnode)
}
}
debug('Notification from node %d: %s (%s)', nodeid, help, notif)
}
function scanComplete () {
this.scanComplete = true
this.status = ZWAVE_STATUS[2]
var nodes = this.nodes.filter(n => !n.failed)
// popolate groups (just for active nodes)
for (var i = 0; i < nodes.length; i++) {
this.getGroups(nodes[i].node_id)
nodes[i].neighborns = this.client.getNodeNeighbors(nodes[i].node_id)
}
if (this.cfg.saveConfig && typeof this.client.writeConfig === 'function') {
this.client.writeConfig()
}
debug('Network scan complete. Found:', nodes.length, 'nodes')
}
function controllerCommand (nodeid, state, errcode, help) {
var obj = {
nodeid: nodeid,
state: state,
errcode: errcode,
help: help.replace('ControllerCommand - ', '')
}
debug('controller command', obj)
this.cntStatus = obj.help
// NodeFailed
if (errcode === 0 && state === 10) {
nodeRemoved.call(this, nodeid)
}
this.emitEvent('CONTROLLER_CMD', obj)
}
// ------- Utils ------------------------
/**
* Get the device id of a specific node
*
* @param {Object} ozwnode Zwave node Object
* @returns A string in the format `<manufacturerId>-<productId>-<producttype>` that unique identifhy a zwave device
*/
function getDeviceID (ozwnode) {
if (!ozwnode) return ''
return `${parseInt(ozwnode.manufacturerid)}-${parseInt(
ozwnode.productid
)}-${parseInt(ozwnode.producttype)}`
}
/**
* Used to parse a valueId value based on value type
*
* @param {Object} valueId Zwave valueId object
*/
function parseValue (valueId) {
var fun = VAR_TYPES[valueId.type]
if (fun) {
valueId.value = fun(valueId.value, valueId)
}
}
/**
* Get a valueId from a valueId object
*
* @param {Object} v Zwave valueId object
* @returns The value id without node reference: `${v.class_id}-${v.instance}-${v.index}`
*/
function getValueID (v) {
return `${v.class_id}-${v.instance}-${v.index}`
}
/**
* Function wrapping code used for writing queue.
* fn - reference to function.
* context - what you want "this" to be.
* params - array of parameters to pass to function.
*/
function wrapFunction (fn, context, params) {
return function () {
fn.apply(context, params)
}
}
/**
* Deep copy of an object
*
* @param {*} obj The object to copy
* @returns The copied object
*/
function copy (obj) {
return JSON.parse(JSON.stringify(obj))
}
// -------- Public methods --------------
/**
* Used to get unique homeHex of driver
*/
Object.defineProperty(ZwaveClient.prototype, 'homeHex', {
get: function () {
return this.ozwConfig.name
},
enumerable: true
})
/**
* Used to schedule next network heal at hours: cfg.healHours
*/
ZwaveClient.prototype.scheduleHeal = function () {
if (!this.cfg.healNetwork) {
return
}
var now = new Date()
var start
var hour = this.cfg.healHour
if (now.getHours() < hour) {
start = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate(),
hour,
0,
0,
0
)
} else {
start = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate() + 1,
hour,
0,
0,
0
)
}
var wait = start.getTime() - now.getTime()
if (wait < 0) {
this.scheduleHeal()
} else {
this.healTimeout = setTimeout(this.heal.bind(this), wait)
}
}
/**
* Calls client healNetwork function and schedule next heal
*
*/
ZwaveClient.prototype.heal = function () {
if (this.healTimeout) {
clearTimeout(this.healTimeout)
this.healTimeout = null
}
try {
this.client.healNetwork()
debug('Network auto heal started')
} catch (error) {
debug('Error while doing scheduled network heal', error.message)
}
// schedule next
this.scheduleHeal()
}
/**
* Used to Update an hass device of a specific node
*
* @param {Object} hassDevice The Hass device
* @param {Integer} nodeId The nodeid
* @param {Boolean} deleteDevice True to remove the hass device from node hass devices
*/
ZwaveClient.prototype.updateDevice = function (
hassDevice,
nodeId,
deleteDevice
) {
var node = nodeId >= 0 ? this.nodes[nodeId] : null
// check for existing node and node hassdevice with given id
if (node && hassDevice.id && node.hassDevices[hassDevice.id]) {
if (deleteDevice) {
delete node.hassDevices[hassDevice.id]
} else {
var id = hassDevice.id
delete hassDevice.id
node.hassDevices[id] = hassDevice
}
this.emitEvent('NODE_UPDATED', node)
}
}
/**
* Used to Add a new hass device to a specific node
*
* @param {Object} hassDevice The Hass device
* @param {Integer} nodeId The nodeid
*/
ZwaveClient.prototype.addDevice = function (hassDevice, nodeId) {
var node = nodeId >= 0 ? this.nodes[nodeId] : null
// check for existing node and node hassdevice with given id
if (node && hassDevice.id) {
delete hassDevice.id
const id = hassDevice.type + '_' + hassDevice.object_id
hassDevice.persistent = false
node.hassDevices[id] = hassDevice
this.emitEvent('NODE_UPDATED', node)
}
}
/**
* Used to update hass devices list of a specific node and store them in `nodes.json`
*
* @param {Object} devices List of devices `"<deviceId>" : <deviceObject>`
* @param {*} nodeId The node to send this devices
*/
ZwaveClient.prototype.storeDevices = async function (devices, nodeId, remove) {
var node = this.nodes[nodeId]
if (node) {
for (const id in devices) {
devices[id].persistent = !remove
}
if (remove) {
delete this.zwcfg_nodes[nodeId].hassDevices
} else {
this.zwcfg_nodes[nodeId].hassDevices = devices
}
node.hassDevices = copy(devices)
await jsonStore.put(store.nodes, this.zwcfg_nodes)
this.emitEvent('NODE_UPDATED', node)
}
}
/**
* Method used to close client connection, use this before destroy
*/
ZwaveClient.prototype.close = function () {
if (this.tail) {
this.tail.unwatch()
}
this.status = ZWAVE_STATUS[6]
if (this.commandsTimeout) {
this.stopControllerCommand()
}
if (this.connected && this.client) {
if (this.cfg.saveConfig && typeof this.client.writeConfig === 'function') {
this.client.writeConfig()
}
this.connected = false
this.closed = true
if (this.healTimeout) {
clearTimeout(this.healTimeout)
this.healTimeout = null
}
this.client.removeAllListeners()
this.removeAllListeners()
this.client.disconnect(this.cfg.port)
}
}
ZwaveClient.prototype.getStatus = function () {
var status = {}
status.status = this.connected
status.config = this.cfg
return status
}
/**
* Inits a Zwave node object with give nodeinfo object
* Overrides `name` and `loc` properties and add node specific `hassDevices` using info stored in `nodes.json`
* Calculates node `device_id`
*
* @param {Object} ozwnode The Node Zwave Object
* @param {Object} nodeinfo Node Info Object
*/
ZwaveClient.prototype.initNode = function (ozwnode, nodeinfo) {
var nodeid = ozwnode.node_id
for (var attrname in nodeinfo) {
// Use custom node naming and location
if (attrname === 'name' || attrname === 'loc') {
ozwnode[attrname] = this.zwcfg_nodes[nodeid]
? this.zwcfg_nodes[nodeid][attrname]
: ''
} else {
ozwnode[attrname] = nodeinfo[attrname]
}
}
if (this.zwcfg_nodes[nodeid] && this.zwcfg_nodes[nodeid].hassDevices) {
ozwnode.hassDevices = copy(this.zwcfg_nodes[nodeid].hassDevices)
}
if (!this.zwcfg_nodes[nodeid]) this.zwcfg_nodes[nodeid] = {}
ozwnode.status = NODE_STATUS[4] // sleeping
ozwnode.available = true
var deviceID = getDeviceID(ozwnode)
ozwnode.device_id = deviceID
ozwnode.basic_device_class = this.client.getNodeBasic(nodeid)
ozwnode.generic_device_class = this.client.getNodeGeneric(nodeid)
ozwnode.specific_device_class = this.client.getNodeSpecific(nodeid)
// if scan is complete update node groups (for nodes added 'on fly')
if (this.scanComplete) {
this.getGroups(nodeid)
ozwnode.neighborns = this.client.getNodeNeighbors(nodeid)
}
}
/**
* Used to replace `null` nodes in nodes Array
*
*/
ZwaveClient.prototype.addEmptyNodes = function () {
for (var i = 0; i < this.nodes.length; i++) {
if (!this.nodes[i]) {
this.nodes[i] = {
node_id: i,
type: i === 0 ? 'Main controller' : '',
status: i === 0 ? '' : 'Removed',
name: this.zwcfg_nodes[i] ? this.zwcfg_nodes[i].name : '',
loc: this.zwcfg_nodes[i] ? this.zwcfg_nodes[i].loc : '',
failed: true,
values: {}
}
}
}
}
/**
* Popolate node `groups` property by creating an array of groups `{text: <groupLabel>, value: <groupIndex>}`
*
* @param {Integer} nodeID Zwave node id
*/
ZwaveClient.prototype.getGroups = function (nodeID) {
if (this.nodes[nodeID]) {
var numGrups = this.client.getNumGroups(nodeID)
for (var n = 0; n < numGrups; n++) {
var label = this.client.getGroupLabel(nodeID, n + 1)
this.nodes[nodeID].groups.push({
text: label,
value: n + 1
})
}
}
}
/**
* Refresh all nodes neighborns
*
* @returns The nodes array where `node_id` is the array index and the value is the array
* of neighburns of that `node_id`
*/
ZwaveClient.prototype.refreshNeighborns = function () {
for (let i = 0; i < this.nodes.length; i++) {
if (!this.nodes[i].failed) {
this.nodes[i].neighborns = this.client.getNodeNeighbors(i)
}
}
return this.nodes.map(n => n.neighborns)
}
/**
* Method used to start Zwave connection using configuration `port`
*/
ZwaveClient.prototype.connect = function () {
if (!this.connected) {
debug('Connecting to', this.cfg.port)
this.client.connect(this.cfg.port)
this.connected = true
} else {
debug('Client already connected to', this.cfg.port)
}
}
/**